PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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/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 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 (char *dbname, 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

#define BACKEND_TYPE_ALL   0x000F /* OR of all the above */
#define BACKEND_TYPE_AUTOVAC   0x0002 /* autovacuum worker process */

Definition at line 143 of file postmaster.c.

Referenced by pmdie(), and StartAutovacuumWorker().

#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */

Definition at line 145 of file postmaster.c.

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

#define BACKEND_TYPE_NORMAL   0x0001 /* normal backend */
#define BACKEND_TYPE_WALSND   0x0004 /* walsender process */

Definition at line 144 of file postmaster.c.

Referenced by CountChildren(), and SignalSomeChildren().

#define BACKEND_TYPE_WORKER   (BACKEND_TYPE_AUTOVAC | BACKEND_TYPE_BGWORKER)

Definition at line 148 of file postmaster.c.

Referenced by PostmasterStateMachine().

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

Definition at line 553 of file postmaster.c.

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

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

Definition at line 554 of file postmaster.c.

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

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

Definition at line 555 of file postmaster.c.

Referenced by reaper().

#define FastShutdown   2

Definition at line 271 of file postmaster.c.

Referenced by pmdie().

#define ImmediateShutdown   3

Definition at line 272 of file postmaster.c.

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

#define MAX_BGWORKERS_TO_LAUNCH   100

Referenced by maybe_start_bgworkers().

#define MAXLISTEN   64
#define NoShutdown   0
#define OPTS_FILE   "postmaster.opts"

Referenced by CreateOptsFile().

#define PgArchStartupAllowed ( )
Value:
#define XLogArchivingAlways()
Definition: xlog.h:138
static PMState pmState
Definition: postmaster.c:338
#define XLogArchivingActive()
Definition: xlog.h:135

Definition at line 441 of file postmaster.c.

Referenced by reaper(), and ServerLoop().

#define SIGKILL_CHILDREN_AFTER_SECS   5

Definition at line 345 of file postmaster.c.

Referenced by DetermineSleepTime(), and ServerLoop().

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

Definition at line 424 of file postmaster.c.

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

#define SmartShutdown   1

Definition at line 270 of file postmaster.c.

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

#define StartBackgroundWriter ( )    StartChildProcess(BgWriterProcess)

Definition at line 547 of file postmaster.c.

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

#define StartCheckpointer ( )    StartChildProcess(CheckpointerProcess)

Definition at line 548 of file postmaster.c.

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

#define StartupDataBase ( )    StartChildProcess(StartupProcess)

Definition at line 546 of file postmaster.c.

Referenced by PostmasterMain(), and PostmasterStateMachine().

#define StartWalReceiver ( )    StartChildProcess(WalReceiverProcess)

Definition at line 550 of file postmaster.c.

Referenced by MaybeStartWalReceiver().

#define StartWalWriter ( )    StartChildProcess(WalWriterProcess)

Definition at line 549 of file postmaster.c.

Referenced by reaper(), and ServerLoop().

Typedef Documentation

Enumeration Type Documentation

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

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

Definition at line 258 of file postmaster.c.

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

Function Documentation

static bool assign_backendlist_entry ( RegisteredBgWorker rw)
static

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

5764 {
5765  Backend *bn;
5766 
5767  /*
5768  * Compute the cancel key that will be assigned to this session. We
5769  * probably don't need cancel keys for background workers, but we'd better
5770  * have something random in the field to prevent unfriendly people from
5771  * sending cancels to them.
5772  */
5774  {
5775  ereport(LOG,
5776  (errcode(ERRCODE_INTERNAL_ERROR),
5777  errmsg("could not generate random cancel key")));
5778  return false;
5779  }
5780 
5781  bn = malloc(sizeof(Backend));
5782  if (bn == NULL)
5783  {
5784  ereport(LOG,
5785  (errcode(ERRCODE_OUT_OF_MEMORY),
5786  errmsg("out of memory")));
5787  return false;
5788  }
5789 
5790  bn->cancel_key = MyCancelKey;
5793  bn->dead_end = false;
5794  bn->bgworker_notify = false;
5795 
5796  rw->rw_backend = bn;
5797  rw->rw_child_slot = bn->child_slot;
5798 
5799  return true;
5800 }
struct bkend * rw_backend
int errcode(int sqlerrcode)
Definition: elog.c:575
#define LOG
Definition: elog.h:26
bool bgworker_notify
Definition: postmaster.c:179
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:169
bool dead_end
Definition: postmaster.c:178
#define ereport(elevel, rest)
Definition: elog.h:122
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:145
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:5199
int child_slot
Definition: postmaster.c:170
int bkend_type
Definition: postmaster.c:177
int MyPMChildSlot
Definition: globals.c:43
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void BackendInitialize ( Port port)
static

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

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

Definition at line 4298 of file postmaster.c.

References Assert, av, Port::database_name, DEBUG3, ereport, errmsg_internal(), ExtraOptions, i, MemoryContextAlloc(), MemoryContextSwitchTo(), MyProcPid, pg_split_opts(), PostgresMain(), progname, random_seed, random_start_time, Port::SessionStartTime, srandom(), TimestampDifference(), TopMemoryContext, and Port::user_name.

Referenced by BackendStartup().

4299 {
4300  char **av;
4301  int maxac;
4302  int ac;
4303  long secs;
4304  int usecs;
4305  int i;
4306 
4307  /*
4308  * Don't want backend to be able to see the postmaster random number
4309  * generator state. We have to clobber the static random_seed *and* start
4310  * a new random sequence in the random() library function.
4311  */
4312 #ifndef HAVE_STRONG_RANDOM
4313  random_seed = 0;
4314  random_start_time.tv_usec = 0;
4315 #endif
4316  /* slightly hacky way to convert timestamptz into integers */
4317  TimestampDifference(0, port->SessionStartTime, &secs, &usecs);
4318  srandom((unsigned int) (MyProcPid ^ (usecs << 12) ^ secs));
4319 
4320  /*
4321  * Now, build the argv vector that will be given to PostgresMain.
4322  *
4323  * The maximum possible number of commandline arguments that could come
4324  * from ExtraOptions is (strlen(ExtraOptions) + 1) / 2; see
4325  * pg_split_opts().
4326  */
4327  maxac = 2; /* for fixed args supplied below */
4328  maxac += (strlen(ExtraOptions) + 1) / 2;
4329 
4330  av = (char **) MemoryContextAlloc(TopMemoryContext,
4331  maxac * sizeof(char *));
4332  ac = 0;
4333 
4334  av[ac++] = "postgres";
4335 
4336  /*
4337  * Pass any backend switches specified with -o on the postmaster's own
4338  * command line. We assume these are secure.
4339  */
4340  pg_split_opts(av, &ac, ExtraOptions);
4341 
4342  av[ac] = NULL;
4343 
4344  Assert(ac < maxac);
4345 
4346  /*
4347  * Debug: print arguments being passed to backend
4348  */
4349  ereport(DEBUG3,
4350  (errmsg_internal("%s child[%d]: starting with (",
4351  progname, (int) getpid())));
4352  for (i = 0; i < ac; ++i)
4353  ereport(DEBUG3,
4354  (errmsg_internal("\t%s", av[i])));
4355  ereport(DEBUG3,
4356  (errmsg_internal(")")));
4357 
4358  /*
4359  * Make sure we aren't in PostmasterContext anymore. (We can't delete it
4360  * just yet, though, because InitPostgres will need the HBA data.)
4361  */
4363 
4364  PostgresMain(ac, av, port->database_name, port->user_name);
4365 }
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:373
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:220
#define Assert(condition)
Definition: c.h:681
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:374
static int BackendStartup ( Port port)
static

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

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

Definition at line 5586 of file postmaster.c.

References BlockSig, and PG_SETMASK.

5587 {
5588  PG_SETMASK(&BlockSig);
5589 }
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
sigset_t BlockSig
Definition: pqsignal.c:22
void BackgroundWorkerInitializeConnection ( char *  dbname,
char *  username 
)

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

5541 {
5543 
5544  /* XXX is this the right errcode? */
5546  ereport(FATAL,
5547  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5548  errmsg("database connection requirement not indicated during registration")));
5549 
5551 
5552  /* it had better not gotten out of "init" mode yet */
5553  if (!IsInitProcessingMode())
5554  ereport(ERROR,
5555  (errmsg("invalid processing mode in background worker")));
5557 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define SetProcessingMode(mode)
Definition: miscadmin.h:373
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:189
#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
void BackgroundWorkerInitializeConnectionByOid ( Oid  dboid,
Oid  useroid 
)

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

5564 {
5566 
5567  /* XXX is this the right errcode? */
5569  ereport(FATAL,
5570  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5571  errmsg("database connection requirement not indicated during registration")));
5572 
5573  InitPostgres(NULL, dboid, NULL, useroid, NULL);
5574 
5575  /* it had better not gotten out of "init" mode yet */
5576  if (!IsInitProcessingMode())
5577  ereport(ERROR,
5578  (errmsg("invalid processing mode in background worker")));
5580 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define SetProcessingMode(mode)
Definition: miscadmin.h:373
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:189
#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
void BackgroundWorkerUnblockSignals ( void  )

Definition at line 5592 of file postmaster.c.

References PG_SETMASK, and UnBlockSig.

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

5593 {
5595 }
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
sigset_t UnBlockSig
Definition: pqsignal.c:22
static bool bgworker_should_start_now ( BgWorkerStartTime  start_time)
static

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

5720 {
5721  switch (pmState)
5722  {
5723  case PM_NO_CHILDREN:
5724  case PM_WAIT_DEAD_END:
5725  case PM_SHUTDOWN_2:
5726  case PM_SHUTDOWN:
5727  case PM_WAIT_BACKENDS:
5728  case PM_WAIT_READONLY:
5729  case PM_WAIT_BACKUP:
5730  break;
5731 
5732  case PM_RUN:
5734  return true;
5735  /* fall through */
5736 
5737  case PM_HOT_STANDBY:
5739  return true;
5740  /* fall through */
5741 
5742  case PM_RECOVERY:
5743  case PM_STARTUP:
5744  case PM_INIT:
5746  return true;
5747  /* fall through */
5748 
5749  }
5750 
5751  return false;
5752 }
static time_t start_time
Definition: pg_ctl.c:103
static PMState pmState
Definition: postmaster.c:338
static CAC_state canAcceptConnections ( void  )
static

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

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

Definition at line 1477 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, snprintf(), strerror(), ValidatePgVersion(), and write_stderr.

Referenced by PostmasterMain().

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

Definition at line 3198 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, EXIT_STATUS_0, EXIT_STATUS_1, free, HandleChildCrash(), LOG, LogChildExit(), bkend::pid, and ReleasePostmasterChildSlot().

Referenced by reaper().

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

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

3100 {
3101  char namebuf[MAXPGPATH];
3102  slist_mutable_iter iter;
3103 
3105  {
3106  RegisteredBgWorker *rw;
3107 
3108  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
3109 
3110  if (rw->rw_pid != pid)
3111  continue;
3112 
3113 #ifdef WIN32
3114  /* see CleanupBackend */
3115  if (exitstatus == ERROR_WAIT_NO_CHILDREN)
3116  exitstatus = 0;
3117 #endif
3118 
3119  snprintf(namebuf, MAXPGPATH, _("background worker \"%s\""),
3120  rw->rw_worker.bgw_type);
3121 
3122 
3123  if (!EXIT_STATUS_0(exitstatus))
3124  {
3125  /* Record timestamp, so we know when to restart the worker. */
3127  }
3128  else
3129  {
3130  /* Zero exit status means terminate */
3131  rw->rw_crashed_at = 0;
3132  rw->rw_terminate = true;
3133  }
3134 
3135  /*
3136  * Additionally, for shared-memory-connected workers, just like a
3137  * backend, any exit status other than 0 or 1 is considered a crash
3138  * and causes a system-wide restart.
3139  */
3140  if ((rw->rw_worker.bgw_flags & BGWORKER_SHMEM_ACCESS) != 0)
3141  {
3142  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3143  {
3144  HandleChildCrash(pid, exitstatus, namebuf);
3145  return true;
3146  }
3147  }
3148 
3149  /*
3150  * We must release the postmaster child slot whether this worker is
3151  * connected to shared memory or not, but we only treat it as a crash
3152  * if it is in fact connected.
3153  */
3156  {
3157  HandleChildCrash(pid, exitstatus, namebuf);
3158  return true;
3159  }
3160 
3161  /* Get it out of the BackendList and clear out remaining data */
3162  dlist_delete(&rw->rw_backend->elem);
3163 #ifdef EXEC_BACKEND
3164  ShmemBackendArrayRemove(rw->rw_backend);
3165 #endif
3166 
3167  /*
3168  * It's possible that this background worker started some OTHER
3169  * background worker and asked to be notified when that worker started
3170  * or stopped. If so, cancel any notifications destined for the
3171  * now-dead backend.
3172  */
3173  if (rw->rw_backend->bgworker_notify)
3175  free(rw->rw_backend);
3176  rw->rw_backend = NULL;
3177  rw->rw_pid = 0;
3178  rw->rw_child_slot = 0;
3179  ReportBackgroundWorkerExit(&iter); /* report child death */
3180 
3181  LogChildExit(EXIT_STATUS_0(exitstatus) ? DEBUG1 : LOG,
3182  namebuf, pid, exitstatus);
3183 
3184  return true;
3185  }
3186 
3187  return false;
3188 }
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:180
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:52
void BackgroundWorkerStopNotifications(pid_t pid)
Definition: bgworker.c:493
bool bgworker_notify
Definition: postmaster.c:179
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:716
#define EXIT_STATUS_1(st)
Definition: postmaster.c:554
#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:3282
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:91
static void LogChildExit(int lev, const char *procname, int pid, int exitstatus)
Definition: postmaster.c:3538
BackgroundWorker rw_worker
#define _(x)
Definition: elog.c:84
#define EXIT_STATUS_0(st)
Definition: postmaster.c:553
void ClosePostmasterPorts ( bool  am_syslogger)

Definition at line 2451 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 BackendStartup(), do_start_bgworker(), pgarch_start(), pgstat_start(), StartAutoVacLauncher(), StartAutoVacWorker(), StartChildProcess(), and SysLogger_Start().

2452 {
2453  int i;
2454 
2455 #ifndef WIN32
2456 
2457  /*
2458  * Close the write end of postmaster death watch pipe. It's important to
2459  * do this as early as possible, so that if postmaster dies, others won't
2460  * think that it's still running because we're holding the pipe open.
2461  */
2463  ereport(FATAL,
2465  errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
2467 #endif
2468 
2469  /* Close the listen sockets */
2470  for (i = 0; i < MAXLISTEN; i++)
2471  {
2472  if (ListenSocket[i] != PGINVALID_SOCKET)
2473  {
2476  }
2477  }
2478 
2479  /* If using syslogger, close the read side of the pipe */
2480  if (!am_syslogger)
2481  {
2482 #ifndef WIN32
2483  if (syslogPipe[0] >= 0)
2484  close(syslogPipe[0]);
2485  syslogPipe[0] = -1;
2486 #else
2487  if (syslogPipe[0])
2488  CloseHandle(syslogPipe[0]);
2489  syslogPipe[0] = 0;
2490 #endif
2491  }
2492 
2493 #ifdef USE_BONJOUR
2494  /* If using Bonjour, close the connection to the mDNS daemon */
2495  if (bonjour_sdref)
2496  close(DNSServiceRefSockFD(bonjour_sdref));
2497 #endif
2498 }
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:562
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:215
#define PGINVALID_SOCKET
Definition: port.h:24
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
int i
#define close(a)
Definition: win32.h:12
#define MAXLISTEN
Definition: postmaster.c:214
int syslogPipe[2]
Definition: syslogger.c:112
static void CloseServerPorts ( int  status,
Datum  arg 
)
static

Definition at line 1378 of file postmaster.c.

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

Referenced by PostmasterMain().

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

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

2386 {
2387  Port *port;
2388 
2389  if (!(port = (Port *) calloc(1, sizeof(Port))))
2390  {
2391  ereport(LOG,
2392  (errcode(ERRCODE_OUT_OF_MEMORY),
2393  errmsg("out of memory")));
2394  ExitPostmaster(1);
2395  }
2396 
2397  if (StreamConnection(serverFd, port) != STATUS_OK)
2398  {
2399  if (port->sock != PGINVALID_SOCKET)
2400  StreamClose(port->sock);
2401  ConnFree(port);
2402  return NULL;
2403  }
2404 
2405  /*
2406  * Allocate GSSAPI specific state struct
2407  */
2408 #ifndef EXEC_BACKEND
2409 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2410  port->gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
2411  if (!port->gss)
2412  {
2413  ereport(LOG,
2414  (errcode(ERRCODE_OUT_OF_MEMORY),
2415  errmsg("out of memory")));
2416  ExitPostmaster(1);
2417  }
2418 #endif
2419 #endif
2420 
2421  return port;
2422 }
#define calloc(a, b)
Definition: header.h:55
void StreamClose(pgsocket sock)
Definition: pqcomm.c:844
static void ConnFree(Port *port)
Definition: postmaster.c:2429
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:4971
#define ereport(elevel, rest)
Definition: elog.h:122
#define STATUS_OK
Definition: c.h:981
static int port
Definition: pg_regress.c:90
#define PGINVALID_SOCKET
Definition: port.h:24
void * gss
Definition: libpq-be.h:175
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void ConnFree ( Port port)
static

Definition at line 2429 of file postmaster.c.

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

Referenced by ConnCreate(), and ServerLoop().

2430 {
2431 #ifdef USE_SSL
2432  secure_close(conn);
2433 #endif
2434  if (conn->gss)
2435  free(conn->gss);
2436  free(conn);
2437 }
PGconn * conn
Definition: streamutil.c:46
#define free(a)
Definition: header.h:65
void secure_close(Port *port)
Definition: be-secure.c:126
static int CountChildren ( int  target)
static

Definition at line 5240 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, and IsPostmasterChildWalSender().

Referenced by canAcceptConnections(), and PostmasterStateMachine().

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

Definition at line 5490 of file postmaster.c.

References elog, i, LOG, and OPTS_FILE.

Referenced by PostmasterMain().

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

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

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

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

5629 {
5630  pid_t worker_pid;
5631 
5632  Assert(rw->rw_pid == 0);
5633 
5634  /*
5635  * Allocate and assign the Backend element. Note we must do this before
5636  * forking, so that we can handle out of memory properly.
5637  *
5638  * Treat failure as though the worker had crashed. That way, the
5639  * postmaster will wait a bit before attempting to start it again; if it
5640  * tried again right away, most likely it'd find itself repeating the
5641  * out-of-memory or fork failure condition.
5642  */
5643  if (!assign_backendlist_entry(rw))
5644  {
5646  return false;
5647  }
5648 
5649  ereport(DEBUG1,
5650  (errmsg("starting background worker process \"%s\"",
5651  rw->rw_worker.bgw_name)));
5652 
5653 #ifdef EXEC_BACKEND
5654  switch ((worker_pid = bgworker_forkexec(rw->rw_shmem_slot)))
5655 #else
5656  switch ((worker_pid = fork_process()))
5657 #endif
5658  {
5659  case -1:
5660  /* in postmaster, fork failed ... */
5661  ereport(LOG,
5662  (errmsg("could not fork worker process: %m")));
5663  /* undo what assign_backendlist_entry did */
5665  rw->rw_child_slot = 0;
5666  free(rw->rw_backend);
5667  rw->rw_backend = NULL;
5668  /* mark entry as crashed, so we'll try again later */
5670  break;
5671 
5672 #ifndef EXEC_BACKEND
5673  case 0:
5674  /* in postmaster child ... */
5676 
5677  /* Close the postmaster's sockets */
5678  ClosePostmasterPorts(false);
5679 
5680  /*
5681  * Before blowing away PostmasterContext, save this bgworker's
5682  * data where it can find it.
5683  */
5686  memcpy(MyBgworkerEntry, &rw->rw_worker, sizeof(BackgroundWorker));
5687 
5688  /* Release postmaster's working memory context */
5691  PostmasterContext = NULL;
5692 
5694 
5695  exit(1); /* should not get here */
5696  break;
5697 #endif
5698  default:
5699  /* in postmaster, fork successful ... */
5700  rw->rw_pid = worker_pid;
5701  rw->rw_backend->pid = rw->rw_pid;
5703  /* add new worker to lists of backends */
5705 #ifdef EXEC_BACKEND
5706  ShmemBackendArrayAdd(rw->rw_backend);
5707 #endif
5708  return true;
5709  }
5710 
5711  return false;
5712 }
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:189
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:185
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:180
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2451
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:5763
static dlist_head BackendList
Definition: postmaster.c:183
#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:681
pid_t pid
Definition: postmaster.c:168
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
static void dummy_handler ( SIGNAL_ARGS  )
static

Definition at line 5180 of file postmaster.c.

Referenced by PostmasterMain().

5181 {
5182 }
static void ExitPostmaster ( int  status)
static

Definition at line 4971 of file postmaster.c.

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

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

4972 {
4973 #ifdef HAVE_PTHREAD_IS_THREADED_NP
4974 
4975  /*
4976  * There is no known cause for a postmaster to become multithreaded after
4977  * startup. Recheck to account for the possibility of unknown causes.
4978  * This message uses LOG level, because an unclean shutdown at this point
4979  * would usually not look much different from a clean shutdown.
4980  */
4981  if (pthread_is_threaded_np() != 0)
4982  ereport(LOG,
4983  (errcode(ERRCODE_INTERNAL_ERROR),
4984  errmsg_internal("postmaster became multithreaded"),
4985  errdetail("Please report this to <pgsql-bugs@postgresql.org>.")));
4986 #endif
4987 
4988  /* should cleanup shared memory and kill all backends */
4989 
4990  /*
4991  * Not sure of the semantics here. When the Postmaster dies, should the
4992  * backends all be killed? probably not.
4993  *
4994  * MUST -- vadim 05-10-1999
4995  */
4996 
4997  proc_exit(status);
4998 }
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
static void getInstallationPaths ( const char *  argv0)
static

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

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

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

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

Definition at line 1911 of file postmaster.c.

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

Referenced by ServerLoop().

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

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

6389 {
6390 #ifndef WIN32
6391 
6392  /*
6393  * Create a pipe. Postmaster holds the write end of the pipe open
6394  * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
6395  * the read file descriptor to select() to wake up in case postmaster
6396  * dies, or check for postmaster death with a (read() == 0). Children must
6397  * close the write end as soon as possible after forking, because EOF
6398  * won't be signaled in the read end until all processes have closed the
6399  * write fd. That is taken care of in ClosePostmasterPorts().
6400  */
6402  if (pipe(postmaster_alive_fds) < 0)
6403  ereport(FATAL,
6405  errmsg_internal("could not create pipe to monitor postmaster death: %m")));
6406 
6407  /*
6408  * Set O_NONBLOCK to allow testing for the fd's presence with a read()
6409  * call.
6410  */
6411  if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
6412  ereport(FATAL,
6414  errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
6415 #else
6416 
6417  /*
6418  * On Windows, we use a process handle for the same purpose.
6419  */
6420  if (DuplicateHandle(GetCurrentProcess(),
6421  GetCurrentProcess(),
6422  GetCurrentProcess(),
6423  &PostmasterHandle,
6424  0,
6425  TRUE,
6426  DUPLICATE_SAME_ACCESS) == 0)
6427  ereport(FATAL,
6428  (errmsg_internal("could not duplicate postmaster handle: error code %lu",
6429  GetLastError())));
6430 #endif /* WIN32 */
6431 }
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:562
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
#define Assert(condition)
Definition: c.h:681
#define TRUE
Definition: c.h:215
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:42
static void LogChildExit ( int  lev,
const char *  procname,
int  pid,
int  exitstatus 
)
static

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

3539 {
3540  /*
3541  * size of activity_buffer is arbitrary, but set equal to default
3542  * track_activity_query_size
3543  */
3544  char activity_buffer[1024];
3545  const char *activity = NULL;
3546 
3547  if (!EXIT_STATUS_0(exitstatus))
3548  activity = pgstat_get_crashed_backend_activity(pid,
3549  activity_buffer,
3550  sizeof(activity_buffer));
3551 
3552  if (WIFEXITED(exitstatus))
3553  ereport(lev,
3554 
3555  /*------
3556  translator: %s is a noun phrase describing a child process, such as
3557  "server process" */
3558  (errmsg("%s (PID %d) exited with exit code %d",
3559  procname, pid, WEXITSTATUS(exitstatus)),
3560  activity ? errdetail("Failed process was running: %s", activity) : 0));
3561  else if (WIFSIGNALED(exitstatus))
3562 #if defined(WIN32)
3563  ereport(lev,
3564 
3565  /*------
3566  translator: %s is a noun phrase describing a child process, such as
3567  "server process" */
3568  (errmsg("%s (PID %d) was terminated by exception 0x%X",
3569  procname, pid, WTERMSIG(exitstatus)),
3570  errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
3571  activity ? errdetail("Failed process was running: %s", activity) : 0));
3572 #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST
3573  ereport(lev,
3574 
3575  /*------
3576  translator: %s is a noun phrase describing a child process, such as
3577  "server process" */
3578  (errmsg("%s (PID %d) was terminated by signal %d: %s",
3579  procname, pid, WTERMSIG(exitstatus),
3580  WTERMSIG(exitstatus) < NSIG ?
3581  sys_siglist[WTERMSIG(exitstatus)] : "(unknown)"),
3582  activity ? errdetail("Failed process was running: %s", activity) : 0));
3583 #else
3584  ereport(lev,
3585 
3586  /*------
3587  translator: %s is a noun phrase describing a child process, such as
3588  "server process" */
3589  (errmsg("%s (PID %d) was terminated by signal %d",
3590  procname, pid, WTERMSIG(exitstatus)),
3591  activity ? errdetail("Failed process was running: %s", activity) : 0));
3592 #endif
3593  else
3594  ereport(lev,
3595 
3596  /*------
3597  translator: %s is a noun phrase describing a child process, such as
3598  "server process" */
3599  (errmsg("%s (PID %d) exited with unrecognized status %d",
3600  procname, pid, exitstatus),
3601  activity ? errdetail("Failed process was running: %s", activity) : 0));
3602 }
int errhint(const char *fmt,...)
Definition: elog.c:987
#define WIFEXITED(w)
Definition: win32.h:172
#define WIFSIGNALED(w)
Definition: win32.h:173
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
#define WEXITSTATUS(w)
Definition: win32.h:174
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 WTERMSIG(w)
Definition: win32.h:175
#define EXIT_STATUS_0(st)
Definition: postmaster.c:553
int MaxLivePostmasterChildren ( void  )

Definition at line 5530 of file postmaster.c.

References autovacuum_max_workers, max_worker_processes, and MaxConnections.

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

5531 {
5532  return 2 * (MaxConnections + autovacuum_max_workers + 1 +
5534 }
int MaxConnections
Definition: globals.c:123
int autovacuum_max_workers
Definition: autovacuum.c:115
int max_worker_processes
Definition: globals.c:124
static void maybe_start_bgworkers ( void  )
static

Definition at line 5814 of file postmaster.c.

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

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

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

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

5474 {
5475  if (WalReceiverPID == 0 &&
5476  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5478  Shutdown == NoShutdown)
5479  {
5481  WalReceiverRequested = false;
5482  }
5483 }
static pid_t WalReceiverPID
Definition: postmaster.c:251
static volatile sig_atomic_t WalReceiverRequested
Definition: postmaster.c:361
static int Shutdown
Definition: postmaster.c:274
static PMState pmState
Definition: postmaster.c:338
#define NoShutdown
Definition: postmaster.c:269
#define StartWalReceiver()
Definition: postmaster.c:550
static void pmdie ( SIGNAL_ARGS  )
static

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

2597 {
2598  int save_errno = errno;
2599 
2600  PG_SETMASK(&BlockSig);
2601 
2602  ereport(DEBUG2,
2603  (errmsg_internal("postmaster received signal %d",
2604  postgres_signal_arg)));
2605 
2606  switch (postgres_signal_arg)
2607  {
2608  case SIGTERM:
2609 
2610  /*
2611  * Smart Shutdown:
2612  *
2613  * Wait for children to end their work, then shut down.
2614  */
2615  if (Shutdown >= SmartShutdown)
2616  break;
2618  ereport(LOG,
2619  (errmsg("received smart shutdown request")));
2620 
2621  /* Report status */
2623 #ifdef USE_SYSTEMD
2624  sd_notify(0, "STOPPING=1");
2625 #endif
2626 
2627  if (pmState == PM_RUN || pmState == PM_RECOVERY ||
2629  {
2630  /* autovac workers are told to shut down immediately */
2631  /* and bgworkers too; does this need tweaking? */
2632  SignalSomeChildren(SIGTERM,
2634  /* and the autovac launcher too */
2635  if (AutoVacPID != 0)
2636  signal_child(AutoVacPID, SIGTERM);
2637  /* and the bgwriter too */
2638  if (BgWriterPID != 0)
2639  signal_child(BgWriterPID, SIGTERM);
2640  /* and the walwriter too */
2641  if (WalWriterPID != 0)
2642  signal_child(WalWriterPID, SIGTERM);
2643 
2644  /*
2645  * If we're in recovery, we can't kill the startup process
2646  * right away, because at present doing so does not release
2647  * its locks. We might want to change this in a future
2648  * release. For the time being, the PM_WAIT_READONLY state
2649  * indicates that we're waiting for the regular (read only)
2650  * backends to die off; once they do, we'll kill the startup
2651  * and walreceiver processes.
2652  */
2653  pmState = (pmState == PM_RUN) ?
2655  }
2656 
2657  /*
2658  * Now wait for online backup mode to end and backends to exit. If
2659  * that is already the case, PostmasterStateMachine will take the
2660  * next step.
2661  */
2663  break;
2664 
2665  case SIGINT:
2666 
2667  /*
2668  * Fast Shutdown:
2669  *
2670  * Abort all children with SIGTERM (rollback active transactions
2671  * and exit) and shut down when they are gone.
2672  */
2673  if (Shutdown >= FastShutdown)
2674  break;
2676  ereport(LOG,
2677  (errmsg("received fast shutdown request")));
2678 
2679  /* Report status */
2681 #ifdef USE_SYSTEMD
2682  sd_notify(0, "STOPPING=1");
2683 #endif
2684 
2685  if (StartupPID != 0)
2686  signal_child(StartupPID, SIGTERM);
2687  if (BgWriterPID != 0)
2688  signal_child(BgWriterPID, SIGTERM);
2689  if (WalReceiverPID != 0)
2690  signal_child(WalReceiverPID, SIGTERM);
2691  if (pmState == PM_RECOVERY)
2692  {
2694 
2695  /*
2696  * Only startup, bgwriter, walreceiver, possibly bgworkers,
2697  * and/or checkpointer should be active in this state; we just
2698  * signaled the first four, and we don't want to kill
2699  * checkpointer yet.
2700  */
2702  }
2703  else if (pmState == PM_RUN ||
2704  pmState == PM_WAIT_BACKUP ||
2708  {
2709  ereport(LOG,
2710  (errmsg("aborting any active transactions")));
2711  /* shut down all backends and workers */
2712  SignalSomeChildren(SIGTERM,
2715  /* and the autovac launcher too */
2716  if (AutoVacPID != 0)
2717  signal_child(AutoVacPID, SIGTERM);
2718  /* and the walwriter too */
2719  if (WalWriterPID != 0)
2720  signal_child(WalWriterPID, SIGTERM);
2722  }
2723 
2724  /*
2725  * Now wait for backends to exit. If there are none,
2726  * PostmasterStateMachine will take the next step.
2727  */
2729  break;
2730 
2731  case SIGQUIT:
2732 
2733  /*
2734  * Immediate Shutdown:
2735  *
2736  * abort all children with SIGQUIT, wait for them to exit,
2737  * terminate remaining ones with SIGKILL, then exit without
2738  * attempt to properly shut down the data base system.
2739  */
2740  if (Shutdown >= ImmediateShutdown)
2741  break;
2743  ereport(LOG,
2744  (errmsg("received immediate shutdown request")));
2745 
2746  /* Report status */
2748 #ifdef USE_SYSTEMD
2749  sd_notify(0, "STOPPING=1");
2750 #endif
2751 
2754 
2755  /* set stopwatch for them to die */
2756  AbortStartTime = time(NULL);
2757 
2758  /*
2759  * Now wait for backends to exit. If there are none,
2760  * PostmasterStateMachine will take the next step.
2761  */
2763  break;
2764  }
2765 
2767 
2768  errno = save_errno;
2769 }
static void PostmasterStateMachine(void)
Definition: postmaster.c:3611
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1158
static pid_t WalReceiverPID
Definition: postmaster.c:251
static bool SignalSomeChildren(int signal, int targets)
Definition: postmaster.c:3891
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:142
#define LOG
Definition: elog.h:26
#define BACKEND_TYPE_AUTOVAC
Definition: postmaster.c:143
#define SIGQUIT
Definition: win32.h:189
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
static int Shutdown
Definition: postmaster.c:274
static pid_t BgWriterPID
Definition: postmaster.c:248
static pid_t StartupPID
Definition: postmaster.c:247
#define SmartShutdown
Definition: postmaster.c:270
#define DEBUG2
Definition: elog.h:24
static void TerminateChildren(int signal)
Definition: postmaster.c:3935
#define FastShutdown
Definition: postmaster.c:271
sigset_t UnBlockSig
Definition: pqsignal.c:22
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:3865
#define ereport(elevel, rest)
Definition: elog.h:122
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:145
sigset_t BlockSig
Definition: pqsignal.c:22
static PMState pmState
Definition: postmaster.c:338
#define ImmediateShutdown
Definition: postmaster.c:272
static pid_t WalWriterPID
Definition: postmaster.c:250
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
static pid_t AutoVacPID
Definition: postmaster.c:252
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:342
void PostmasterMain ( int  argc,
char *  argv[] 
)

Definition at line 572 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_IRWXG, S_IRWXO, 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().

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

Definition at line 5924 of file postmaster.c.

References bkend::bgworker_notify, dlist_iter::cur, dlist_container, dlist_foreach, and bkend::pid.

Referenced by BackgroundWorkerStateChange().

5925 {
5926  dlist_iter iter;
5927  Backend *bp;
5928 
5929  dlist_foreach(iter, &BackendList)
5930  {
5931  bp = dlist_container(Backend, elem, iter.cur);
5932  if (bp->pid == pid)
5933  {
5934  bp->bgworker_notify = true;
5935  return true;
5936  }
5937  }
5938  return false;
5939 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
bool bgworker_notify
Definition: postmaster.c:179
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static dlist_head BackendList
Definition: postmaster.c:183
dlist_node * cur
Definition: ilist.h:161
pid_t pid
Definition: postmaster.c:168
static void PostmasterStateMachine ( void  )
static

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

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

Definition at line 2270 of file postmaster.c.

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

Referenced by ProcessStartupPacket().

2271 {
2272  CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
2273  int backendPID;
2274  int32 cancelAuthCode;
2275  Backend *bp;
2276 
2277 #ifndef EXEC_BACKEND
2278  dlist_iter iter;
2279 #else
2280  int i;
2281 #endif
2282 
2283  backendPID = (int) pg_ntoh32(canc->backendPID);
2284  cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode);
2285 
2286  /*
2287  * See if we have a matching backend. In the EXEC_BACKEND case, we can no
2288  * longer access the postmaster's own backend list, and must rely on the
2289  * duplicate array in shared memory.
2290  */
2291 #ifndef EXEC_BACKEND
2292  dlist_foreach(iter, &BackendList)
2293  {
2294  bp = dlist_container(Backend, elem, iter.cur);
2295 #else
2296  for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
2297  {
2298  bp = (Backend *) &ShmemBackendArray[i];
2299 #endif
2300  if (bp->pid == backendPID)
2301  {
2302  if (bp->cancel_key == cancelAuthCode)
2303  {
2304  /* Found a match; signal that backend to cancel current op */
2305  ereport(DEBUG2,
2306  (errmsg_internal("processing cancel request: sending SIGINT to process %d",
2307  backendPID)));
2308  signal_child(bp->pid, SIGINT);
2309  }
2310  else
2311  /* Right PID, wrong key: no way, Jose */
2312  ereport(LOG,
2313  (errmsg("wrong key in cancel request for process %d",
2314  backendPID)));
2315  return;
2316  }
2317  }
2318 
2319  /* No matching backend */
2320  ereport(LOG,
2321  (errmsg("PID %d in cancel request did not match any process",
2322  backendPID)));
2323 }
#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:246
#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:183
#define DEBUG2
Definition: elog.h:24
int32 cancel_key
Definition: postmaster.c:169
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:3865
#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:5530
pid_t pid
Definition: postmaster.c:168
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
static int ProcessStartupPacket ( Port port,
bool  SSLdone 
)
static

Definition at line 1946 of file postmaster.c.

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

Referenced by BackendInitialize().

1947 {
1948  int32 len;
1949  void *buf;
1950  ProtocolVersion proto;
1951  MemoryContext oldcontext;
1952 
1953  pq_startmsgread();
1954  if (pq_getbytes((char *) &len, 4) == EOF)
1955  {
1956  /*
1957  * EOF after SSLdone probably means the client didn't like our
1958  * response to NEGOTIATE_SSL_CODE. That's not an error condition, so
1959  * don't clutter the log with a complaint.
1960  */
1961  if (!SSLdone)
1963  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1964  errmsg("incomplete startup packet")));
1965  return STATUS_ERROR;
1966  }
1967 
1968  len = pg_ntoh32(len);
1969  len -= 4;
1970 
1971  if (len < (int32) sizeof(ProtocolVersion) ||
1973  {
1975  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1976  errmsg("invalid length of startup packet")));
1977  return STATUS_ERROR;
1978  }
1979 
1980  /*
1981  * Allocate at least the size of an old-style startup packet, plus one
1982  * extra byte, and make sure all are zeroes. This ensures we will have
1983  * null termination of all strings, in both fixed- and variable-length
1984  * packet layouts.
1985  */
1986  if (len <= (int32) sizeof(StartupPacket))
1987  buf = palloc0(sizeof(StartupPacket) + 1);
1988  else
1989  buf = palloc0(len + 1);
1990 
1991  if (pq_getbytes(buf, len) == EOF)
1992  {
1994  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1995  errmsg("incomplete startup packet")));
1996  return STATUS_ERROR;
1997  }
1998  pq_endmsgread();
1999 
2000  /*
2001  * The first field is either a protocol version number or a special
2002  * request code.
2003  */
2004  port->proto = proto = pg_ntoh32(*((ProtocolVersion *) buf));
2005 
2006  if (proto == CANCEL_REQUEST_CODE)
2007  {
2008  processCancelRequest(port, buf);
2009  /* Not really an error, but we don't want to proceed further */
2010  return STATUS_ERROR;
2011  }
2012 
2013  if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
2014  {
2015  char SSLok;
2016 
2017 #ifdef USE_SSL
2018  /* No SSL when disabled or on Unix sockets */
2019  if (!LoadedSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
2020  SSLok = 'N';
2021  else
2022  SSLok = 'S'; /* Support for SSL */
2023 #else
2024  SSLok = 'N'; /* No support for SSL */
2025 #endif
2026 
2027 retry1:
2028  if (send(port->sock, &SSLok, 1, 0) != 1)
2029  {
2030  if (errno == EINTR)
2031  goto retry1; /* if interrupted, just retry */
2033  (