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/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 checkDataDir (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)
 
void BackgroundWorkerInitializeConnectionByOid (Oid dboid, Oid useroid)
 
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 144 of file postmaster.c.

Referenced by pmdie(), and StartAutovacuumWorker().

◆ BACKEND_TYPE_BGWORKER

#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */

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

Referenced by PostmasterStateMachine().

◆ EXIT_STATUS_0

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

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

Referenced by reaper().

◆ FastShutdown

#define FastShutdown   2

Definition at line 272 of file postmaster.c.

Referenced by pmdie().

◆ ImmediateShutdown

#define ImmediateShutdown   3

Definition at line 273 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:339
#define XLogArchivingActive()
Definition: xlog.h:135

Definition at line 443 of file postmaster.c.

Referenced by reaper(), and ServerLoop().

◆ SIGKILL_CHILDREN_AFTER_SECS

#define SIGKILL_CHILDREN_AFTER_SECS   5

Definition at line 346 of file postmaster.c.

Referenced by DetermineSleepTime(), and ServerLoop().

◆ SignalChildren

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

Definition at line 426 of file postmaster.c.

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

◆ SmartShutdown

#define SmartShutdown   1

Definition at line 271 of file postmaster.c.

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

◆ StartBackgroundWriter

#define StartBackgroundWriter ( )    StartChildProcess(BgWriterProcess)

Definition at line 549 of file postmaster.c.

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

◆ StartCheckpointer

#define StartCheckpointer ( )    StartChildProcess(CheckpointerProcess)

Definition at line 550 of file postmaster.c.

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

◆ StartupDataBase

#define StartupDataBase ( )    StartChildProcess(StartupProcess)

Definition at line 548 of file postmaster.c.

Referenced by PostmasterMain(), and PostmasterStateMachine().

◆ StartWalReceiver

#define StartWalReceiver ( )    StartChildProcess(WalReceiverProcess)

Definition at line 552 of file postmaster.c.

Referenced by MaybeStartWalReceiver().

◆ StartWalWriter

#define StartWalWriter ( )    StartChildProcess(WalWriterProcess)

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

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

◆ StartupStatusEnum

Enumerator
STARTUP_NOT_RUNNING 
STARTUP_RUNNING 
STARTUP_SIGNALED 
STARTUP_CRASHED 

Definition at line 259 of file postmaster.c.

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

Function Documentation

◆ assign_backendlist_entry()

static bool assign_backendlist_entry ( RegisteredBgWorker rw)
static

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

5812 {
5813  Backend *bn;
5814 
5815  /*
5816  * Compute the cancel key that will be assigned to this session. We
5817  * probably don't need cancel keys for background workers, but we'd better
5818  * have something random in the field to prevent unfriendly people from
5819  * sending cancels to them.
5820  */
5822  {
5823  ereport(LOG,
5824  (errcode(ERRCODE_INTERNAL_ERROR),
5825  errmsg("could not generate random cancel key")));
5826  return false;
5827  }
5828 
5829  bn = malloc(sizeof(Backend));
5830  if (bn == NULL)
5831  {
5832  ereport(LOG,
5833  (errcode(ERRCODE_OUT_OF_MEMORY),
5834  errmsg("out of memory")));
5835  return false;
5836  }
5837 
5838  bn->cancel_key = MyCancelKey;
5841  bn->dead_end = false;
5842  bn->bgworker_notify = false;
5843 
5844  rw->rw_backend = bn;
5845  rw->rw_child_slot = bn->child_slot;
5846 
5847  return true;
5848 }
struct bkend * rw_backend
int errcode(int sqlerrcode)
Definition: elog.c:575
#define LOG
Definition: elog.h:26
bool bgworker_notify
Definition: postmaster.c:180
int AssignPostmasterChildSlot(void)
Definition: pmsignal.c:151
#define malloc(a)
Definition: header.h:50
int32 MyCancelKey
Definition: globals.c:42
int32 cancel_key
Definition: postmaster.c:170
bool dead_end
Definition: postmaster.c:179
#define ereport(elevel, rest)
Definition: elog.h:122
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:146
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:5247
int child_slot
Definition: postmaster.c:171
int bkend_type
Definition: postmaster.c:178
int MyPMChildSlot
Definition: globals.c:43
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ BackendInitialize()

static void BackendInitialize ( Port port)
static

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

4167 {
4168  int status;
4169  int ret;
4170  char remote_host[NI_MAXHOST];
4171  char remote_port[NI_MAXSERV];
4172  char remote_ps_data[NI_MAXHOST];
4173 
4174  /* Save port etc. for ps status */
4175  MyProcPort = port;
4176 
4177  /*
4178  * PreAuthDelay is a debugging aid for investigating problems in the
4179  * authentication cycle: it can be set in postgresql.conf to allow time to
4180  * attach to the newly-forked backend with a debugger. (See also
4181  * PostAuthDelay, which we allow clients to pass through PGOPTIONS, but it
4182  * is not honored until after authentication.)
4183  */
4184  if (PreAuthDelay > 0)
4185  pg_usleep(PreAuthDelay * 1000000L);
4186 
4187  /* This flag will remain set until InitPostgres finishes authentication */
4188  ClientAuthInProgress = true; /* limit visibility of log messages */
4189 
4190  /* save process start time */
4193 
4194  /* set these to empty in case they are needed before we set them up */
4195  port->remote_host = "";
4196  port->remote_port = "";
4197 
4198  /*
4199  * Initialize libpq and enable reporting of ereport errors to the client.
4200  * Must do this now because authentication uses libpq to send messages.
4201  */
4202  pq_init(); /* initialize libpq to talk to client */
4203  whereToSendOutput = DestRemote; /* now safe to ereport to client */
4204 
4205  /*
4206  * We arrange for a simple exit(1) if we receive SIGTERM or SIGQUIT or
4207  * timeout while trying to collect the startup packet. Otherwise the
4208  * postmaster cannot shutdown the database FAST or IMMED cleanly if a
4209  * buggy client fails to send the packet promptly. XXX it follows that
4210  * the remainder of this function must tolerate losing control at any
4211  * instant. Likewise, any pg_on_exit_callback registered before or during
4212  * this function must be prepared to execute at any instant between here
4213  * and the end of this function. Furthermore, affected callbacks execute
4214  * partially or not at all when a second exit-inducing signal arrives
4215  * after proc_exit_prepare() decrements on_proc_exit_index. (Thanks to
4216  * that mechanic, callbacks need not anticipate more than one call.) This
4217  * is fragile; it ought to instead follow the norm of handling interrupts
4218  * at selected, safe opportunities.
4219  */
4220  pqsignal(SIGTERM, startup_die);
4222  InitializeTimeouts(); /* establishes SIGALRM handler */
4224 
4225  /*
4226  * Get the remote host name and port for logging and status display.
4227  */
4228  remote_host[0] = '\0';
4229  remote_port[0] = '\0';
4230  if ((ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
4231  remote_host, sizeof(remote_host),
4232  remote_port, sizeof(remote_port),
4233  (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV)) != 0)
4234  ereport(WARNING,
4235  (errmsg_internal("pg_getnameinfo_all() failed: %s",
4236  gai_strerror(ret))));
4237  if (remote_port[0] == '\0')
4238  snprintf(remote_ps_data, sizeof(remote_ps_data), "%s", remote_host);
4239  else
4240  snprintf(remote_ps_data, sizeof(remote_ps_data), "%s(%s)", remote_host, remote_port);
4241 
4242  /*
4243  * Save remote_host and remote_port in port structure (after this, they
4244  * will appear in log_line_prefix data for log messages).
4245  */
4246  port->remote_host = strdup(remote_host);
4247  port->remote_port = strdup(remote_port);
4248 
4249  /* And now we can issue the Log_connections message, if wanted */
4250  if (Log_connections)
4251  {
4252  if (remote_port[0])
4253  ereport(LOG,
4254  (errmsg("connection received: host=%s port=%s",
4255  remote_host,
4256  remote_port)));
4257  else
4258  ereport(LOG,
4259  (errmsg("connection received: host=%s",
4260  remote_host)));
4261  }
4262 
4263  /*
4264  * If we did a reverse lookup to name, we might as well save the results
4265  * rather than possibly repeating the lookup during authentication.
4266  *
4267  * Note that we don't want to specify NI_NAMEREQD above, because then we'd
4268  * get nothing useful for a client without an rDNS entry. Therefore, we
4269  * must check whether we got a numeric IPv4 or IPv6 address, and not save
4270  * it into remote_hostname if so. (This test is conservative and might
4271  * sometimes classify a hostname as numeric, but an error in that
4272  * direction is safe; it only results in a possible extra lookup.)
4273  */
4274  if (log_hostname &&
4275  ret == 0 &&
4276  strspn(remote_host, "0123456789.") < strlen(remote_host) &&
4277  strspn(remote_host, "0123456789ABCDEFabcdef:") < strlen(remote_host))
4278  port->remote_hostname = strdup(remote_host);
4279 
4280  /*
4281  * Ready to begin client interaction. We will give up and exit(1) after a
4282  * time delay, so that a broken client can't hog a connection
4283  * indefinitely. PreAuthDelay and any DNS interactions above don't count
4284  * against the time limit.
4285  *
4286  * Note: AuthenticationTimeout is applied here while waiting for the
4287  * startup packet, and then again in InitPostgres for the duration of any
4288  * authentication operations. So a hostile client could tie up the
4289  * process for nearly twice AuthenticationTimeout before we kick him off.
4290  *
4291  * Note: because PostgresMain will call InitializeTimeouts again, the
4292  * registration of STARTUP_PACKET_TIMEOUT will be lost. This is okay
4293  * since we never use it again after this function.
4294  */
4297 
4298  /*
4299  * Receive the startup packet (which might turn out to be a cancel request
4300  * packet).
4301  */
4302  status = ProcessStartupPacket(port, false);
4303 
4304  /*
4305  * Stop here if it was bad or a cancel packet. ProcessStartupPacket
4306  * already did any appropriate error reporting.
4307  */
4308  if (status != STATUS_OK)
4309  proc_exit(0);
4310 
4311  /*
4312  * Now that we have the user and database name, we can set the process
4313  * title for ps. It's good to do this as early as possible in startup.
4314  *
4315  * For a walsender, the ps display is set in the following form:
4316  *
4317  * postgres: walsender <user> <host> <activity>
4318  *
4319  * To achieve that, we pass "walsender" as username and username as dbname
4320  * to init_ps_display(). XXX: should add a new variant of
4321  * init_ps_display() to avoid abusing the parameters like this.
4322  */
4323  if (am_walsender)
4325  update_process_title ? "authentication" : "");
4326  else
4327  init_ps_display(port->user_name, port->database_name, remote_ps_data,
4328  update_process_title ? "authentication" : "");
4329 
4330  /*
4331  * Disable the timeout, and prevent SIGTERM/SIGQUIT again.
4332  */
4334  PG_SETMASK(&BlockSig);
4335 }
void InitializeTimeouts(void)
Definition: timeout.c:340
#define SIGQUIT
Definition: win32_port.h:164
static void startup_die(SIGNAL_ARGS)
Definition: postmaster.c:5213
#define NI_NUMERICHOST
Definition: getaddrinfo.h:78
struct Port * MyProcPort
Definition: globals.c:41
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:4044
pg_time_t MyStartTime
Definition: globals.c:40
struct sockaddr_storage addr
Definition: pqcomm.h:64
void proc_exit(int code)
Definition: ipc.c:99
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:240
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
#define gai_strerror
Definition: getaddrinfo.h:146
int AuthenticationTimeout
Definition: postmaster.c:237
char * remote_hostname
Definition: libpq-be.h:124
bool ClientAuthInProgress
Definition: postmaster.c:350
SockAddr raddr
Definition: libpq-be.h:122
bool am_walsender
Definition: walsender.c:114
void pg_usleep(long microsec)
Definition: signal.c:53
void pq_init(void)
Definition: pqcomm.c:194
#define NI_MAXHOST
Definition: getaddrinfo.h:88
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:953
bool log_hostname
Definition: postmaster.c:239
static int port
Definition: pg_regress.c:90
#define WARNING
Definition: elog.h:40
static int ProcessStartupPacket(Port *port, bool SSLdone)
Definition: postmaster.c:1948
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:236
char * remote_host
Definition: libpq-be.h:123
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void StartupPacketTimeoutHandler(void)
Definition: postmaster.c:5237
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:525
CommandDest whereToSendOutput
Definition: postgres.c:88
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 4346 of file postmaster.c.

References AllocateFile(), Assert, AutoVacLauncherMain(), AutoVacWorkerMain(), AuxiliaryProcessMain(), av, BackendInitialize(), BlockSig, calloc, 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, malloc, MAXPGPATH, MemoryContextAlloc(), MemoryContextSwitchTo(), mkdir, 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(), S_IRWXU, secure_initialize(), Port::SessionStartTime, set_stack_base(), snprintf(), srandom(), StartBackgroundWorker(), SysLoggerMain(), TimestampDifference(), TopMemoryContext, TRUE, UsedShmemSegAddr, Port::user_name, and whereToSendOutput.

Referenced by BackendStartup().

4347 {
4348  char **av;
4349  int maxac;
4350  int ac;
4351  long secs;
4352  int usecs;
4353  int i;
4354 
4355  /*
4356  * Don't want backend to be able to see the postmaster random number
4357  * generator state. We have to clobber the static random_seed *and* start
4358  * a new random sequence in the random() library function.
4359  */
4360 #ifndef HAVE_STRONG_RANDOM
4361  random_seed = 0;
4362  random_start_time.tv_usec = 0;
4363 #endif
4364  /* slightly hacky way to convert timestamptz into integers */
4365  TimestampDifference(0, port->SessionStartTime, &secs, &usecs);
4366  srandom((unsigned int) (MyProcPid ^ (usecs << 12) ^ secs));
4367 
4368  /*
4369  * Now, build the argv vector that will be given to PostgresMain.
4370  *
4371  * The maximum possible number of commandline arguments that could come
4372  * from ExtraOptions is (strlen(ExtraOptions) + 1) / 2; see
4373  * pg_split_opts().
4374  */
4375  maxac = 2; /* for fixed args supplied below */
4376  maxac += (strlen(ExtraOptions) + 1) / 2;
4377 
4378  av = (char **) MemoryContextAlloc(TopMemoryContext,
4379  maxac * sizeof(char *));
4380  ac = 0;
4381 
4382  av[ac++] = "postgres";
4383 
4384  /*
4385  * Pass any backend switches specified with -o on the postmaster's own
4386  * command line. We assume these are secure.
4387  */
4388  pg_split_opts(av, &ac, ExtraOptions);
4389 
4390  av[ac] = NULL;
4391 
4392  Assert(ac < maxac);
4393 
4394  /*
4395  * Debug: print arguments being passed to backend
4396  */
4397  ereport(DEBUG3,
4398  (errmsg_internal("%s child[%d]: starting with (",
4399  progname, (int) getpid())));
4400  for (i = 0; i < ac; ++i)
4401  ereport(DEBUG3,
4402  (errmsg_internal("\t%s", av[i])));
4403  ereport(DEBUG3,
4404  (errmsg_internal(")")));
4405 
4406  /*
4407  * Make sure we aren't in PostmasterContext anymore. (We can't delete it
4408  * just yet, though, because InitPostgres will need the HBA data.)
4409  */
4411 
4412  PostgresMain(ac, av, port->database_name, port->user_name);
4413 }
int MyProcPid
Definition: globals.c:39
#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:374
TimestampTz SessionStartTime
Definition: libpq-be.h:151
void PostgresMain(int argc, char *argv[], const char *dbname, const char *username)
Definition: postgres.c:3615
void pg_split_opts(char **argv, int *argcp, const char *optstr)
Definition: postinit.c:437
char * user_name
Definition: libpq-be.h:137
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:43
struct @18::@19 av[32]
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
static char ExtraOptions[MAXPGPATH]
Definition: postmaster.c:221
#define Assert(condition)
Definition: c.h:670
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:706
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:375

◆ BackendStartup()

static int BackendStartup ( Port port)
static

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

4017 {
4018  Backend *bn; /* for backend cleanup */
4019  pid_t pid;
4020 
4021  /*
4022  * Create backend data structure. Better before the fork() so we can
4023  * handle failure cleanly.
4024  */
4025  bn = (Backend *) malloc(sizeof(Backend));
4026  if (!bn)
4027  {
4028  ereport(LOG,
4029  (errcode(ERRCODE_OUT_OF_MEMORY),
4030  errmsg("out of memory")));
4031  return STATUS_ERROR;
4032  }
4033 
4034  /*
4035  * Compute the cancel key that will be assigned to this backend. The
4036  * backend will have its own copy in the forked-off process' value of
4037  * MyCancelKey, so that it can transmit the key to the frontend.
4038  */
4040  {
4041  free(bn);
4042  ereport(LOG,
4043  (errcode(ERRCODE_INTERNAL_ERROR),
4044  errmsg("could not generate random cancel key")));
4045  return STATUS_ERROR;
4046  }
4047 
4048  bn->cancel_key = MyCancelKey;
4049 
4050  /* Pass down canAcceptConnections state */
4052  bn->dead_end = (port->canAcceptConnections != CAC_OK &&
4054 
4055  /*
4056  * Unless it's a dead_end child, assign it a child slot number
4057  */
4058  if (!bn->dead_end)
4060  else
4061  bn->child_slot = 0;
4062 
4063  /* Hasn't asked to be notified about any bgworkers yet */
4064  bn->bgworker_notify = false;
4065 
4066 #ifdef EXEC_BACKEND
4067  pid = backend_forkexec(port);
4068 #else /* !EXEC_BACKEND */
4069  pid = fork_process();
4070  if (pid == 0) /* child */
4071  {
4072  free(bn);
4073 
4074  /* Detangle from postmaster */
4076 
4077  /* Close the postmaster's sockets */
4078  ClosePostmasterPorts(false);
4079 
4080  /* Perform additional initialization and collect startup packet */
4081  BackendInitialize(port);
4082 
4083  /* And run the backend */
4084  BackendRun(port);
4085  }
4086 #endif /* EXEC_BACKEND */
4087 
4088  if (pid < 0)
4089  {
4090  /* in parent, fork failed */
4091  int save_errno = errno;
4092 
4093  if (!bn->dead_end)
4095  free(bn);
4096  errno = save_errno;
4097  ereport(LOG,
4098  (errmsg("could not fork new process for connection: %m")));
4099  report_fork_failure_to_client(port, save_errno);
4100  return STATUS_ERROR;
4101  }
4102 
4103  /* in parent, successful fork */
4104  ereport(DEBUG2,
4105  (errmsg_internal("forked new backend, pid=%d socket=%d",
4106  (int) pid, (int) port->sock)));
4107 
4108  /*
4109  * Everything's been successful, it's safe to add this backend to our list
4110  * of backends.
4111  */
4112  bn->pid = pid;
4113  bn->bkend_type = BACKEND_TYPE_NORMAL; /* Can change later to WALSND */
4115 
4116 #ifdef EXEC_BACKEND
4117  if (!bn->dead_end)
4118  ShmemBackendArrayAdd(bn);
4119 #endif
4120 
4121  return STATUS_OK;
4122 }
CAC_state canAcceptConnections
Definition: libpq-be.h:129
void InitPostmasterChild(void)
Definition: miscinit.c:176
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:4346
pid_t fork_process(void)
Definition: fork_process.c:31
int errcode(int sqlerrcode)
Definition: elog.c:575
#define STATUS_ERROR
Definition: c.h:954
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:185
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:143
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:181
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2499
pgsocket sock
Definition: libpq-be.h:118
bool bgworker_notify
Definition: postmaster.c:180
int AssignPostmasterChildSlot(void)
Definition: pmsignal.c:151
#define malloc(a)
Definition: header.h:50
int32 MyCancelKey
Definition: globals.c:42
static dlist_head BackendList
Definition: postmaster.c:184
#define DEBUG2
Definition: elog.h:24
static void report_fork_failure_to_client(Port *port, int errnum)
Definition: postmaster.c:4133
int32 cancel_key
Definition: postmaster.c:170
bool dead_end
Definition: postmaster.c:179
#define ereport(elevel, rest)
Definition: elog.h:122
#define STATUS_OK
Definition: c.h:953
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:5247
int child_slot
Definition: postmaster.c:171
int bkend_type
Definition: postmaster.c:178
#define free(a)
Definition: header.h:65
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
pid_t pid
Definition: postmaster.c:169
int MyPMChildSlot
Definition: globals.c:43
int errmsg(const char *fmt,...)
Definition: elog.c:797
static CAC_state canAcceptConnections(void)
Definition: postmaster.c:2377
static void BackendInitialize(Port *port)
Definition: postmaster.c:4166

◆ BackgroundWorkerBlockSignals()

void BackgroundWorkerBlockSignals ( void  )

Definition at line 5634 of file postmaster.c.

References BlockSig, and PG_SETMASK.

5635 {
5636  PG_SETMASK(&BlockSig);
5637 }
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
sigset_t BlockSig
Definition: pqsignal.c:22

◆ BackgroundWorkerInitializeConnection()

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

Definition at line 5588 of file postmaster.c.

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

Referenced by ApplyLauncherMain(), and initialize_worker_spi().

5589 {
5591 
5592  /* XXX is this the right errcode? */
5594  ereport(FATAL,
5595  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5596  errmsg("database connection requirement not indicated during registration")));
5597 
5599 
5600  /* it had better not gotten out of "init" mode yet */
5601  if (!IsInitProcessingMode())
5602  ereport(ERROR,
5603  (errmsg("invalid processing mode in background worker")));
5605 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define SetProcessingMode(mode)
Definition: miscadmin.h:373
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:190
#define ERROR
Definition: elog.h:43
#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
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
char * dbname
Definition: streamutil.c:42
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname)
Definition: postinit.c:559
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define IsInitProcessingMode()
Definition: miscadmin.h:368

◆ BackgroundWorkerInitializeConnectionByOid()

void BackgroundWorkerInitializeConnectionByOid ( Oid  dboid,
Oid  useroid 
)

Definition at line 5611 of file postmaster.c.

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

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

5612 {
5614 
5615  /* XXX is this the right errcode? */
5617  ereport(FATAL,
5618  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5619  errmsg("database connection requirement not indicated during registration")));
5620 
5621  InitPostgres(NULL, dboid, NULL, useroid, NULL);
5622 
5623  /* it had better not gotten out of "init" mode yet */
5624  if (!IsInitProcessingMode())
5625  ereport(ERROR,
5626  (errmsg("invalid processing mode in background worker")));
5628 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define SetProcessingMode(mode)
Definition: miscadmin.h:373
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:190
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
#define ereport(elevel, rest)
Definition: elog.h:122
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname)
Definition: postinit.c:559
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define IsInitProcessingMode()
Definition: miscadmin.h:368

◆ BackgroundWorkerUnblockSignals()

void BackgroundWorkerUnblockSignals ( void  )

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

5641 {
5643 }
#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 5767 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().

5768 {
5769  switch (pmState)
5770  {
5771  case PM_NO_CHILDREN:
5772  case PM_WAIT_DEAD_END:
5773  case PM_SHUTDOWN_2:
5774  case PM_SHUTDOWN:
5775  case PM_WAIT_BACKENDS:
5776  case PM_WAIT_READONLY:
5777  case PM_WAIT_BACKUP:
5778  break;
5779 
5780  case PM_RUN:
5782  return true;
5783  /* fall through */
5784 
5785  case PM_HOT_STANDBY:
5787  return true;
5788  /* fall through */
5789 
5790  case PM_RECOVERY:
5791  case PM_STARTUP:
5792  case PM_INIT:
5794  return true;
5795  /* fall through */
5796 
5797  }
5798 
5799  return false;
5800 }
static time_t start_time
Definition: pg_ctl.c:95
static PMState pmState
Definition: postmaster.c:339

◆ canAcceptConnections()

static CAC_state canAcceptConnections ( void  )
static

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

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

◆ checkDataDir()

static void checkDataDir ( void  )
static

Definition at line 1479 of file postmaster.c.

References AllocateFile(), Assert, DataDir, ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg(), ExitPostmaster(), FATAL, FreeFile(), MAXPGPATH, PG_BINARY_R, progname, S_IRWXG, S_IRWXO, S_ISDIR, snprintf(), stat, strerror(), ValidatePgVersion(), and write_stderr.

Referenced by PostmasterMain().

1480 {
1481  char path[MAXPGPATH];
1482  FILE *fp;
1483  struct stat stat_buf;
1484 
1485  Assert(DataDir);
1486 
1487  if (stat(DataDir, &stat_buf) != 0)
1488  {
1489  if (errno == ENOENT)
1490  ereport(FATAL,
1492  errmsg("data directory \"%s\" does not exist",
1493  DataDir)));
1494  else
1495  ereport(FATAL,
1497  errmsg("could not read permissions of directory \"%s\": %m",
1498  DataDir)));
1499  }
1500 
1501  /* eventual chdir would fail anyway, but let's test ... */
1502  if (!S_ISDIR(stat_buf.st_mode))
1503  ereport(FATAL,
1504  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1505  errmsg("specified data directory \"%s\" is not a directory",
1506  DataDir)));
1507 
1508  /*
1509  * Check that the directory belongs to my userid; if not, reject.
1510  *
1511  * This check is an essential part of the interlock that prevents two
1512  * postmasters from starting in the same directory (see CreateLockFile()).
1513  * Do not remove or weaken it.
1514  *
1515  * XXX can we safely enable this check on Windows?
1516  */
1517 #if !defined(WIN32) && !defined(__CYGWIN__)
1518  if (stat_buf.st_uid != geteuid())
1519  ereport(FATAL,
1520  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1521  errmsg("data directory \"%s\" has wrong ownership",
1522  DataDir),
1523  errhint("The server must be started by the user that owns the data directory.")));
1524 #endif
1525 
1526  /*
1527  * Check if the directory has group or world access. If so, reject.
1528  *
1529  * It would be possible to allow weaker constraints (for example, allow
1530  * group access) but we cannot make a general assumption that that is
1531  * okay; for example there are platforms where nearly all users
1532  * customarily belong to the same group. Perhaps this test should be
1533  * configurable.
1534  *
1535  * XXX temporarily suppress check when on Windows, because there may not
1536  * be proper support for Unix-y file permissions. Need to think of a
1537  * reasonable check to apply on Windows.
1538  */
1539 #if !defined(WIN32) && !defined(__CYGWIN__)
1540  if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
1541  ereport(FATAL,
1542  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1543  errmsg("data directory \"%s\" has group or world access",
1544  DataDir),
1545  errdetail("Permissions should be u=rwx (0700).")));
1546 #endif
1547 
1548  /* Look for PG_VERSION before looking for pg_control */
1550 
1551  snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1552 
1553  fp = AllocateFile(path, PG_BINARY_R);
1554  if (fp == NULL)
1555  {
1556  write_stderr("%s: could not find the database system\n"
1557  "Expected to find it in the directory \"%s\",\n"
1558  "but could not open file \"%s\": %s\n",
1559  progname, DataDir, path, strerror(errno));
1560  ExitPostmaster(2);
1561  }
1562  FreeFile(fp);
1563 }
int errhint(const char *fmt,...)
Definition: elog.c:987
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1358
#define write_stderr(str)
Definition: parallel.c:182
int errcode(int sqlerrcode)
Definition: elog.c:575
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:1027
struct stat stat_buf
Definition: pg_standby.c:103
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5019
#define FATAL
Definition: elog.h:52
#define MAXPGPATH
#define S_IRWXG
Definition: win32_port.h:292
int errdetail(const char *fmt,...)
Definition: elog.c:873
int errcode_for_file_access(void)
Definition: elog.c:598
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2342
#define ereport(elevel, rest)
Definition: elog.h:122
#define stat(a, b)
Definition: win32_port.h:266
#define Assert(condition)
Definition: c.h:670
#define S_ISDIR(m)
Definition: win32_port.h:307
int FreeFile(FILE *file)
Definition: fd.c:2534
int errmsg(const char *fmt,...)
Definition: elog.c:797
const char * strerror(int errnum)
Definition: strerror.c:19
char * DataDir
Definition: globals.c:60
#define S_IRWXO
Definition: win32_port.h:304

◆ CleanupBackend()

static void CleanupBackend ( int  pid,
int  exitstatus 
)
static

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

3248 {
3249  dlist_mutable_iter iter;
3250 
3251  LogChildExit(DEBUG2, _("server process"), pid, exitstatus);
3252 
3253  /*
3254  * If a backend dies in an ugly way then we must signal all other backends
3255  * to quickdie. If exit status is zero (normal) or one (FATAL exit), we
3256  * assume everything is all right and proceed to remove the backend from
3257  * the active backend list.
3258  */
3259 
3260 #ifdef WIN32
3261 
3262  /*
3263  * On win32, also treat ERROR_WAIT_NO_CHILDREN (128) as nonfatal case,
3264  * since that sometimes happens under load when the process fails to start
3265  * properly (long before it starts using shared memory). Microsoft reports
3266  * it is related to mutex failure:
3267  * http://archives.postgresql.org/pgsql-hackers/2010-09/msg00790.php
3268  */
3269  if (exitstatus == ERROR_WAIT_NO_CHILDREN)
3270  {
3271  LogChildExit(LOG, _("server process"), pid, exitstatus);
3272  exitstatus = 0;
3273  }
3274 #endif
3275 
3276  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3277  {
3278  HandleChildCrash(pid, exitstatus, _("server process"));
3279  return;
3280  }
3281 
3283  {
3284  Backend *bp = dlist_container(Backend, elem, iter.cur);
3285 
3286  if (bp->pid == pid)
3287  {
3288  if (!bp->dead_end)
3289  {
3291  {
3292  /*
3293  * Uh-oh, the child failed to clean itself up. Treat as a
3294  * crash after all.
3295  */
3296  HandleChildCrash(pid, exitstatus, _("server process"));
3297  return;
3298  }
3299 #ifdef EXEC_BACKEND
3300  ShmemBackendArrayRemove(bp);
3301 #endif
3302  }
3303  if (bp->bgworker_notify)
3304  {
3305  /*
3306  * This backend may have been slated to receive SIGUSR1 when
3307  * some background worker started or stopped. Cancel those
3308  * notifications, as we don't want to signal PIDs that are not
3309  * PostgreSQL backends. This gets skipped in the (probably
3310  * very common) case where the backend has never requested any
3311  * such notifications.
3312  */
3314  }
3315  dlist_delete(iter.cur);
3316  free(bp);
3317  break;
3318  }
3319  }
3320 }
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:180
#define EXIT_STATUS_1(st)
Definition: postmaster.c:556
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static dlist_head BackendList
Definition: postmaster.c:184
#define DEBUG2
Definition: elog.h:24
bool dead_end
Definition: postmaster.c:179
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
int child_slot
Definition: postmaster.c:171
#define free(a)
Definition: header.h:65
pid_t pid
Definition: postmaster.c:169
static void HandleChildCrash(int pid, int exitstatus, const char *procname)
Definition: postmaster.c:3330
static void LogChildExit(int lev, const char *procname, int pid, int exitstatus)
Definition: postmaster.c:3586
#define _(x)
Definition: elog.c:84
#define EXIT_STATUS_0(st)
Definition: postmaster.c:555

◆ CleanupBackgroundWorker()

static bool CleanupBackgroundWorker ( int  pid,
int  exitstatus 
)
static

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

3148 {
3149  char namebuf[MAXPGPATH];
3150  slist_mutable_iter iter;
3151 
3153  {
3154  RegisteredBgWorker *rw;
3155 
3156  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
3157 
3158  if (rw->rw_pid != pid)
3159  continue;
3160 
3161 #ifdef WIN32
3162  /* see CleanupBackend */
3163  if (exitstatus == ERROR_WAIT_NO_CHILDREN)
3164  exitstatus = 0;
3165 #endif
3166 
3167  snprintf(namebuf, MAXPGPATH, _("background worker \"%s\""),
3168  rw->rw_worker.bgw_type);
3169 
3170 
3171  if (!EXIT_STATUS_0(exitstatus))
3172  {
3173  /* Record timestamp, so we know when to restart the worker. */
3175  }
3176  else
3177  {
3178  /* Zero exit status means terminate */
3179  rw->rw_crashed_at = 0;
3180  rw->rw_terminate = true;
3181  }
3182 
3183  /*
3184  * Additionally, for shared-memory-connected workers, just like a
3185  * backend, any exit status other than 0 or 1 is considered a crash
3186  * and causes a system-wide restart.
3187  */
3188  if ((rw->rw_worker.bgw_flags & BGWORKER_SHMEM_ACCESS) != 0)
3189  {
3190  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3191  {
3192  HandleChildCrash(pid, exitstatus, namebuf);
3193  return true;
3194  }
3195  }
3196 
3197  /*
3198  * We must release the postmaster child slot whether this worker is
3199  * connected to shared memory or not, but we only treat it as a crash
3200  * if it is in fact connected.
3201  */
3204  {
3205  HandleChildCrash(pid, exitstatus, namebuf);
3206  return true;
3207  }
3208 
3209  /* Get it out of the BackendList and clear out remaining data */
3210  dlist_delete(&rw->rw_backend->elem);
3211 #ifdef EXEC_BACKEND
3212  ShmemBackendArrayRemove(rw->rw_backend);
3213 #endif
3214 
3215  /*
3216  * It's possible that this background worker started some OTHER
3217  * background worker and asked to be notified when that worker started
3218  * or stopped. If so, cancel any notifications destined for the
3219  * now-dead backend.
3220  */
3221  if (rw->rw_backend->bgworker_notify)
3223  free(rw->rw_backend);
3224  rw->rw_backend = NULL;
3225  rw->rw_pid = 0;
3226  rw->rw_child_slot = 0;
3227  ReportBackgroundWorkerExit(&iter); /* report child death */
3228 
3229  LogChildExit(EXIT_STATUS_0(exitstatus) ? DEBUG1 : LOG,
3230  namebuf, pid, exitstatus);
3231 
3232  return true;
3233  }
3234 
3235  return false;
3236 }
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:181
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:52
void BackgroundWorkerStopNotifications(pid_t pid)
Definition: bgworker.c:493
bool bgworker_notify
Definition: postmaster.c:180
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:716
#define EXIT_STATUS_1(st)
Definition: postmaster.c:556
#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:3330
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:91
static void LogChildExit(int lev, const char *procname, int pid, int exitstatus)
Definition: postmaster.c:3586
BackgroundWorker rw_worker
#define _(x)
Definition: elog.c:84
#define EXIT_STATUS_0(st)
Definition: postmaster.c:555

◆ ClosePostmasterPorts()

void ClosePostmasterPorts ( bool  am_syslogger)

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

2500 {
2501  int i;
2502 
2503 #ifndef WIN32
2504 
2505  /*
2506  * Close the write end of postmaster death watch pipe. It's important to
2507  * do this as early as possible, so that if postmaster dies, others won't
2508  * think that it's still running because we're holding the pipe open.
2509  */
2511  ereport(FATAL,
2513  errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
2515 #endif
2516 
2517  /* Close the listen sockets */
2518  for (i = 0; i < MAXLISTEN; i++)
2519  {
2520  if (ListenSocket[i] != PGINVALID_SOCKET)
2521  {
2524  }
2525  }
2526 
2527  /* If using syslogger, close the read side of the pipe */
2528  if (!am_syslogger)
2529  {
2530 #ifndef WIN32
2531  if (syslogPipe[0] >= 0)
2532  close(syslogPipe[0]);
2533  syslogPipe[0] = -1;
2534 #else
2535  if (syslogPipe[0])
2536  CloseHandle(syslogPipe[0]);
2537  syslogPipe[0] = 0;
2538 #endif
2539  }
2540 
2541 #ifdef USE_BONJOUR
2542  /* If using Bonjour, close the connection to the mDNS daemon */
2543  if (bonjour_sdref)
2544  close(DNSServiceRefSockFD(bonjour_sdref));
2545 #endif
2546 }
void StreamClose(pgsocket sock)
Definition: pqcomm.c:844
#define FATAL
Definition: elog.h:52
bool am_syslogger
Definition: syslogger.c:74
#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:564
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:216
#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:215
int syslogPipe[2]
Definition: syslogger.c:112

◆ CloseServerPorts()

static void CloseServerPorts ( int  status,
Datum  arg 
)
static

Definition at line 1380 of file postmaster.c.

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

Referenced by PostmasterMain().

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

◆ ConnCreate()

static Port * ConnCreate ( int  serverFd)
static

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

2434 {
2435  Port *port;
2436 
2437  if (!(port = (Port *) calloc(1, sizeof(Port))))
2438  {
2439  ereport(LOG,
2440  (errcode(ERRCODE_OUT_OF_MEMORY),
2441  errmsg("out of memory")));
2442  ExitPostmaster(1);
2443  }
2444 
2445  if (StreamConnection(serverFd, port) != STATUS_OK)
2446  {
2447  if (port->sock != PGINVALID_SOCKET)
2448  StreamClose(port->sock);
2449  ConnFree(port);
2450  return NULL;
2451  }
2452 
2453  /*
2454  * Allocate GSSAPI specific state struct
2455  */
2456 #ifndef EXEC_BACKEND
2457 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2458  port->gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
2459  if (!port->gss)
2460  {
2461  ereport(LOG,
2462  (errcode(ERRCODE_OUT_OF_MEMORY),
2463  errmsg("out of memory")));
2464  ExitPostmaster(1);
2465  }
2466 #endif
2467 #endif
2468 
2469  return port;
2470 }
#define calloc(a, b)
Definition: header.h:55
void StreamClose(pgsocket sock)
Definition: pqcomm.c:844
static void ConnFree(Port *port)
Definition: postmaster.c:2477
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:5019
#define ereport(elevel, rest)
Definition: elog.h:122
#define STATUS_OK
Definition: c.h:953
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 2477 of file postmaster.c.

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

Referenced by ConnCreate(), and ServerLoop().

2478 {
2479 #ifdef USE_SSL
2480  secure_close(conn);
2481 #endif
2482  if (conn->gss)
2483  free(conn->gss);
2484  free(conn);
2485 }
PGconn * conn
Definition: streamutil.c:46
#define free(a)
Definition: header.h:65
void secure_close(Port *port)
Definition: be-secure.c:126

◆ CountChildren()

static int CountChildren ( int  target)
static

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

5289 {
5290  dlist_iter iter;
5291  int cnt = 0;
5292 
5293  dlist_foreach(iter, &BackendList)
5294  {
5295  Backend *bp = dlist_container(Backend, elem, iter.cur);
5296 
5297  if (bp->dead_end)
5298  continue;
5299 
5300  /*
5301  * Since target == BACKEND_TYPE_ALL is the most common case, we test
5302  * it first and avoid touching shared memory for every child.
5303  */
5304  if (target != BACKEND_TYPE_ALL)
5305  {
5306  /*
5307  * Assign bkend_type for any recently announced WAL Sender
5308  * processes.
5309  */
5310  if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
5313 
5314  if (!(target & bp->bkend_type))
5315  continue;
5316  }
5317 
5318  cnt++;
5319  }
5320  return cnt;
5321 }
#define BACKEND_TYPE_ALL
Definition: postmaster.c:147
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:143
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static dlist_head BackendList
Definition: postmaster.c:184
#define BACKEND_TYPE_WALSND
Definition: postmaster.c:145
bool dead_end
Definition: postmaster.c:179
int child_slot
Definition: postmaster.c:171
int bkend_type
Definition: postmaster.c:178
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 5538 of file postmaster.c.

References elog, i, LOG, and OPTS_FILE.

Referenced by PostmasterMain().

5539 {
5540  FILE *fp;
5541  int i;
5542 
5543 #define OPTS_FILE "postmaster.opts"
5544 
5545  if ((fp = fopen(OPTS_FILE, "w")) == NULL)
5546  {
5547  elog(LOG, "could not create file \"%s\": %m", OPTS_FILE);
5548  return false;
5549  }
5550 
5551  fprintf(fp, "%s", fullprogname);
5552  for (i = 1; i < argc; i++)
5553  fprintf(fp, " \"%s\"", argv[i]);
5554  fputs("\n", fp);
5555 
5556  if (fclose(fp))
5557  {
5558  elog(LOG, "could not write file \"%s\": %m", OPTS_FILE);
5559  return false;
5560  }
5561 
5562  return true;
5563 }
#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 1575 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().

1576 {
1577  TimestampTz next_wakeup = 0;
1578 
1579  /*
1580  * Normal case: either there are no background workers at all, or we're in
1581  * a shutdown sequence (during which we ignore bgworkers altogether).
1582  */
1583  if (Shutdown > NoShutdown ||
1585  {
1586  if (AbortStartTime != 0)
1587  {
1588  /* time left to abort; clamp to 0 in case it already expired */
1589  timeout->tv_sec = SIGKILL_CHILDREN_AFTER_SECS -
1590  (time(NULL) - AbortStartTime);
1591  timeout->tv_sec = Max(timeout->tv_sec, 0);
1592  timeout->tv_usec = 0;
1593  }
1594  else
1595  {
1596  timeout->tv_sec = 60;
1597  timeout->tv_usec = 0;
1598  }
1599  return;
1600  }
1601 
1602  if (StartWorkerNeeded)
1603  {
1604  timeout->tv_sec = 0;
1605  timeout->tv_usec = 0;
1606  return;
1607  }
1608 
1609  if (HaveCrashedWorker)
1610  {
1611  slist_mutable_iter siter;
1612 
1613  /*
1614  * When there are crashed bgworkers, we sleep just long enough that
1615  * they are restarted when they request to be. Scan the list to
1616  * determine the minimum of all wakeup times according to most recent
1617  * crash time and requested restart interval.
1618  */
1620  {
1621  RegisteredBgWorker *rw;
1622  TimestampTz this_wakeup;
1623 
1624  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
1625 
1626  if (rw->rw_crashed_at == 0)
1627  continue;
1628 
1630  || rw->rw_terminate)
1631  {
1632  ForgetBackgroundWorker(&siter);
1633  continue;
1634  }
1635 
1636  this_wakeup = TimestampTzPlusMilliseconds(rw->rw_crashed_at,
1637  1000L * rw->rw_worker.bgw_restart_time);
1638  if (next_wakeup == 0 || this_wakeup < next_wakeup)
1639  next_wakeup = this_wakeup;
1640  }
1641  }
1642 
1643  if (next_wakeup != 0)
1644  {
1645  long secs;
1646  int microsecs;
1647 
1649  &secs, &microsecs);
1650  timeout->tv_sec = secs;
1651  timeout->tv_usec = microsecs;
1652 
1653  /* Ensure we don't exceed one minute */
1654  if (timeout->tv_sec > 60)
1655  {
1656  timeout->tv_sec = 60;
1657  timeout->tv_usec = 0;
1658  }
1659  }
1660  else
1661  {
1662  timeout->tv_sec = 60;
1663  timeout->tv_usec = 0;
1664  }
1665 }
static volatile bool StartWorkerNeeded
Definition: postmaster.c:365
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:366
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:716
static int Shutdown
Definition: postmaster.c:275
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:346
#define Max(x, y)
Definition: c.h:796
#define NoShutdown
Definition: postmaster.c:270
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:343

◆ do_start_bgworker()

static bool do_start_bgworker ( RegisteredBgWorker rw)
static

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

5677 {
5678  pid_t worker_pid;
5679 
5680  Assert(rw->rw_pid == 0);
5681 
5682  /*
5683  * Allocate and assign the Backend element. Note we must do this before
5684  * forking, so that we can handle out of memory properly.
5685  *
5686  * Treat failure as though the worker had crashed. That way, the
5687  * postmaster will wait a bit before attempting to start it again; if it
5688  * tried again right away, most likely it'd find itself repeating the
5689  * out-of-memory or fork failure condition.
5690  */
5691  if (!assign_backendlist_entry(rw))
5692  {
5694  return false;
5695  }
5696 
5697  ereport(DEBUG1,
5698  (errmsg("starting background worker process \"%s\"",
5699  rw->rw_worker.bgw_name)));
5700 
5701 #ifdef EXEC_BACKEND
5702  switch ((worker_pid = bgworker_forkexec(rw->rw_shmem_slot)))
5703 #else
5704  switch ((worker_pid = fork_process()))
5705 #endif
5706  {
5707  case -1:
5708  /* in postmaster, fork failed ... */
5709  ereport(LOG,
5710  (errmsg("could not fork worker process: %m")));
5711  /* undo what assign_backendlist_entry did */
5713  rw->rw_child_slot = 0;
5714  free(rw->rw_backend);
5715  rw->rw_backend = NULL;
5716  /* mark entry as crashed, so we'll try again later */
5718  break;
5719 
5720 #ifndef EXEC_BACKEND
5721  case 0:
5722  /* in postmaster child ... */
5724 
5725  /* Close the postmaster's sockets */
5726  ClosePostmasterPorts(false);
5727 
5728  /*
5729  * Before blowing away PostmasterContext, save this bgworker's
5730  * data where it can find it.
5731  */
5734  memcpy(MyBgworkerEntry, &rw->rw_worker, sizeof(BackgroundWorker));
5735 
5736  /* Release postmaster's working memory context */
5739  PostmasterContext = NULL;
5740 
5742 
5743  exit(1); /* should not get here */
5744  break;
5745 #endif
5746  default:
5747  /* in postmaster, fork successful ... */
5748  rw->rw_pid = worker_pid;
5749  rw->rw_backend->pid = rw->rw_pid;
5751  /* add new worker to lists of backends */
5753 #ifdef EXEC_BACKEND
5754  ShmemBackendArrayAdd(rw->rw_backend);
5755 #endif
5756  return true;
5757  }
5758 
5759  return false;
5760 }
struct bkend * rw_backend
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
#define DEBUG1
Definition: elog.h:25
void InitPostmasterChild(void)
Definition: miscinit.c:176
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:190
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:185
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:181
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2499
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:5811
static dlist_head BackendList
Definition: postmaster.c:184
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:43
#define free(a)
Definition: header.h:65
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:90
#define Assert(condition)
Definition: c.h:670
pid_t pid
Definition: postmaster.c:169
int errmsg(const char *fmt,...)
Definition: elog.c:797
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:706
BackgroundWorker rw_worker
MemoryContext PostmasterContext
Definition: mcxt.c:45

◆ dummy_handler()

static void dummy_handler ( SIGNAL_ARGS  )
static

Definition at line 5228 of file postmaster.c.

Referenced by PostmasterMain().

5229 {
5230 }

◆ ExitPostmaster()

static void ExitPostmaster ( int  status)
static

Definition at line 5019 of file postmaster.c.

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

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

5020 {
5021 #ifdef HAVE_PTHREAD_IS_THREADED_NP
5022 
5023  /*
5024  * There is no known cause for a postmaster to become multithreaded after
5025  * startup. Recheck to account for the possibility of unknown causes.
5026  * This message uses LOG level, because an unclean shutdown at this point
5027  * would usually not look much different from a clean shutdown.
5028  */
5029  if (pthread_is_threaded_np() != 0)
5030  ereport(LOG,
5031  (errcode(ERRCODE_INTERNAL_ERROR),
5032  errmsg_internal("postmaster became multithreaded"),
5033  errdetail("Please report this to <pgsql-bugs@postgresql.org>.")));
5034 #endif
5035 
5036  /* should cleanup shared memory and kill all backends */
5037 
5038  /*
5039  * Not sure of the semantics here. When the Postmaster dies, should the
5040  * backends all be killed? probably not.
5041  *
5042  * MUST -- vadim 05-10-1999
5043  */
5044 
5045  proc_exit(status);
5046 }
void proc_exit(int code)
Definition: ipc.c:99
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 1428 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().

1429 {
1430  DIR *pdir;
1431 
1432  /* Locate the postgres executable itself */
1433  if (find_my_exec(argv0, my_exec_path) < 0)
1434  elog(FATAL, "%s: could not locate my own executable path", argv0);
1435 
1436 #ifdef EXEC_BACKEND
1437  /* Locate executable backend before we change working directory */
1438  if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1439  postgres_exec_path) < 0)
1440  ereport(FATAL,
1441  (errmsg("%s: could not locate matching postgres executable",
1442  argv0)));
1443 #endif
1444 
1445  /*
1446  * Locate the pkglib directory --- this has to be set early in case we try
1447  * to load any modules from it in response to postgresql.conf entries.
1448  */
1450 
1451  /*
1452  * Verify that there's a readable directory there; otherwise the Postgres
1453  * installation is incomplete or corrupt. (A typical cause of this
1454  * failure is that the postgres executable has been moved or hardlinked to
1455  * some directory that's not a sibling of the installation lib/
1456  * directory.)
1457  */
1458  pdir = AllocateDir(pkglib_path);
1459  if (pdir == NULL)
1460  ereport(ERROR,
1462  errmsg("could not open directory \"%s\": %m",
1463  pkglib_path),
1464  errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1465  my_exec_path)));
1466  FreeDir(pdir);
1467 
1468  /*
1469  * XXX is it worth similarly checking the share/ directory? If the lib/
1470  * directory is there, then share/ probably is too.
1471  */
1472 }
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:93
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:2596
#define ereport(elevel, rest)
Definition: elog.h:122
char my_exec_path[MAXPGPATH]
Definition: globals.c:64
#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:65
int FreeDir(DIR *dir)
Definition: fd.c:2714

◆ HandleChildCrash()

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

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

3331 {
3332  dlist_mutable_iter iter;
3333  slist_iter siter;
3334  Backend *bp;
3335  bool take_action;
3336 
3337  /*
3338  * We only log messages and send signals if this is the first process
3339  * crash and we're not doing an immediate shutdown; otherwise, we're only
3340  * here to update postmaster's idea of live processes. If we have already
3341  * signalled children, nonzero exit status is to be expected, so don't
3342  * clutter log.
3343  */
3344  take_action = !FatalError && Shutdown != ImmediateShutdown;
3345 
3346  if (take_action)
3347  {
3348  LogChildExit(LOG, procname, pid, exitstatus);
3349  ereport(LOG,
3350  (errmsg("terminating any other active server processes")));
3351  }
3352 
3353  /* Process background workers. */
3355  {
3356  RegisteredBgWorker *rw;
3357 
3358  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
3359  if (rw->rw_pid == 0)
3360  continue; /* not running */
3361  if (rw->rw_pid == pid)
3362  {
3363  /*
3364  * Found entry for freshly-dead worker, so remove it.
3365  */
3367  dlist_delete(&rw->rw_backend->elem);
3368 #ifdef EXEC_BACKEND
3369  ShmemBackendArrayRemove(rw->rw_backend);
3370 #endif
3371  free(rw->rw_backend);
3372  rw->rw_backend = NULL;
3373  rw->rw_pid = 0;
3374  rw->rw_child_slot = 0;
3375  /* don't reset crashed_at */
3376  /* don't report child stop, either */
3377  /* Keep looping so we can signal remaining workers */
3378  }
3379  else
3380  {
3381  /*
3382  * This worker is still alive. Unless we did so already, tell it
3383  * to commit hara-kiri.
3384  *
3385  * SIGQUIT is the special signal that says exit without proc_exit
3386  * and let the user know what's going on. But if SendStop is set
3387  * (-s on command line), then we send SIGSTOP instead, so that we
3388  * can get core dumps from all backends by hand.
3389  */
3390  if (take_action)
3391  {
3392  ereport(DEBUG2,
3393  (errmsg_internal("sending %s to process %d",
3394  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3395  (int) rw->rw_pid)));
3397  }
3398  }
3399  }
3400 
3401  /* Process regular backends */
3403  {
3404  bp = dlist_container(Backend, elem, iter.cur);
3405 
3406  if (bp->pid == pid)
3407  {
3408  /*
3409  * Found entry for freshly-dead backend, so remove it.
3410  */
3411  if (!bp->dead_end)
3412  {
3414 #ifdef EXEC_BACKEND
3415  ShmemBackendArrayRemove(bp);
3416 #endif
3417  }
3418  dlist_delete(iter.cur);
3419  free(bp);
3420  /* Keep looping so we can signal remaining backends */
3421  }
3422  else
3423  {
3424  /*
3425  * This backend is still alive. Unless we did so already, tell it
3426  * to commit hara-kiri.
3427  *
3428  * SIGQUIT is the special signal that says exit without proc_exit
3429  * and let the user know what's going on. But if SendStop is set
3430  * (-s on command line), then we send SIGSTOP instead, so that we
3431  * can get core dumps from all backends by hand.
3432  *
3433  * We could exclude dead_end children here, but at least in the
3434  * SIGSTOP case it seems better to include them.
3435  *
3436  * Background workers were already processed above; ignore them
3437  * here.
3438  */
3439  if (bp->bkend_type == BACKEND_TYPE_BGWORKER)
3440  continue;
3441 
3442  if (take_action)
3443  {
3444  ereport(DEBUG2,
3445  (errmsg_internal("sending %s to process %d",
3446  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3447  (int) bp->pid)));
3448  signal_child(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
3449  }
3450  }
3451  }
3452 
3453  /* Take care of the startup process too */
3454  if (pid == StartupPID)
3455  {
3456  StartupPID = 0;
3458  }
3459  else if (StartupPID != 0 && take_action)
3460  {
3461  ereport(DEBUG2,
3462  (errmsg_internal("sending %s to process %d",
3463  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3464  (int) StartupPID)));
3467  }
3468 
3469  /* Take care of the bgwriter too */
3470  if (pid == BgWriterPID)
3471  BgWriterPID = 0;
3472  else if (BgWriterPID != 0 && take_action)
3473  {
3474  ereport(DEBUG2,
3475  (errmsg_internal("sending %s to process %d",
3476  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3477  (int) BgWriterPID)));
3479  }
3480 
3481  /* Take care of the checkpointer too */
3482  if (pid == CheckpointerPID)
3483  CheckpointerPID = 0;
3484  else if (CheckpointerPID != 0 && take_action)
3485  {
3486  ereport(DEBUG2,
3487  (errmsg_internal("sending %s to process %d",
3488  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3489  (int) CheckpointerPID)));
3491  }
3492 
3493  /* Take care of the walwriter too */
3494  if (pid == WalWriterPID)
3495  WalWriterPID = 0;
3496  else if (WalWriterPID != 0 && take_action)
3497  {
3498  ereport(DEBUG2,
3499  (errmsg_internal("sending %s to process %d",
3500  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3501  (int) WalWriterPID)));
3503  }
3504 
3505  /* Take care of the walreceiver too */
3506  if (pid == WalReceiverPID)
3507  WalReceiverPID = 0;
3508  else if (WalReceiverPID != 0 && take_action)
3509  {
3510  ereport(DEBUG2,
3511  (errmsg_internal("sending %s to process %d",
3512  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3513  (int) WalReceiverPID)));
3515  }
3516 
3517  /* Take care of the autovacuum launcher too */
3518  if (pid == AutoVacPID)
3519  AutoVacPID = 0;
3520  else if (AutoVacPID != 0 && take_action)
3521  {
3522  ereport(DEBUG2,
3523  (errmsg_internal("sending %s to process %d",
3524  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3525  (int) AutoVacPID)));
3527  }
3528 
3529  /*
3530  * Force a power-cycle of the pgarch process too. (This isn't absolutely
3531  * necessary, but it seems like a good idea for robustness, and it
3532  * simplifies the state-machine logic in the case where a shutdown request
3533  * arrives during crash processing.)
3534  */
3535  if (PgArchPID != 0 && take_action)
3536  {
3537  ereport(DEBUG2,
3538  (errmsg_internal("sending %s to process %d",
3539  "SIGQUIT",
3540  (int) PgArchPID)));
3542  }
3543 
3544  /*
3545  * Force a power-cycle of the pgstat process too. (This isn't absolutely
3546  * necessary, but it seems like a good idea for robustness, and it
3547  * simplifies the state-machine logic in the case where a shutdown request
3548  * arrives during crash processing.)
3549  */
3550  if (PgStatPID != 0 && take_action)
3551  {
3552  ereport(DEBUG2,
3553  (errmsg_internal("sending %s to process %d",
3554  "SIGQUIT",
3555  (int) PgStatPID)));
3558  }
3559 
3560  /* We do NOT restart the syslogger */
3561 
3562  if (Shutdown != ImmediateShutdown)
3563  FatalError = true;
3564 
3565  /* We now transit into a state of waiting for children to die */
3566  if (pmState == PM_RECOVERY ||
3567  pmState == PM_HOT_STANDBY ||
3568  pmState == PM_RUN ||
3569  pmState == PM_WAIT_BACKUP ||
3571  pmState == PM_SHUTDOWN)
3573 
3574  /*
3575  * .. and if this doesn't happen quickly enough, now the clock is ticking
3576  * for us to kill them without mercy.
3577  */
3578  if (AbortStartTime == 0)
3579  AbortStartTime = time(NULL);
3580 }
struct bkend * rw_backend
#define SIGQUIT
Definition: win32_port.h:164
static StartupStatusEnum StartupStatus
Definition: postmaster.c:267
dlist_node * cur
Definition: ilist.h:180
#define dlist_foreach_modify(iter, lhead)
Definition: ilist.h:524
static pid_t PgStatPID
Definition: postmaster.c:255
slist_node * cur
Definition: ilist.h:226
static pid_t CheckpointerPID
Definition: postmaster.c:250
static pid_t WalReceiverPID
Definition: postmaster.c:252
static bool FatalError
Definition: postmaster.c:277
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:185
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:181
#define SIGSTOP
Definition: win32_port.h:170
static int Shutdown
Definition: postmaster.c:275
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static pid_t BgWriterPID
Definition: postmaster.c:249
static pid_t StartupPID
Definition: postmaster.c:248
static dlist_head BackendList
Definition: postmaster.c:184
slist_head BackgroundWorkerList
Definition: bgworker.c:43
#define DEBUG2
Definition: elog.h:24
bool dead_end
Definition: postmaster.c:179
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:3913
#define ereport(elevel, rest)
Definition: elog.h:122
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:146
int child_slot
Definition: postmaster.c:171
int bkend_type
Definition: postmaster.c:178
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
static PMState pmState
Definition: postmaster.c:339
#define ImmediateShutdown
Definition: postmaster.c:273
#define free(a)
Definition: header.h:65
static pid_t WalWriterPID
Definition: postmaster.c:251
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
pid_t pid
Definition: postmaster.c:169
static pid_t AutoVacPID
Definition: postmaster.c:253
#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:3586
static int SendStop
Definition: postmaster.c:231
static time_t AbortStartTime
Definition: postmaster.c:343
void allow_immediate_pgstat_restart(void)
Definition: pgstat.c:790
static pid_t PgArchPID
Definition: postmaster.c:254

◆ initMasks()

static int initMasks ( fd_set *  rmask)
static

Definition at line 1913 of file postmaster.c.

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

Referenced by ServerLoop().

1914 {
1915  int maxsock = -1;
1916  int i;
1917 
1918  FD_ZERO(rmask);
1919 
1920  for (i = 0; i < MAXLISTEN; i++)
1921  {
1922  int fd = ListenSocket[i];
1923 
1924  if (fd == PGINVALID_SOCKET)
1925  break;
1926  FD_SET(fd, rmask);
1927 
1928  if (fd > maxsock)
1929  maxsock = fd;
1930  }
1931 
1932  return maxsock + 1;
1933 }
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:216
#define PGINVALID_SOCKET
Definition: port.h:33
int i
#define MAXLISTEN
Definition: postmaster.c:215

◆ InitPostmasterDeathWatchHandle()

static void InitPostmasterDeathWatchHandle ( void  )
static

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

6446 {
6447 #ifndef WIN32
6448 
6449  /*
6450  * Create a pipe. Postmaster holds the write end of the pipe open
6451  * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
6452  * the read file descriptor to select() to wake up in case postmaster
6453  * dies, or check for postmaster death with a (read() == 0). Children must
6454  * close the write end as soon as possible after forking, because EOF
6455  * won't be signaled in the read end until all processes have closed the
6456  * write fd. That is taken care of in ClosePostmasterPorts().
6457  */
6459  if (pipe(postmaster_alive_fds) < 0)
6460  ereport(FATAL,
6462  errmsg_internal("could not create pipe to monitor postmaster death: %m")));
6463 
6464  /*
6465  * Set O_NONBLOCK to allow testing for the fd's presence with a read()
6466  * call.
6467  */
6468  if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
6469  ereport(FATAL,
6471  errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
6472 #else
6473 
6474  /*
6475  * On Windows, we use a process handle for the same purpose.
6476  */
6477  if (DuplicateHandle(GetCurrentProcess(),
6478  GetCurrentProcess(),
6479  GetCurrentProcess(),
6480  &PostmasterHandle,
6481  0,
6482  TRUE,
6483  DUPLICATE_SAME_ACCESS) == 0)
6484  ereport(FATAL,
6485  (errmsg_internal("could not duplicate postmaster handle: error code %lu",
6486  GetLastError())));
6487 #endif /* WIN32 */
6488 }
#define TRUE
Definition: ecpglib.h:35
int MyProcPid
Definition: globals.c:39
#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:87
int postmaster_alive_fds[2]
Definition: postmaster.c:564
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
#define Assert(condition)
Definition: c.h:670
#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 3586 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().

3587 {
3588  /*
3589  * size of activity_buffer is arbitrary, but set equal to default
3590  * track_activity_query_size
3591  */
3592  char activity_buffer[1024];
3593  const char *activity = NULL;
3594 
3595  if (!EXIT_STATUS_0(exitstatus))
3596  activity = pgstat_get_crashed_backend_activity(pid,
3597  activity_buffer,
3598  sizeof(activity_buffer));
3599 
3600  if (WIFEXITED(exitstatus))
3601  ereport(lev,
3602 
3603  /*------
3604  translator: %s is a noun phrase describing a child process, such as
3605  "server process" */
3606  (errmsg("%s (PID %d) exited with exit code %d",
3607  procname, pid, WEXITSTATUS(exitstatus)),
3608  activity ? errdetail("Failed process was running: %s", activity) : 0));
3609  else if (WIFSIGNALED(exitstatus))
3610 #if defined(WIN32)
3611  ereport(lev,
3612 
3613  /*------
3614  translator: %s is a noun phrase describing a child process, such as
3615  "server process" */
3616  (errmsg("%s (PID %d) was terminated by exception 0x%X",
3617  procname, pid, WTERMSIG(exitstatus)),
3618  errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
3619  activity ? errdetail("Failed process was running: %s", activity) : 0));
3620 #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST
3621  ereport(lev,
3622 
3623  /*------
3624  translator: %s is a noun phrase describing a child process, such as
3625  "server process" */
3626  (errmsg("%s (PID %d) was terminated by signal %d: %s",
3627  procname, pid, WTERMSIG(exitstatus),
3628  WTERMSIG(exitstatus) < NSIG ?
3629  sys_siglist[WTERMSIG(exitstatus)] : "(unknown)"),
3630  activity ? errdetail("Failed process was running: %s", activity) : 0));
3631 #else
3632  ereport(lev,
3633 
3634  /*------
3635  translator: %s is a noun phrase describing a child process, such as
3636  "server process" */
3637  (errmsg("%s (PID %d) was terminated by signal %d",
3638  procname, pid, WTERMSIG(exitstatus)),
3639  activity ? errdetail("Failed process was running: %s", activity) : 0));
3640 #endif
3641  else
3642  ereport(lev,
3643 
3644  /*------
3645  translator: %s is a noun phrase describing a child process, such as
3646  "server process" */
3647  (errmsg("%s (PID %d) exited with unrecognized status %d",
3648  procname, pid, exitstatus),
3649  activity ? errdetail("Failed process was running: %s", activity) : 0));
3650 }
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:3985
#define WIFSIGNALED(w)
Definition: win32_port.h:148
#define WEXITSTATUS(w)
Definition: win32_port.h:149
#define EXIT_STATUS_0(st)
Definition: postmaster.c:555

◆ MaxLivePostmasterChildren()

int MaxLivePostmasterChildren ( void  )

Definition at line 5578 of file postmaster.c.

References autovacuum_max_workers, max_worker_processes, and MaxConnections.

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

5579 {
5580  return 2 * (MaxConnections + autovacuum_max_workers + 1 +
5582 }
int MaxConnections
Definition: globals.c:123
int autovacuum_max_workers
Definition: autovacuum.c:115
int max_worker_processes
Definition: globals.c:124

◆ maybe_start_bgworkers()

static void maybe_start_bgworkers ( void  )
static

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

5863 {
5864 #define MAX_BGWORKERS_TO_LAUNCH 100
5865  int num_launched = 0;
5866  TimestampTz now = 0;
5867  slist_mutable_iter iter;
5868 
5869  /*
5870  * During crash recovery, we have no need to be called until the state
5871  * transition out of recovery.
5872  */
5873  if (FatalError)
5874  {
5875  StartWorkerNeeded = false;
5876  HaveCrashedWorker = false;
5877  return;
5878  }
5879 
5880  /* Don't need to be called again unless we find a reason for it below */
5881  StartWorkerNeeded = false;
5882  HaveCrashedWorker = false;
5883 
5885  {
5886  RegisteredBgWorker *rw;
5887 
5888  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
5889 
5890  /* ignore if already running */
5891  if (rw->rw_pid != 0)
5892  continue;
5893 
5894  /* if marked for death, clean up and remove from list */
5895  if (rw->rw_terminate)
5896  {
5897  ForgetBackgroundWorker(&iter);
5898  continue;
5899  }
5900 
5901  /*
5902  * If this worker has crashed previously, maybe it needs to be
5903  * restarted (unless on registration it specified it doesn't want to
5904  * be restarted at all). Check how long ago did a crash last happen.
5905  * If the last crash is too recent, don't start it right away; let it
5906  * be restarted once enough time has passed.
5907  */
5908  if (rw->rw_crashed_at != 0)
5909  {
5911  {
5912  int notify_pid;
5913 
5914  notify_pid = rw->rw_worker.bgw_notify_pid;
5915 
5916  ForgetBackgroundWorker(&iter);
5917 
5918  /* Report worker is gone now. */
5919  if (notify_pid != 0)
5920  kill(notify_pid, SIGUSR1);
5921 
5922  continue;
5923  }
5924 
5925  /* read system time only when needed */
5926  if (now == 0)
5927  now = GetCurrentTimestamp();
5928 
5930  rw->rw_worker.bgw_restart_time * 1000))
5931  {
5932  /* Set flag to remember that we have workers to start later */
5933  HaveCrashedWorker = true;
5934  continue;
5935  }
5936  }
5937 
5939  {
5940  /* reset crash time before trying to start worker */
5941  rw->rw_crashed_at = 0;
5942 
5943  /*
5944  * Try to start the worker.
5945  *
5946  * On failure, give up processing workers for now, but set
5947  * StartWorkerNeeded so we'll come back here on the next iteration
5948  * of ServerLoop to try again. (We don't want to wait, because
5949  * there might be additional ready-to-run workers.) We could set
5950  * HaveCrashedWorker as well, since this worker is now marked
5951  * crashed, but there's no need because the next run of this
5952  * function will do that.
5953  */
5954  if (!do_start_bgworker(rw))
5955  {
5956  StartWorkerNeeded = true;
5957  return;
5958  }
5959 
5960  /*
5961  * If we've launched as many workers as allowed, quit, but have
5962  * ServerLoop call us again to look for additional ready-to-run
5963  * workers. There might not be any, but we'll find out the next
5964  * time we run.
5965  */
5966  if (++num_launched >= MAX_BGWORKERS_TO_LAUNCH)
5967  {
5968  StartWorkerNeeded = true;
5969  return;
5970  }
5971  }
5972  }
5973 }
static volatile bool StartWorkerNeeded
Definition: postmaster.c:365
static bool bgworker_should_start_now(BgWorkerStartTime start_time)
Definition: postmaster.c:5767
#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:277
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1649
static volatile bool HaveCrashedWorker
Definition: postmaster.c:366
#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:5676
#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 5521 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().

5522 {
5523  if (WalReceiverPID == 0 &&
5524  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5526  Shutdown == NoShutdown)
5527  {
5529  WalReceiverRequested = false;
5530  }
5531 }
static pid_t WalReceiverPID
Definition: postmaster.c:252
static volatile sig_atomic_t WalReceiverRequested
Definition: postmaster.c:362
static int Shutdown
Definition: postmaster.c:275
static PMState pmState
Definition: postmaster.c:339
#define NoShutdown
Definition: postmaster.c:270
#define StartWalReceiver()
Definition: postmaster.c:552

◆ pmdie()

static void pmdie ( SIGNAL_ARGS  )
static

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

2645 {
2646  int save_errno = errno;
2647 
2648  PG_SETMASK(&BlockSig);
2649 
2650  ereport(DEBUG2,
2651  (errmsg_internal("postmaster received signal %d",
2652  postgres_signal_arg)));
2653 
2654  switch (postgres_signal_arg)
2655  {
2656  case SIGTERM:
2657 
2658  /*
2659  * Smart Shutdown:
2660  *
2661  * Wait for children to end their work, then shut down.
2662  */
2663  if (Shutdown >= SmartShutdown)
2664  break;
2666  ereport(LOG,
2667  (errmsg("received smart shutdown request")));
2668 
2669  /* Report status */
2671 #ifdef USE_SYSTEMD
2672  sd_notify(0, "STOPPING=1");
2673 #endif
2674 
2675  if (pmState == PM_RUN || pmState == PM_RECOVERY ||
2677  {
2678  /* autovac workers are told to shut down immediately */
2679  /* and bgworkers too; does this need tweaking? */
2680  SignalSomeChildren(SIGTERM,
2682  /* and the autovac launcher too */
2683  if (AutoVacPID != 0)
2684  signal_child(AutoVacPID, SIGTERM);
2685  /* and the bgwriter too */
2686  if (BgWriterPID != 0)
2687  signal_child(BgWriterPID, SIGTERM);
2688  /* and the walwriter too */
2689  if (WalWriterPID != 0)
2690  signal_child(WalWriterPID, SIGTERM);
2691 
2692  /*
2693  * If we're in recovery, we can't kill the startup process
2694  * right away, because at present doing so does not release
2695  * its locks. We might want to change this in a future
2696  * release. For the time being, the PM_WAIT_READONLY state
2697  * indicates that we're waiting for the regular (read only)
2698  * backends to die off; once they do, we'll kill the startup
2699  * and walreceiver processes.
2700  */
2701  pmState = (pmState == PM_RUN) ?
2703  }
2704 
2705  /*
2706  * Now wait for online backup mode to end and backends to exit. If
2707  * that is already the case, PostmasterStateMachine will take the
2708  * next step.
2709  */
2711  break;
2712 
2713  case SIGINT:
2714 
2715  /*
2716  * Fast Shutdown:
2717  *
2718  * Abort all children with SIGTERM (rollback active transactions
2719  * and exit) and shut down when they are gone.
2720  */
2721  if (Shutdown >= FastShutdown)
2722  break;
2724  ereport(LOG,
2725  (errmsg("received fast shutdown request")));
2726 
2727  /* Report status */
2729 #ifdef USE_SYSTEMD
2730  sd_notify(0, "STOPPING=1");
2731 #endif
2732 
2733  if (StartupPID != 0)
2734  signal_child(StartupPID, SIGTERM);
2735  if (BgWriterPID != 0)
2736  signal_child(BgWriterPID, SIGTERM);
2737  if (WalReceiverPID != 0)
2738  signal_child(WalReceiverPID, SIGTERM);
2739  if (pmState == PM_RECOVERY)
2740  {
2742 
2743  /*
2744  * Only startup, bgwriter, walreceiver, possibly bgworkers,
2745  * and/or checkpointer should be active in this state; we just
2746  * signaled the first four, and we don't want to kill
2747  * checkpointer yet.
2748  */
2750  }
2751  else if (pmState == PM_RUN ||
2752  pmState == PM_WAIT_BACKUP ||
2756  {
2757  ereport(LOG,
2758  (errmsg("aborting any active transactions")));
2759  /* shut down all backends and workers */
2760  SignalSomeChildren(SIGTERM,
2763  /* and the autovac launcher too */
2764  if (AutoVacPID != 0)
2765  signal_child(AutoVacPID, SIGTERM);
2766  /* and the walwriter too */
2767  if (WalWriterPID != 0)
2768  signal_child(WalWriterPID, SIGTERM);
2770  }
2771 
2772  /*
2773  * Now wait for backends to exit. If there are none,
2774  * PostmasterStateMachine will take the next step.
2775  */
2777  break;
2778 
2779  case SIGQUIT:
2780 
2781  /*
2782  * Immediate Shutdown:
2783  *
2784  * abort all children with SIGQUIT, wait for them to exit,
2785  * terminate remaining ones with SIGKILL, then exit without
2786  * attempt to properly shut down the data base system.
2787  */
2788  if (Shutdown >= ImmediateShutdown)
2789  break;
2791  ereport(LOG,
2792  (errmsg("received immediate shutdown request")));
2793 
2794  /* Report status */
2796 #ifdef USE_SYSTEMD
2797  sd_notify(0, "STOPPING=1");
2798 #endif
2799 
2802 
2803  /* set stopwatch for them to die */
2804  AbortStartTime = time(NULL);
2805 
2806  /*
2807  * Now wait for backends to exit. If there are none,
2808  * PostmasterStateMachine will take the next step.
2809  */
2811  break;
2812  }
2813 
2815 
2816  errno = save_errno;
2817 }
static void PostmasterStateMachine(void)
Definition: postmaster.c:3659
#define SIGQUIT
Definition: win32_port.h:164
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1158
static pid_t WalReceiverPID
Definition: postmaster.c:252
static bool SignalSomeChildren(int signal, int targets)
Definition: postmaster.c:3939
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:143
#define LOG
Definition: elog.h:26
#define BACKEND_TYPE_AUTOVAC
Definition: postmaster.c:144
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
static int Shutdown
Definition: postmaster.c:275
static pid_t BgWriterPID
Definition: postmaster.c:249
static pid_t StartupPID
Definition: postmaster.c:248
#define SmartShutdown
Definition: postmaster.c:271
#define DEBUG2
Definition: elog.h:24
static void TerminateChildren(int signal)
Definition: postmaster.c:3983
#define FastShutdown
Definition: postmaster.c:272
sigset_t UnBlockSig
Definition: pqsignal.c:22
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:3913
#define ereport(elevel, rest)
Definition: elog.h:122
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:146
sigset_t BlockSig
Definition: pqsignal.c:22
static PMState pmState
Definition: postmaster.c:339
#define ImmediateShutdown
Definition: postmaster.c:273
static pid_t WalWriterPID
Definition: postmaster.c:251
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
static pid_t AutoVacPID
Definition: postmaster.c:253
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:343

◆ PostmasterMain()

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

Definition at line 574 of file postmaster.c.

References AddToDataDirLockFile(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), ApplyLauncherRegister(), ARCHIVE_MODE_OFF, Assert, autovac_init(), BlockSig, bonjour_name, ChangeToDataDir(), 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_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_IRWXG, S_IRWXO, 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().

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

◆ PostmasterMarkPIDForWorkerNotify()

bool PostmasterMarkPIDForWorkerNotify ( int  pid)

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

5982 {
5983  dlist_iter iter;
5984  Backend *bp;
5985 
5986  dlist_foreach(iter, &BackendList)
5987  {
5988  bp = dlist_container(Backend, elem, iter.cur);
5989  if (bp->pid == pid)
5990  {
5991  bp->bgworker_notify = true;
5992  return true;
5993  }
5994  }
5995  return false;
5996 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
bool bgworker_notify
Definition: postmaster.c:180
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static dlist_head BackendList
Definition: postmaster.c:184
dlist_node * cur
Definition: ilist.h:161
pid_t pid
Definition: postmaster.c:169

◆ PostmasterStateMachine()

static void PostmasterStateMachine ( void  )
static

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

3660 {
3661  if (pmState == PM_WAIT_BACKUP)
3662  {
3663  /*
3664  * PM_WAIT_BACKUP state ends when online backup mode is not active.
3665  */
3666  if (!BackupInProgress())
3668  }
3669 
3670  if (pmState == PM_WAIT_READONLY)
3671  {
3672  /*
3673  * PM_WAIT_READONLY state ends when we have no regular backends that
3674  * have been started during recovery. We kill the startup and
3675  * walreceiver processes and transition to PM_WAIT_BACKENDS. Ideally,
3676  * we might like to kill these processes first and then wait for
3677  * backends to die off, but that doesn't work at present because
3678  * killing the startup process doesn't release its locks.
3679  */
3681  {
3682  if (StartupPID != 0)
3683  signal_child(StartupPID, SIGTERM);
3684  if (WalReceiverPID != 0)
3685  signal_child(WalReceiverPID, SIGTERM);
3687  }
3688  }
3689 
3690  /*
3691  * If we are in a state-machine state that implies waiting for backends to
3692  * exit, see if they're all gone, and change state if so.
3693  */
3694  if (pmState == PM_WAIT_BACKENDS)
3695  {
3696  /*
3697  * PM_WAIT_BACKENDS state ends when we have no regular backends
3698  * (including autovac workers), no bgworkers (including unconnected
3699  * ones), and no walwriter, autovac launcher or bgwriter. If we are
3700  * doing crash recovery or an immediate shutdown then we expect the
3701  * checkpointer to exit as well, otherwise not. The archiver, stats,
3702  * and syslogger processes are disregarded since they are not
3703  * connected to shared memory; we also disregard dead_end children
3704  * here. Walsenders are also disregarded, they will be terminated
3705  * later after writing the checkpoint record, like the archiver
3706  * process.
3707  */
3709  StartupPID == 0 &&
3710  WalReceiverPID == 0 &&
3711  BgWriterPID == 0 &&
3712  (CheckpointerPID == 0 ||
3714  WalWriterPID == 0 &&
3715  AutoVacPID == 0)
3716  {
3718  {
3719  /*
3720  * Start waiting for dead_end children to die. This state
3721  * change causes ServerLoop to stop creating new ones.
3722  */
3724 
3725  /*
3726  * We already SIGQUIT'd the archiver and stats processes, if
3727  * any, when we started immediate shutdown or entered
3728  * FatalError state.
3729  */
3730  }
3731  else
3732  {
3733  /*
3734  * If we get here, we are proceeding with normal shutdown. All
3735  * the regular children are gone, and it's time to tell the
3736  * checkpointer to do a shutdown checkpoint.
3737  */
3739  /* Start the checkpointer if not running */
3740  if (CheckpointerPID == 0)
3742  /* And tell it to shut down */
3743  if (CheckpointerPID != 0)
3744  {
3746  pmState = PM_SHUTDOWN;
3747  }
3748  else
3749  {
3750  /*
3751  * If we failed to fork a checkpointer, just shut down.
3752  * Any required cleanup will happen at next restart. We
3753  * set FatalError so that an "abnormal shutdown" message
3754  * gets logged when we exit.
3755  */
3756  FatalError = true;
3758 
3759  /* Kill the walsenders, archiver and stats collector too */
3761  if (PgArchPID != 0)
3763  if (PgStatPID != 0)
3765  }
3766  }
3767  }
3768  }
3769 
3770  if (pmState == PM_SHUTDOWN_2)
3771  {
3772  /*
3773  * PM_SHUTDOWN_2 state ends when there's no other children than
3774  * dead_end children left. There shouldn't be any regular backends
3775  * left by now anyway; what we're really waiting for is walsenders and
3776  * archiver.
3777  *
3778  * Walreceiver should normally be dead by now, but not when a fast
3779  * shutdown is performed during recovery.
3780  */
3781  if (PgArchPID == 0 && CountChildren(BACKEND_TYPE_ALL) == 0 &&
3782  WalReceiverPID == 0)
3783  {
3785  }
3786  }
3787 
3788  if (pmState == PM_WAIT_DEAD_END)
3789  {
3790  /*
3791  * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
3792  * (ie, no dead_end children remain), and the archiver and stats
3793  * collector are gone too.
3794  *
3795  * The reason we wait for those two is to protect them against a new
3796  * postmaster starting conflicting subprocesses; this isn't an
3797  * ironclad protection, but it at least helps in the
3798  * shutdown-and-immediately-restart scenario. Note that they have
3799  * already been sent appropriate shutdown signals, either during a
3800  * normal state transition leading up to PM_WAIT_DEAD_END, or during
3801  * FatalError processing.
3802  */
3803  if (dlist_is_empty(&BackendList) &&
3804  PgArchPID == 0 && PgStatPID == 0)
3805  {
3806  /* These other guys should be dead already */
3807  Assert(StartupPID == 0);
3808  Assert(WalReceiverPID == 0);
3809  Assert(BgWriterPID == 0);
3810  Assert(CheckpointerPID == 0);
3811  Assert(WalWriterPID == 0);
3812  Assert(AutoVacPID == 0);
3813  /* syslogger is not considered here */
3815  }
3816  }
3817 
3818  /*
3819  * If we've been told to shut down, we exit as soon as there are no
3820  * remaining children. If there was a crash, cleanup will occur at the
3821  * next startup. (Before PostgreSQL 8.3, we tried to recover from the
3822  * crash before exiting, but that seems unwise if we are quitting because
3823  * we got SIGTERM from init --- there may well not be time for recovery
3824  * before init decides to SIGKILL us.)
3825  *
3826  * Note that the syslogger continues to run. It will exit when it sees
3827  * EOF on its input pipe, which happens when there are no more upstream
3828  * processes.
3829  */
3831  {
3832  if (FatalError)
3833  {
3834  ereport(LOG, (errmsg("abnormal database system shutdown")));
3835  ExitPostmaster(1);
3836  }
3837  else
3838  {
3839  /*
3840  * Terminate exclusive backup mode to avoid recovery after a clean
3841  * fast shutdown. Since an exclusive backup can only be taken
3842  * during normal running (and not, for example, while running
3843  * under Hot Standby) it only makes sense to do this if we reached
3844  * normal running. If we're still in recovery, the backup file is
3845  * one we're recovering *from*, and we must keep it around so that
3846  * recovery restarts from the right place.
3847  */
3849  CancelBackup();
3850 
3851  /* Normal exit from the postmaster is here */
3852  ExitPostmaster(0);
3853  }
3854  }
3855 
3856  /*
3857  * If the startup process failed, or the user does not want an automatic
3858  * restart after backend crashes, wait for all non-syslogger children to
3859  * exit, and then exit postmaster. We don't try to reinitialize when the
3860  * startup process fails, because more than likely it will just fail again
3861  * and we will keep trying forever.
3862  */
3863  if (pmState == PM_NO_CHILDREN &&
3865  ExitPostmaster(1);
3866 
3867  /*
3868  * If we need to recover from a crash, wait for all non-syslogger children
3869  * to exit, then reset shmem and StartupDataBase.
3870  */
3871  if (FatalError && pmState == PM_NO_CHILDREN)
3872  {
3873  ereport(LOG,
3874  (errmsg("all server processes terminated; reinitializing")));
3875 
3876  /* allow background workers to immediately restart */
3878 
3879  shmem_exit(1);
3880 
3881  /* re-read control file into local memory */
3883 
3885 
3887  Assert(StartupPID != 0);
3889  pmState = PM_STARTUP;
3890  /* crash recovery started, reset SIGKILL flag */
3891  AbortStartTime = 0;
3892  }
3893 }
void CancelBackup(void)
Definition: xlog.c:11401
#define SIGQUIT
Definition: win32_port.h:164
static StartupStatusEnum StartupStatus
Definition: postmaster.c:267
#define BACKEND_TYPE_ALL
Definition: postmaster.c:147
#define StartupDataBase()
Definition: postmaster.c:548
static pid_t PgStatPID
Definition: postmaster.c:255
static pid_t CheckpointerPID
Definition: postmaster.c:250
static pid_t WalReceiverPID
Definition: postmaster.c:252
static bool FatalError
Definition: postmaster.c:277
void shmem_exit(int code)
Definition: ipc.c:215
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:143
#define SIGUSR2
Definition: win32_port.h:178
#define LOG
Definition: elog.h:26
bool BackupInProgress(void)
Definition: xlog.c:11381
void ResetBackgroundWorkerCrashTimes(void)
Definition: bgworker.c:515
#define SignalChildren(sig)
Definition: postmaster.c:426
static int Shutdown
Definition: postmaster.c:275
static pid_t BgWriterPID
Definition: postmaster.c:249
#define StartCheckpointer()
Definition: postmaster.c:550
static int CountChildren(int target)
Definition: postmaster.c:5288
static pid_t StartupPID
Definition: postmaster.c:248
int PostPortNumber
Definition: postmaster.c:195
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5019
bool restart_after_crash
Definition: postmaster.c:245
static dlist_head BackendList
Definition: postmaster.c:184
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4831
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:3913
#define ereport(elevel, rest)
Definition: elog.h:122
static PMState pmState
Definition: postmaster.c:339
#define BACKEND_TYPE_WORKER
Definition: postmaster.c:149
#define ImmediateShutdown
Definition: postmaster.c:273
static void reset_shared(int port)
Definition: postmaster.c:2553
static pid_t WalWriterPID
Definition: postmaster.c:251
#define Assert(condition)
Definition: c.h:670
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
#define NoShutdown
Definition: postmaster.c:270
static pid_t AutoVacPID
Definition: postmaster.c:253
int errmsg(const char *fmt,...)
Definition: elog.c:797
static bool ReachedNormalRunning
Definition: postmaster.c:348
static time_t AbortStartTime
Definition: postmaster.c:343
static pid_t PgArchPID
Definition: postmaster.c:254

◆ processCancelRequest()

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

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

2319 {
2320  CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
2321  int backendPID;
2322  int32 cancelAuthCode;
2323  Backend *bp;
2324 
2325 #ifndef EXEC_BACKEND
2326  dlist_iter iter;
2327 #else
2328  int i;
2329 #endif
2330 
2331  backendPID = (int) pg_ntoh32(canc->backendPID);
2332  cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode);
2333 
2334  /*
2335  * See if we have a matching backend. In the EXEC_BACKEND case, we can no
2336  * longer access the postmaster's own backend list, and must rely on the
2337  * duplicate array in shared memory.
2338  */
2339 #ifndef EXEC_BACKEND
2340  dlist_foreach(iter, &BackendList)
2341  {
2342  bp = dlist_container(Backend, elem, iter.cur);
2343 #else
2344  for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
2345  {
2346  bp = (Backend *) &ShmemBackendArray[i];
2347 #endif
2348  if (bp->pid == backendPID)
2349  {
2350  if (bp->cancel_key == cancelAuthCode)
2351  {
2352  /* Found a match; signal that backend to cancel current op */
2353  ereport(DEBUG2,
2354  (errmsg_internal("processing cancel request: sending SIGINT to process %d",
2355  backendPID)));
2356  signal_child(bp->pid, SIGINT);
2357  }
2358  else
2359  /* Right PID, wrong key: no way, Jose */
2360  ereport(LOG,
2361  (errmsg("wrong key in cancel request for process %d",
2362  backendPID)));
2363  return;
2364  }
2365  }
2366 
2367  /* No matching backend */
2368  ereport(LOG,
2369  (errmsg("PID %d in cancel request did not match any process",
2370  backendPID)));
2371 }
#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:284
#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:184
#define DEBUG2
Definition: elog.h:24
int32 cancel_key
Definition: postmaster.c:170
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:3913
#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:5578
pid_t pid
Definition: postmaster.c:169
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i

◆ ProcessStartupPacket()

static int ProcessStartupPacket ( Port port,
bool  SSLdone 
)
static

Definition at line 1948 of file postmaster.c.

References