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 <netinet/in.h>
#include <arpa/inet.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 "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/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 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 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(), PostmasterStateMachine(), 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 548 of file postmaster.c.

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

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

Definition at line 549 of file postmaster.c.

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

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

Definition at line 550 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:137
static PMState pmState
Definition: postmaster.c:338
#define XLogArchivingActive()
Definition: xlog.h:134

Definition at line 436 of file postmaster.c.

Referenced by reaper(), and ServerLoop().

#define SIGKILL_CHILDREN_AFTER_SECS   5

Definition at line 344 of file postmaster.c.

Referenced by DetermineSleepTime(), and ServerLoop().

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

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

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

#define StartCheckpointer ( )    StartChildProcess(CheckpointerProcess)

Definition at line 543 of file postmaster.c.

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

#define StartupDataBase ( )    StartChildProcess(StartupProcess)

Definition at line 541 of file postmaster.c.

Referenced by PostmasterMain(), and PostmasterStateMachine().

#define StartWalReceiver ( )    StartChildProcess(WalReceiverProcess)

Definition at line 545 of file postmaster.c.

Referenced by sigusr1_handler().

#define StartWalWriter ( )    StartChildProcess(WalWriterProcess)

Definition at line 544 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 5693 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, NULL, RandomCancelKey(), RegisteredBgWorker::rw_backend, and RegisteredBgWorker::rw_child_slot.

Referenced by do_start_bgworker().

5694 {
5695  Backend *bn;
5696 
5697  /*
5698  * Compute the cancel key that will be assigned to this session. We
5699  * probably don't need cancel keys for background workers, but we'd better
5700  * have something random in the field to prevent unfriendly people from
5701  * sending cancels to them.
5702  */
5704  {
5705  ereport(LOG,
5706  (errcode(ERRCODE_INTERNAL_ERROR),
5707  errmsg("could not generate random cancel key")));
5708  return false;
5709  }
5710 
5711  bn = malloc(sizeof(Backend));
5712  if (bn == NULL)
5713  {
5714  ereport(LOG,
5715  (errcode(ERRCODE_OUT_OF_MEMORY),
5716  errmsg("out of memory")));
5717  return false;
5718  }
5719 
5720  bn->cancel_key = MyCancelKey;
5723  bn->dead_end = false;
5724  bn->bgworker_notify = false;
5725 
5726  rw->rw_backend = bn;
5727  rw->rw_child_slot = bn->child_slot;
5728 
5729  return true;
5730 }
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:41
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:5147
int child_slot
Definition: postmaster.c:170
int bkend_type
Definition: postmaster.c:177
#define NULL
Definition: c.h:229
int MyPMChildSlot
Definition: globals.c:42
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void BackendInitialize ( Port port)
static

Definition at line 4088 of file postmaster.c.

References SockAddr::addr, am_walsender, AuthenticationTimeout, 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(), 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().

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

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

Referenced by BackendStartup().

4269 {
4270  char **av;
4271  int maxac;
4272  int ac;
4273  long secs;
4274  int usecs;
4275  int i;
4276 
4277  /*
4278  * Don't want backend to be able to see the postmaster random number
4279  * generator state. We have to clobber the static random_seed *and* start
4280  * a new random sequence in the random() library function.
4281  */
4282 #ifndef HAVE_STRONG_RANDOM
4283  random_seed = 0;
4284  random_start_time.tv_usec = 0;
4285 #endif
4286  /* slightly hacky way to convert timestamptz into integers */
4287  TimestampDifference(0, port->SessionStartTime, &secs, &usecs);
4288  srandom((unsigned int) (MyProcPid ^ (usecs << 12) ^ secs));
4289 
4290  /*
4291  * Now, build the argv vector that will be given to PostgresMain.
4292  *
4293  * The maximum possible number of commandline arguments that could come
4294  * from ExtraOptions is (strlen(ExtraOptions) + 1) / 2; see
4295  * pg_split_opts().
4296  */
4297  maxac = 2; /* for fixed args supplied below */
4298  maxac += (strlen(ExtraOptions) + 1) / 2;
4299 
4300  av = (char **) MemoryContextAlloc(TopMemoryContext,
4301  maxac * sizeof(char *));
4302  ac = 0;
4303 
4304  av[ac++] = "postgres";
4305 
4306  /*
4307  * Pass any backend switches specified with -o on the postmaster's own
4308  * command line. We assume these are secure.
4309  */
4310  pg_split_opts(av, &ac, ExtraOptions);
4311 
4312  av[ac] = NULL;
4313 
4314  Assert(ac < maxac);
4315 
4316  /*
4317  * Debug: print arguments being passed to backend
4318  */
4319  ereport(DEBUG3,
4320  (errmsg_internal("%s child[%d]: starting with (",
4321  progname, (int) getpid())));
4322  for (i = 0; i < ac; ++i)
4323  ereport(DEBUG3,
4324  (errmsg_internal("\t%s", av[i])));
4325  ereport(DEBUG3,
4326  (errmsg_internal(")")));
4327 
4328  /*
4329  * Make sure we aren't in PostmasterContext anymore. (We can't delete it
4330  * just yet, though, because InitPostgres will need the HBA data.)
4331  */
4333 
4334  PostgresMain(ac, av, port->database_name, port->user_name);
4335 }
int MyProcPid
Definition: globals.c:38
#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:369
TimestampTz SessionStartTime
Definition: libpq-be.h:151
void PostgresMain(int argc, char *argv[], const char *dbname, const char *username)
Definition: postgres.c:3567
void pg_split_opts(char **argv, int *argcp, const char *optstr)
Definition: postinit.c:436
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
#define NULL
Definition: c.h:229
static char ExtraOptions[MAXPGPATH]
Definition: postmaster.c:220
#define Assert(condition)
Definition: c.h:675
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:707
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:370
static int BackendStartup ( Port port)
static

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

3939 {
3940  Backend *bn; /* for backend cleanup */
3941  pid_t pid;
3942 
3943  /*
3944  * Create backend data structure. Better before the fork() so we can
3945  * handle failure cleanly.
3946  */
3947  bn = (Backend *) malloc(sizeof(Backend));
3948  if (!bn)
3949  {
3950  ereport(LOG,
3951  (errcode(ERRCODE_OUT_OF_MEMORY),
3952  errmsg("out of memory")));
3953  return STATUS_ERROR;
3954  }
3955 
3956  /*
3957  * Compute the cancel key that will be assigned to this backend. The
3958  * backend will have its own copy in the forked-off process' value of
3959  * MyCancelKey, so that it can transmit the key to the frontend.
3960  */
3962  {
3963  free(bn);
3964  ereport(LOG,
3965  (errcode(ERRCODE_INTERNAL_ERROR),
3966  errmsg("could not generate random cancel key")));
3967  return STATUS_ERROR;
3968  }
3969 
3970  bn->cancel_key = MyCancelKey;
3971 
3972  /* Pass down canAcceptConnections state */
3974  bn->dead_end = (port->canAcceptConnections != CAC_OK &&
3976 
3977  /*
3978  * Unless it's a dead_end child, assign it a child slot number
3979  */
3980  if (!bn->dead_end)
3982  else
3983  bn->child_slot = 0;
3984 
3985  /* Hasn't asked to be notified about any bgworkers yet */
3986  bn->bgworker_notify = false;
3987 
3988 #ifdef EXEC_BACKEND
3989  pid = backend_forkexec(port);
3990 #else /* !EXEC_BACKEND */
3991  pid = fork_process();
3992  if (pid == 0) /* child */
3993  {
3994  free(bn);
3995 
3996  /* Detangle from postmaster */
3998 
3999  /* Close the postmaster's sockets */
4000  ClosePostmasterPorts(false);
4001 
4002  /* Perform additional initialization and collect startup packet */
4003  BackendInitialize(port);
4004 
4005  /* And run the backend */
4006  BackendRun(port);
4007  }
4008 #endif /* EXEC_BACKEND */
4009 
4010  if (pid < 0)
4011  {
4012  /* in parent, fork failed */
4013  int save_errno = errno;
4014 
4015  if (!bn->dead_end)
4017  free(bn);
4018  errno = save_errno;
4019  ereport(LOG,
4020  (errmsg("could not fork new process for connection: %m")));
4021  report_fork_failure_to_client(port, save_errno);
4022  return STATUS_ERROR;
4023  }
4024 
4025  /* in parent, successful fork */
4026  ereport(DEBUG2,
4027  (errmsg_internal("forked new backend, pid=%d socket=%d",
4028  (int) pid, (int) port->sock)));
4029 
4030  /*
4031  * Everything's been successful, it's safe to add this backend to our list
4032  * of backends.
4033  */
4034  bn->pid = pid;
4035  bn->bkend_type = BACKEND_TYPE_NORMAL; /* Can change later to WALSND */
4037 
4038 #ifdef EXEC_BACKEND
4039  if (!bn->dead_end)
4040  ShmemBackendArrayAdd(bn);
4041 #endif
4042 
4043  return STATUS_OK;
4044 }
CAC_state canAcceptConnections
Definition: libpq-be.h:129
void InitPostmasterChild(void)
Definition: miscinit.c:175
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:4268
pid_t fork_process(void)
Definition: fork_process.c:31
int errcode(int sqlerrcode)
Definition: elog.c:575
#define STATUS_ERROR
Definition: c.h:976
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:2435
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:41
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:4055
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:975
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:5147
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:42
int errmsg(const char *fmt,...)
Definition: elog.c:797
static CAC_state canAcceptConnections(void)
Definition: postmaster.c:2313
static void BackendInitialize(Port *port)
Definition: postmaster.c:4088
void BackgroundWorkerBlockSignals ( void  )

Definition at line 5516 of file postmaster.c.

References BlockSig, and PG_SETMASK.

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

Definition at line 5470 of file postmaster.c.

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

Referenced by ApplyLauncherMain().

5471 {
5473 
5474  /* XXX is this the right errcode? */
5476  ereport(FATAL,
5477  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5478  errmsg("database connection requirement not indicated during registration")));
5479 
5481 
5482  /* it had better not gotten out of "init" mode yet */
5483  if (!IsInitProcessingMode())
5484  ereport(ERROR,
5485  (errmsg("invalid processing mode in background worker")));
5487 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define SetProcessingMode(mode)
Definition: miscadmin.h:371
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:131
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:229
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
char * dbname
Definition: streamutil.c:38
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname)
Definition: postinit.c:558
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define IsInitProcessingMode()
Definition: miscadmin.h:366
void BackgroundWorkerInitializeConnectionByOid ( Oid  dboid,
Oid  useroid 
)

Definition at line 5493 of file postmaster.c.

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

Referenced by ApplyWorkerMain(), and ParallelWorkerMain().

5494 {
5496 
5497  /* XXX is this the right errcode? */
5499  ereport(FATAL,
5500  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5501  errmsg("database connection requirement not indicated during registration")));
5502 
5503  InitPostgres(NULL, dboid, NULL, useroid, NULL);
5504 
5505  /* it had better not gotten out of "init" mode yet */
5506  if (!IsInitProcessingMode())
5507  ereport(ERROR,
5508  (errmsg("invalid processing mode in background worker")));
5510 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define SetProcessingMode(mode)
Definition: miscadmin.h:371
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 NULL
Definition: c.h:229
#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:558
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define IsInitProcessingMode()
Definition: miscadmin.h:366
void BackgroundWorkerUnblockSignals ( void  )

Definition at line 5522 of file postmaster.c.

References PG_SETMASK, and UnBlockSig.

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

5523 {
5525 }
#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 5649 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().

5650 {
5651  switch (pmState)
5652  {
5653  case PM_NO_CHILDREN:
5654  case PM_WAIT_DEAD_END:
5655  case PM_SHUTDOWN_2:
5656  case PM_SHUTDOWN:
5657  case PM_WAIT_BACKENDS:
5658  case PM_WAIT_READONLY:
5659  case PM_WAIT_BACKUP:
5660  break;
5661 
5662  case PM_RUN:
5664  return true;
5665  /* fall through */
5666 
5667  case PM_HOT_STANDBY:
5669  return true;
5670  /* fall through */
5671 
5672  case PM_RECOVERY:
5673  case PM_STARTUP:
5674  case PM_INIT:
5676  return true;
5677  /* fall through */
5678 
5679  }
5680 
5681  return false;
5682 }
static time_t start_time
Definition: pg_ctl.c:91
static PMState pmState
Definition: postmaster.c:338
static CAC_state canAcceptConnections ( void  )
static

Definition at line 2313 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, result, and Shutdown.

Referenced by BackendStartup(), and StartAutovacuumWorker().

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

Definition at line 1465 of file postmaster.c.

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

Referenced by PostmasterMain().

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

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

3171 {
3172  dlist_mutable_iter iter;
3173 
3174  LogChildExit(DEBUG2, _("server process"), pid, exitstatus);
3175 
3176  /*
3177  * If a backend dies in an ugly way then we must signal all other backends
3178  * to quickdie. If exit status is zero (normal) or one (FATAL exit), we
3179  * assume everything is all right and proceed to remove the backend from
3180  * the active backend list.
3181  */
3182 
3183 #ifdef WIN32
3184 
3185  /*
3186  * On win32, also treat ERROR_WAIT_NO_CHILDREN (128) as nonfatal case,
3187  * since that sometimes happens under load when the process fails to start
3188  * properly (long before it starts using shared memory). Microsoft reports
3189  * it is related to mutex failure:
3190  * http://archives.postgresql.org/pgsql-hackers/2010-09/msg00790.php
3191  */
3192  if (exitstatus == ERROR_WAIT_NO_CHILDREN)
3193  {
3194  LogChildExit(LOG, _("server process"), pid, exitstatus);
3195  exitstatus = 0;
3196  }
3197 #endif
3198 
3199  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3200  {
3201  HandleChildCrash(pid, exitstatus, _("server process"));
3202  return;
3203  }
3204 
3206  {
3207  Backend *bp = dlist_container(Backend, elem, iter.cur);
3208 
3209  if (bp->pid == pid)
3210  {
3211  if (!bp->dead_end)
3212  {
3214  {
3215  /*
3216  * Uh-oh, the child failed to clean itself up. Treat as a
3217  * crash after all.
3218  */
3219  HandleChildCrash(pid, exitstatus, _("server process"));
3220  return;
3221  }
3222 #ifdef EXEC_BACKEND
3223  ShmemBackendArrayRemove(bp);
3224 #endif
3225  }
3226  if (bp->bgworker_notify)
3227  {
3228  /*
3229  * This backend may have been slated to receive SIGUSR1 when
3230  * some background worker started or stopped. Cancel those
3231  * notifications, as we don't want to signal PIDs that are not
3232  * PostgreSQL backends. This gets skipped in the (probably
3233  * very common) case where the backend has never requested any
3234  * such notifications.
3235  */
3237  }
3238  dlist_delete(iter.cur);
3239  free(bp);
3240  break;
3241  }
3242  }
3243 }
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:491
bool bgworker_notify
Definition: postmaster.c:179
#define EXIT_STATUS_1(st)
Definition: postmaster.c:549
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static dlist_head BackendList
Definition: postmaster.c: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:3253
static void LogChildExit(int lev, const char *procname, int pid, int exitstatus)
Definition: postmaster.c:3509
#define _(x)
Definition: elog.c:84
#define EXIT_STATUS_0(st)
Definition: postmaster.c:548
static bool CleanupBackgroundWorker ( int  pid,
int  exitstatus 
)
static

Definition at line 3070 of file postmaster.c.

References _, BackgroundWorkerList, BackgroundWorkerStopNotifications(), BackgroundWorker::bgw_flags, BackgroundWorker::bgw_name, 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, NULL, 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().

3072 {
3073  char namebuf[MAXPGPATH];
3074  slist_mutable_iter iter;
3075 
3077  {
3078  RegisteredBgWorker *rw;
3079 
3080  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
3081 
3082  if (rw->rw_pid != pid)
3083  continue;
3084 
3085 #ifdef WIN32
3086  /* see CleanupBackend */
3087  if (exitstatus == ERROR_WAIT_NO_CHILDREN)
3088  exitstatus = 0;
3089 #endif
3090 
3091  snprintf(namebuf, MAXPGPATH, "%s: %s", _("worker process"),
3092  rw->rw_worker.bgw_name);
3093 
3094  if (!EXIT_STATUS_0(exitstatus))
3095  {
3096  /* Record timestamp, so we know when to restart the worker. */
3098  }
3099  else
3100  {
3101  /* Zero exit status means terminate */
3102  rw->rw_crashed_at = 0;
3103  rw->rw_terminate = true;
3104  }
3105 
3106  /*
3107  * Additionally, for shared-memory-connected workers, just like a
3108  * backend, any exit status other than 0 or 1 is considered a crash
3109  * and causes a system-wide restart.
3110  */
3111  if ((rw->rw_worker.bgw_flags & BGWORKER_SHMEM_ACCESS) != 0)
3112  {
3113  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3114  {
3115  HandleChildCrash(pid, exitstatus, namebuf);
3116  return true;
3117  }
3118  }
3119 
3120  /*
3121  * We must release the postmaster child slot whether this worker is
3122  * connected to shared memory or not, but we only treat it as a crash
3123  * if it is in fact connected.
3124  */
3127  {
3128  HandleChildCrash(pid, exitstatus, namebuf);
3129  return true;
3130  }
3131 
3132  /* Get it out of the BackendList and clear out remaining data */
3133  dlist_delete(&rw->rw_backend->elem);
3134 #ifdef EXEC_BACKEND
3135  ShmemBackendArrayRemove(rw->rw_backend);
3136 #endif
3137 
3138  /*
3139  * It's possible that this background worker started some OTHER
3140  * background worker and asked to be notified when that worker started
3141  * or stopped. If so, cancel any notifications destined for the
3142  * now-dead backend.
3143  */
3144  if (rw->rw_backend->bgworker_notify)
3146  free(rw->rw_backend);
3147  rw->rw_backend = NULL;
3148  rw->rw_pid = 0;
3149  rw->rw_child_slot = 0;
3150  ReportBackgroundWorkerExit(&iter); /* report child death */
3151 
3152  LogChildExit(EXIT_STATUS_0(exitstatus) ? DEBUG1 : LOG,
3153  namebuf, pid, exitstatus);
3154 
3155  return true;
3156  }
3157 
3158  return false;
3159 }
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:457
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:491
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:549
#define MAXPGPATH
slist_head BackgroundWorkerList
Definition: bgworker.c:43
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
#define free(a)
Definition: header.h:65
#define NULL
Definition: c.h:229
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:90
static void HandleChildCrash(int pid, int exitstatus, const char *procname)
Definition: postmaster.c:3253
static void LogChildExit(int lev, const char *procname, int pid, int exitstatus)
Definition: postmaster.c:3509
BackgroundWorker rw_worker
#define _(x)
Definition: elog.c:84
#define EXIT_STATUS_0(st)
Definition: postmaster.c:548
void ClosePostmasterPorts ( bool  am_syslogger)

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

2436 {
2437  int i;
2438 
2439 #ifndef WIN32
2440 
2441  /*
2442  * Close the write end of postmaster death watch pipe. It's important to
2443  * do this as early as possible, so that if postmaster dies, others won't
2444  * think that it's still running because we're holding the pipe open.
2445  */
2447  ereport(FATAL,
2449  errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
2451 #endif
2452 
2453  /* Close the listen sockets */
2454  for (i = 0; i < MAXLISTEN; i++)
2455  {
2456  if (ListenSocket[i] != PGINVALID_SOCKET)
2457  {
2460  }
2461  }
2462 
2463  /* If using syslogger, close the read side of the pipe */
2464  if (!am_syslogger)
2465  {
2466 #ifndef WIN32
2467  if (syslogPipe[0] >= 0)
2468  close(syslogPipe[0]);
2469  syslogPipe[0] = -1;
2470 #else
2471  if (syslogPipe[0])
2472  CloseHandle(syslogPipe[0]);
2473  syslogPipe[0] = 0;
2474 #endif
2475  }
2476 
2477 #ifdef USE_BONJOUR
2478  /* If using Bonjour, close the connection to the mDNS daemon */
2479  if (bonjour_sdref)
2480  close(DNSServiceRefSockFD(bonjour_sdref));
2481 #endif
2482 }
void StreamClose(pgsocket sock)
Definition: pqcomm.c:825
#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:557
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 1366 of file postmaster.c.

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

Referenced by PostmasterMain().

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

Definition at line 2369 of file postmaster.c.

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

Referenced by ServerLoop().

2370 {
2371  Port *port;
2372 
2373  if (!(port = (Port *) calloc(1, sizeof(Port))))
2374  {
2375  ereport(LOG,
2376  (errcode(ERRCODE_OUT_OF_MEMORY),
2377  errmsg("out of memory")));
2378  ExitPostmaster(1);
2379  }
2380 
2381  if (StreamConnection(serverFd, port) != STATUS_OK)
2382  {
2383  if (port->sock != PGINVALID_SOCKET)
2384  StreamClose(port->sock);
2385  ConnFree(port);
2386  return NULL;
2387  }
2388 
2389  /*
2390  * Allocate GSSAPI specific state struct
2391  */
2392 #ifndef EXEC_BACKEND
2393 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2394  port->gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
2395  if (!port->gss)
2396  {
2397  ereport(LOG,
2398  (errcode(ERRCODE_OUT_OF_MEMORY),
2399  errmsg("out of memory")));
2400  ExitPostmaster(1);
2401  }
2402 #endif
2403 #endif
2404 
2405  return port;
2406 }
#define calloc(a, b)
Definition: header.h:55
void StreamClose(pgsocket sock)
Definition: pqcomm.c:825
static void ConnFree(Port *port)
Definition: postmaster.c:2413
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:697
pgsocket sock
Definition: libpq-be.h:118
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:4927
#define ereport(elevel, rest)
Definition: elog.h:122
#define STATUS_OK
Definition: c.h:975
static int port
Definition: pg_regress.c:89
#define PGINVALID_SOCKET
Definition: port.h:24
#define NULL
Definition: c.h:229
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 2413 of file postmaster.c.

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

Referenced by ConnCreate(), and ServerLoop().

2414 {
2415 #ifdef USE_SSL
2416  secure_close(conn);
2417 #endif
2418  if (conn->gss)
2419  free(conn->gss);
2420  free(conn);
2421 }
PGconn * conn
Definition: streamutil.c:42
#define free(a)
Definition: header.h:65
void secure_close(Port *port)
Definition: be-secure.c:125
static int CountChildren ( int  target)
static

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

5189 {
5190  dlist_iter iter;
5191  int cnt = 0;
5192 
5193  dlist_foreach(iter, &BackendList)
5194  {
5195  Backend *bp = dlist_container(Backend, elem, iter.cur);
5196 
5197  if (bp->dead_end)
5198  continue;
5199 
5200  /*
5201  * Since target == BACKEND_TYPE_ALL is the most common case, we test
5202  * it first and avoid touching shared memory for every child.
5203  */
5204  if (target != BACKEND_TYPE_ALL)
5205  {
5206  /*
5207  * Assign bkend_type for any recently announced WAL Sender
5208  * processes.
5209  */
5210  if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
5213 
5214  if (!(target & bp->bkend_type))
5215  continue;
5216  }
5217 
5218  cnt++;
5219  }
5220  return cnt;
5221 }
#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 5420 of file postmaster.c.

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

Referenced by PostmasterMain().

5421 {
5422  FILE *fp;
5423  int i;
5424 
5425 #define OPTS_FILE "postmaster.opts"
5426 
5427  if ((fp = fopen(OPTS_FILE, "w")) == NULL)
5428  {
5429  elog(LOG, "could not create file \"%s\": %m", OPTS_FILE);
5430  return false;
5431  }
5432 
5433  fprintf(fp, "%s", fullprogname);
5434  for (i = 1; i < argc; i++)
5435  fprintf(fp, " \"%s\"", argv[i]);
5436  fputs("\n", fp);
5437 
5438  if (fclose(fp))
5439  {
5440  elog(LOG, "could not write file \"%s\": %m", OPTS_FILE);
5441  return false;
5442  }
5443 
5444  return true;
5445 }
#define LOG
Definition: elog.h:26
#define NULL
Definition: c.h:229
int i
#define elog
Definition: elog.h:219
#define OPTS_FILE
static void DetermineSleepTime ( struct timeval *  timeout)
static

Definition at line 1561 of file postmaster.c.

References AbortStartTime, BackgroundWorkerList, BGW_NEVER_RESTART, BackgroundWorker::bgw_restart_time, slist_mutable_iter::cur, ForgetBackgroundWorker(), GetCurrentTimestamp(), HaveCrashedWorker, Max, NoShutdown, NULL, 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().

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

5559 {
5560  pid_t worker_pid;
5561 
5562  Assert(rw->rw_pid == 0);
5563 
5564  /*
5565  * Allocate and assign the Backend element. Note we must do this before
5566  * forking, so that we can handle out of memory properly.
5567  *
5568  * Treat failure as though the worker had crashed. That way, the
5569  * postmaster will wait a bit before attempting to start it again; if it
5570  * tried again right away, most likely it'd find itself repeating the
5571  * out-of-memory or fork failure condition.
5572  */
5573  if (!assign_backendlist_entry(rw))
5574  {
5576  return false;
5577  }
5578 
5579  ereport(DEBUG1,
5580  (errmsg("starting background worker process \"%s\"",
5581  rw->rw_worker.bgw_name)));
5582 
5583 #ifdef EXEC_BACKEND
5584  switch ((worker_pid = bgworker_forkexec(rw->rw_shmem_slot)))
5585 #else
5586  switch ((worker_pid = fork_process()))
5587 #endif
5588  {
5589  case -1:
5590  /* in postmaster, fork failed ... */
5591  ereport(LOG,
5592  (errmsg("could not fork worker process: %m")));
5593  /* undo what assign_backendlist_entry did */
5595  rw->rw_child_slot = 0;
5596  free(rw->rw_backend);
5597  rw->rw_backend = NULL;
5598  /* mark entry as crashed, so we'll try again later */
5600  break;
5601 
5602 #ifndef EXEC_BACKEND
5603  case 0:
5604  /* in postmaster child ... */
5606 
5607  /* Close the postmaster's sockets */
5608  ClosePostmasterPorts(false);
5609 
5610  /*
5611  * Before blowing away PostmasterContext, save this bgworker's
5612  * data where it can find it.
5613  */
5616  memcpy(MyBgworkerEntry, &rw->rw_worker, sizeof(BackgroundWorker));
5617 
5618  /* Release postmaster's working memory context */
5622 
5624 
5625  exit(1); /* should not get here */
5626  break;
5627 #endif
5628  default:
5629  /* in postmaster, fork successful ... */
5630  rw->rw_pid = worker_pid;
5631  rw->rw_backend->pid = rw->rw_pid;
5633  /* add new worker to lists of backends */
5635 #ifdef EXEC_BACKEND
5636  ShmemBackendArrayAdd(rw->rw_backend);
5637 #endif
5638  return true;
5639  }
5640 
5641  return false;
5642 }
struct bkend * rw_backend
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
#define DEBUG1
Definition: elog.h:25
void InitPostmasterChild(void)
Definition: miscinit.c:175
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:2435
void StartBackgroundWorker(void)
Definition: bgworker.c:700
void ReportBackgroundWorkerPID(RegisteredBgWorker *rw)
Definition: bgworker.c:438
static bool assign_backendlist_entry(RegisteredBgWorker *rw)
Definition: postmaster.c:5693
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
#define NULL
Definition: c.h:229
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:90
#define Assert(condition)
Definition: c.h:675
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:707
BackgroundWorker rw_worker
MemoryContext PostmasterContext
Definition: mcxt.c:45
static void dummy_handler ( SIGNAL_ARGS  )
static

Definition at line 5128 of file postmaster.c.

Referenced by PostmasterMain().

5129 {
5130 }
static void ExitPostmaster ( int  status)
static

Definition at line 4927 of file postmaster.c.

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

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

4928 {
4929 #ifdef HAVE_PTHREAD_IS_THREADED_NP
4930 
4931  /*
4932  * There is no known cause for a postmaster to become multithreaded after
4933  * startup. Recheck to account for the possibility of unknown causes.
4934  * This message uses LOG level, because an unclean shutdown at this point
4935  * would usually not look much different from a clean shutdown.
4936  */
4937  if (pthread_is_threaded_np() != 0)
4938  ereport(LOG,
4939  (errcode(ERRCODE_INTERNAL_ERROR),
4940  errmsg_internal("postmaster became multithreaded"),
4941  errdetail("Please report this to <pgsql-bugs@postgresql.org>.")));
4942 #endif
4943 
4944  /* should cleanup shared memory and kill all backends */
4945 
4946  /*
4947  * Not sure of the semantics here. When the Postmaster dies, should the
4948  * backends all be killed? probably not.
4949  *
4950  * MUST -- vadim 05-10-1999
4951  */
4952 
4953  proc_exit(status);
4954 }
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:224
static void getInstallationPaths ( const char *  argv0)
static

Definition at line 1414 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, NULL, PG_BACKEND_VERSIONSTR, and pkglib_path.

Referenced by PostmasterMain().

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

Definition at line 3253 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(), NULL, 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().

3254 {
3255  dlist_mutable_iter iter;
3256  slist_iter siter;
3257  Backend *bp;
3258  bool take_action;
3259 
3260  /*
3261  * We only log messages and send signals if this is the first process
3262  * crash and we're not doing an immediate shutdown; otherwise, we're only
3263  * here to update postmaster's idea of live processes. If we have already
3264  * signalled children, nonzero exit status is to be expected, so don't
3265  * clutter log.
3266  */
3267  take_action = !FatalError && Shutdown != ImmediateShutdown;
3268 
3269  if (take_action)
3270  {
3271  LogChildExit(LOG, procname, pid, exitstatus);
3272  ereport(LOG,
3273  (errmsg("terminating any other active server processes")));
3274  }
3275 
3276  /* Process background workers. */
3278  {
3279  RegisteredBgWorker *rw;
3280 
3281  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
3282  if (rw->rw_pid == 0)
3283  continue; /* not running */
3284  if (rw->rw_pid == pid)
3285  {
3286  /*
3287  * Found entry for freshly-dead worker, so remove it.
3288  */
3290  dlist_delete(&rw->rw_backend->elem);
3291 #ifdef EXEC_BACKEND
3292  ShmemBackendArrayRemove(rw->rw_backend);
3293 #endif
3294  free(rw->rw_backend);
3295  rw->rw_backend = NULL;
3296  rw->rw_pid = 0;
3297  rw->rw_child_slot = 0;
3298  /* don't reset crashed_at */
3299  /* don't report child stop, either */
3300  /* Keep looping so we can signal remaining workers */
3301  }
3302  else
3303  {
3304  /*
3305  * This worker is still alive. Unless we did so already, tell it
3306  * to commit hara-kiri.
3307  *
3308  * SIGQUIT is the special signal that says exit without proc_exit
3309  * and let the user know what's going on. But if SendStop is set
3310  * (-s on command line), then we send SIGSTOP instead, so that we
3311  * can get core dumps from all backends by hand.
3312  */
3313  if (take_action)
3314  {
3315  ereport(DEBUG2,
3316  (errmsg_internal("sending %s to process %d",
3317  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3318  (int) rw->rw_pid)));
3320  }
3321  }
3322  }
3323 
3324  /* Process regular backends */
3326  {
3327  bp = dlist_container(Backend, elem, iter.cur);
3328 
3329  if (bp->pid == pid)
3330  {
3331  /*
3332  * Found entry for freshly-dead backend, so remove it.
3333  */
3334  if (!bp->dead_end)
3335  {
3337 #ifdef EXEC_BACKEND
3338  ShmemBackendArrayRemove(bp);
3339 #endif
3340  }
3341  dlist_delete(iter.cur);
3342  free(bp);
3343  /* Keep looping so we can signal remaining backends */
3344  }
3345  else
3346  {
3347  /*
3348  * This backend is still alive. Unless we did so already, tell it
3349  * to commit hara-kiri.
3350  *
3351  * SIGQUIT is the special signal that says exit without proc_exit
3352  * and let the user know what's going on. But if SendStop is set
3353  * (-s on command line), then we send SIGSTOP instead, so that we
3354  * can get core dumps from all backends by hand.
3355  *
3356  * We could exclude dead_end children here, but at least in the
3357  * SIGSTOP case it seems better to include them.
3358  *
3359  * Background workers were already processed above; ignore them
3360  * here.
3361  */
3362  if (bp->bkend_type == BACKEND_TYPE_BGWORKER)
3363  continue;
3364 
3365  if (take_action)
3366  {
3367  ereport(DEBUG2,
3368  (errmsg_internal("sending %s to process %d",
3369  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3370  (int) bp->pid)));
3371  signal_child(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
3372  }
3373  }
3374  }
3375 
3376  /* Take care of the startup process too */
3377  if (pid == StartupPID)
3378  {
3379  StartupPID = 0;
3381  }
3382  else if (StartupPID != 0 && take_action)
3383  {
3384  ereport(DEBUG2,
3385  (errmsg_internal("sending %s to process %d",
3386  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3387  (int) StartupPID)));
3390  }
3391 
3392  /* Take care of the bgwriter too */
3393  if (pid == BgWriterPID)
3394  BgWriterPID = 0;
3395  else if (BgWriterPID != 0 && take_action)
3396  {
3397  ereport(DEBUG2,
3398  (errmsg_internal("sending %s to process %d",
3399  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3400  (int) BgWriterPID)));
3402  }
3403 
3404  /* Take care of the checkpointer too */
3405  if (pid == CheckpointerPID)
3406  CheckpointerPID = 0;
3407  else if (CheckpointerPID != 0 && take_action)
3408  {
3409  ereport(DEBUG2,
3410  (errmsg_internal("sending %s to process %d",
3411  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3412  (int) CheckpointerPID)));
3414  }
3415 
3416  /* Take care of the walwriter too */
3417  if (pid == WalWriterPID)
3418  WalWriterPID = 0;
3419  else if (WalWriterPID != 0 && take_action)
3420  {
3421  ereport(DEBUG2,
3422  (errmsg_internal("sending %s to process %d",
3423  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3424  (int) WalWriterPID)));
3426  }
3427 
3428  /* Take care of the walreceiver too */
3429  if (pid == WalReceiverPID)
3430  WalReceiverPID = 0;
3431  else if (WalReceiverPID != 0 && take_action)
3432  {
3433  ereport(DEBUG2,
3434  (errmsg_internal("sending %s to process %d",
3435  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3436  (int) WalReceiverPID)));
3438  }
3439 
3440  /* Take care of the autovacuum launcher too */
3441  if (pid == AutoVacPID)
3442  AutoVacPID = 0;
3443  else if (AutoVacPID != 0 && take_action)
3444  {
3445  ereport(DEBUG2,
3446  (errmsg_internal("sending %s to process %d",
3447  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3448  (int) AutoVacPID)));
3450  }
3451 
3452  /*
3453  * Force a power-cycle of the pgarch process too. (This isn't absolutely
3454  * necessary, but it seems like a good idea for robustness, and it
3455  * simplifies the state-machine logic in the case where a shutdown request
3456  * arrives during crash processing.)
3457  */
3458  if (PgArchPID != 0 && take_action)
3459  {
3460  ereport(DEBUG2,
3461  (errmsg_internal("sending %s to process %d",
3462  "SIGQUIT",
3463  (int) PgArchPID)));
3465  }
3466 
3467  /*
3468  * Force a power-cycle of the pgstat process too. (This isn't absolutely
3469  * necessary, but it seems like a good idea for robustness, and it
3470  * simplifies the state-machine logic in the case where a shutdown request
3471  * arrives during crash processing.)
3472  */
3473  if (PgStatPID != 0 && take_action)
3474  {
3475  ereport(DEBUG2,
3476  (errmsg_internal("sending %s to process %d",
3477  "SIGQUIT",
3478  (int) PgStatPID)));
3481  }
3482 
3483  /* We do NOT restart the syslogger */
3484 
3485  if (Shutdown != ImmediateShutdown)
3486  FatalError = true;
3487 
3488  /* We now transit into a state of waiting for children to die */
3489  if (pmState == PM_RECOVERY ||
3490  pmState == PM_HOT_STANDBY ||
3491  pmState == PM_RUN ||
3492  pmState == PM_WAIT_BACKUP ||
3494  pmState == PM_SHUTDOWN)
3496 
3497  /*
3498  * .. and if this doesn't happen quickly enough, now the clock is ticking
3499  * for us to kill them without mercy.
3500  */
3501  if (AbortStartTime == 0)
3502  AbortStartTime = time(NULL);
3503 }
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:3835
#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
#define NULL
Definition: c.h:229
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:3509
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 1895 of file postmaster.c.

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

Referenced by ServerLoop().

1896 {
1897  int maxsock = -1;
1898  int i;
1899 
1900  FD_ZERO(rmask);
1901 
1902  for (i = 0; i < MAXLISTEN; i++)
1903  {
1904  int fd = ListenSocket[i];
1905 
1906  if (fd == PGINVALID_SOCKET)
1907  break;
1908  FD_SET(fd, rmask);
1909 
1910  if (fd > maxsock)
1911  maxsock = fd;
1912  }
1913 
1914  return maxsock + 1;
1915 }
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 6318 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().

6319 {
6320 #ifndef WIN32
6321 
6322  /*
6323  * Create a pipe. Postmaster holds the write end of the pipe open
6324  * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
6325  * the read file descriptor to select() to wake up in case postmaster
6326  * dies, or check for postmaster death with a (read() == 0). Children must
6327  * close the write end as soon as possible after forking, because EOF
6328  * won't be signaled in the read end until all processes have closed the
6329  * write fd. That is taken care of in ClosePostmasterPorts().
6330  */
6332  if (pipe(postmaster_alive_fds) < 0)
6333  ereport(FATAL,
6335  errmsg_internal("could not create pipe to monitor postmaster death: %m")));
6336 
6337  /*
6338  * Set O_NONBLOCK to allow testing for the fd's presence with a read()
6339  * call.
6340  */
6341  if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
6342  ereport(FATAL,
6344  errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
6345 #else
6346 
6347  /*
6348  * On Windows, we use a process handle for the same purpose.
6349  */
6350  if (DuplicateHandle(GetCurrentProcess(),
6351  GetCurrentProcess(),
6352  GetCurrentProcess(),
6353  &PostmasterHandle,
6354  0,
6355  TRUE,
6356  DUPLICATE_SAME_ACCESS) == 0)
6357  ereport(FATAL,
6358  (errmsg_internal("could not duplicate postmaster handle: error code %lu",
6359  GetLastError())));
6360 #endif /* WIN32 */
6361 }
int MyProcPid
Definition: globals.c:38
#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:86
int postmaster_alive_fds[2]
Definition: postmaster.c:557
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
#define Assert(condition)
Definition: c.h:675
#define TRUE
Definition: c.h:217
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:42
static void LogChildExit ( int  lev,
const char *  procname,
int  pid,
int  exitstatus 
)
static

Definition at line 3509 of file postmaster.c.

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

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

3510 {
3511  /*
3512  * size of activity_buffer is arbitrary, but set equal to default
3513  * track_activity_query_size
3514  */
3515  char activity_buffer[1024];
3516  const char *activity = NULL;
3517 
3518  if (!EXIT_STATUS_0(exitstatus))
3519  activity = pgstat_get_crashed_backend_activity(pid,
3520  activity_buffer,
3521  sizeof(activity_buffer));
3522 
3523  if (WIFEXITED(exitstatus))
3524  ereport(lev,
3525 
3526  /*------
3527  translator: %s is a noun phrase describing a child process, such as
3528  "server process" */
3529  (errmsg("%s (PID %d) exited with exit code %d",
3530  procname, pid, WEXITSTATUS(exitstatus)),
3531  activity ? errdetail("Failed process was running: %s", activity) : 0));
3532  else if (WIFSIGNALED(exitstatus))
3533 #if defined(WIN32)
3534  ereport(lev,
3535 
3536  /*------
3537  translator: %s is a noun phrase describing a child process, such as
3538  "server process" */
3539  (errmsg("%s (PID %d) was terminated by exception 0x%X",
3540  procname, pid, WTERMSIG(exitstatus)),
3541  errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
3542  activity ? errdetail("Failed process was running: %s", activity) : 0));
3543 #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST
3544  ereport(lev,
3545 
3546  /*------
3547  translator: %s is a noun phrase describing a child process, such as
3548  "server process" */
3549  (errmsg("%s (PID %d) was terminated by signal %d: %s",
3550  procname, pid, WTERMSIG(exitstatus),
3551  WTERMSIG(exitstatus) < NSIG ?
3552  sys_siglist[WTERMSIG(exitstatus)] : "(unknown)"),
3553  activity ? errdetail("Failed process was running: %s", activity) : 0));
3554 #else
3555  ereport(lev,
3556 
3557  /*------
3558  translator: %s is a noun phrase describing a child process, such as
3559  "server process" */
3560  (errmsg("%s (PID %d) was terminated by signal %d",
3561  procname, pid, WTERMSIG(exitstatus)),
3562  activity ? errdetail("Failed process was running: %s", activity) : 0));
3563 #endif
3564  else
3565  ereport(lev,
3566 
3567  /*------
3568  translator: %s is a noun phrase describing a child process, such as
3569  "server process" */
3570  (errmsg("%s (PID %d) exited with unrecognized status %d",
3571  procname, pid, exitstatus),
3572  activity ? errdetail("Failed process was running: %s", activity) : 0));
3573 }
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
#define NULL
Definition: c.h:229
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:3966
#define WTERMSIG(w)
Definition: win32.h:175
#define EXIT_STATUS_0(st)
Definition: postmaster.c:548
int MaxLivePostmasterChildren ( void  )

Definition at line 5460 of file postmaster.c.

References autovacuum_max_workers, max_worker_processes, and MaxConnections.

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

5461 {
5462  return 2 * (MaxConnections + autovacuum_max_workers + 1 +
5464 }
int MaxConnections
Definition: globals.c:123
int autovacuum_max_workers
Definition: autovacuum.c:113
int max_worker_processes
Definition: globals.c:124
static void maybe_start_bgworkers ( void  )
static

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

5745 {
5746 #define MAX_BGWORKERS_TO_LAUNCH 100
5747  int num_launched = 0;
5748  TimestampTz now = 0;
5749  slist_mutable_iter iter;
5750 
5751  /*
5752  * During crash recovery, we have no need to be called until the state
5753  * transition out of recovery.
5754  */
5755  if (FatalError)
5756  {
5757  StartWorkerNeeded = false;
5758  HaveCrashedWorker = false;
5759  return;
5760  }
5761 
5762  /* Don't need to be called again unless we find a reason for it below */
5763  StartWorkerNeeded = false;
5764  HaveCrashedWorker = false;
5765 
5767  {
5768  RegisteredBgWorker *rw;
5769 
5770  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
5771 
5772  /* ignore if already running */
5773  if (rw->rw_pid != 0)
5774  continue;
5775 
5776  /* if marked for death, clean up and remove from list */
5777  if (rw->rw_terminate)
5778  {
5779  ForgetBackgroundWorker(&iter);
5780  continue;
5781  }
5782 
5783  /*
5784  * If this worker has crashed previously, maybe it needs to be
5785  * restarted (unless on registration it specified it doesn't want to
5786  * be restarted at all). Check how long ago did a crash last happen.
5787  * If the last crash is too recent, don't start it right away; let it
5788  * be restarted once enough time has passed.
5789  */
5790  if (rw->rw_crashed_at != 0)
5791  {
5793  {
5794  ForgetBackgroundWorker(&iter);
5795  continue;
5796  }
5797 
5798  /* read system time only when needed */
5799  if (now == 0)
5800  now = GetCurrentTimestamp();
5801 
5803  rw->rw_worker.bgw_restart_time * 1000))
5804  {
5805  /* Set flag to remember that we have workers to start later */
5806  HaveCrashedWorker = true;
5807  continue;
5808  }
5809  }
5810 
5812  {
5813  /* reset crash time before trying to start worker */
5814  rw->rw_crashed_at = 0;
5815 
5816  /*
5817  * Try to start the worker.
5818  *
5819  * On failure, give up processing workers for now, but set
5820  * StartWorkerNeeded so we'll come back here on the next iteration
5821  * of ServerLoop to try again. (We don't want to wait, because
5822  * there might be additional ready-to-run workers.) We could set
5823  * HaveCrashedWorker as well, since this worker is now marked
5824  * crashed, but there's no need because the next run of this
5825  * function will do that.
5826  */
5827  if (!do_start_bgworker(rw))
5828  {
5829  StartWorkerNeeded = true;
5830  return;
5831  }
5832 
5833  /*
5834  * If we've launched as many workers as allowed, quit, but have
5835  * ServerLoop call us again to look for additional ready-to-run
5836  * workers. There might not be any, but we'll find out the next
5837  * time we run.
5838  */
5839  if (++num_launched >= MAX_BGWORKERS_TO_LAUNCH)
5840  {
5841  StartWorkerNeeded = true;
5842  return;
5843  }
5844  }
5845  }
5846 }
static volatile bool StartWorkerNeeded
Definition: postmaster.c:360
static bool bgworker_should_start_now(BgWorkerStartTime start_time)
Definition: postmaster.c:5649
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:93
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:361
#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:410
#define BGW_NEVER_RESTART
Definition: bgworker.h:84
static bool do_start_bgworker(RegisteredBgWorker *rw)
Definition: postmaster.c:5558
#define MAX_BGWORKERS_TO_LAUNCH
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:92
BackgroundWorker rw_worker
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1534
static void pmdie ( SIGNAL_ARGS  )
static

Definition at line 2580 of file postmaster.c.

References AbortStartTime, AutoVacPID, BACKEND_TYPE_AUTOVAC, BACKEND_TYPE_BGWORKER, BACKEND_TYPE_NORMAL, BgWriterPID, BlockSig, DEBUG2, ereport, errmsg(), errmsg_internal(), FastShutdown, ImmediateShutdown, LOG, NULL, PG_SETMASK, PM_HOT_STANDBY, PM_RECOVERY, PM_RUN, PM_STARTUP, 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().

2581 {
2582  int save_errno = errno;
2583 
2584  PG_SETMASK(&BlockSig);
2585 
2586  ereport(DEBUG2,
2587  (errmsg_internal("postmaster received signal %d",
2588  postgres_signal_arg)));
2589 
2590  switch (postgres_signal_arg)
2591  {
2592  case SIGTERM:
2593 
2594  /*
2595  * Smart Shutdown:
2596  *
2597  * Wait for children to end their work, then shut down.
2598  */
2599  if (Shutdown >= SmartShutdown)
2600  break;
2602  ereport(LOG,
2603  (errmsg("received smart shutdown request")));
2604 #ifdef USE_SYSTEMD
2605  sd_notify(0, "STOPPING=1");
2606 #endif
2607 
2608  if (pmState == PM_RUN || pmState == PM_RECOVERY ||
2610  {
2611  /* autovac workers are told to shut down immediately */
2612  /* and bgworkers too; does this need tweaking? */
2613  SignalSomeChildren(SIGTERM,
2615  /* and the autovac launcher too */
2616  if (AutoVacPID != 0)
2617  signal_child(AutoVacPID, SIGTERM);
2618  /* and the bgwriter too */
2619  if (BgWriterPID != 0)
2620  signal_child(BgWriterPID, SIGTERM);
2621  /* and the walwriter too */
2622  if (WalWriterPID != 0)
2623  signal_child(WalWriterPID, SIGTERM);
2624 
2625  /*
2626  * If we're in recovery, we can't kill the startup process
2627  * right away, because at present doing so does not release
2628  * its locks. We might want to change this in a future
2629  * release. For the time being, the PM_WAIT_READONLY state
2630  * indicates that we're waiting for the regular (read only)
2631  * backends to die off; once they do, we'll kill the startup
2632  * and walreceiver processes.
2633  */
2634  pmState = (pmState == PM_RUN) ?
2636  }
2637 
2638  /*
2639  * Now wait for online backup mode to end and backends to exit. If
2640  * that is already the case, PostmasterStateMachine will take the
2641  * next step.
2642  */
2644  break;
2645 
2646  case SIGINT:
2647 
2648  /*
2649  * Fast Shutdown:
2650  *
2651  * Abort all children with SIGTERM (rollback active transactions
2652  * and exit) and shut down when they are gone.
2653  */
2654  if (Shutdown >= FastShutdown)
2655  break;
2657  ereport(LOG,
2658  (errmsg("received fast shutdown request")));
2659 #ifdef USE_SYSTEMD
2660  sd_notify(0, "STOPPING=1");
2661 #endif
2662 
2663  if (StartupPID != 0)
2664  signal_child(StartupPID, SIGTERM);
2665  if (BgWriterPID != 0)
2666  signal_child(BgWriterPID, SIGTERM);
2667  if (WalReceiverPID != 0)
2668  signal_child(WalReceiverPID, SIGTERM);
2669  if (pmState == PM_RECOVERY)
2670  {
2672 
2673  /*
2674  * Only startup, bgwriter, walreceiver, possibly bgworkers,
2675  * and/or checkpointer should be active in this state; we just
2676  * signaled the first four, and we don't want to kill
2677  * checkpointer yet.
2678  */
2680  }
2681  else if (pmState == PM_RUN ||
2682  pmState == PM_WAIT_BACKUP ||
2686  {
2687  ereport(LOG,
2688  (errmsg("aborting any active transactions")));
2689  /* shut down all backends and workers */
2690  SignalSomeChildren(SIGTERM,
2693  /* and the autovac launcher too */
2694  if (AutoVacPID != 0)
2695  signal_child(AutoVacPID, SIGTERM);
2696  /* and the walwriter too */
2697  if (WalWriterPID != 0)
2698  signal_child(WalWriterPID, SIGTERM);
2700  }
2701 
2702  /*
2703  * Now wait for backends to exit. If there are none,
2704  * PostmasterStateMachine will take the next step.
2705  */
2707  break;
2708 
2709  case SIGQUIT:
2710 
2711  /*
2712  * Immediate Shutdown:
2713  *
2714  * abort all children with SIGQUIT, wait for them to exit,
2715  * terminate remaining ones with SIGKILL, then exit without
2716  * attempt to properly shut down the data base system.
2717  */
2718  if (Shutdown >= ImmediateShutdown)
2719  break;
2721  ereport(LOG,
2722  (errmsg("received immediate shutdown request")));
2723 #ifdef USE_SYSTEMD
2724  sd_notify(0, "STOPPING=1");
2725 #endif
2726 
2729 
2730  /* set stopwatch for them to die */
2731  AbortStartTime = time(NULL);
2732 
2733  /*
2734  * Now wait for backends to exit. If there are none,
2735  * PostmasterStateMachine will take the next step.
2736  */
2738  break;
2739  }
2740 
2742 
2743  errno = save_errno;
2744 }
static void PostmasterStateMachine(void)
Definition: postmaster.c:3582
static pid_t WalReceiverPID
Definition: postmaster.c:251
static bool SignalSomeChildren(int signal, int targets)
Definition: postmaster.c:3861
#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:3905
#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:3835
#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
#define NULL
Definition: c.h:229
static pid_t AutoVacPID
Definition: postmaster.c:252
int errmsg(const char *fmt,...)
Definition: elog.c:797
static time_t AbortStartTime
Definition: postmaster.c:342
void PostmasterMain ( int  argc,
char *  argv[] 
)

Definition at line 567 of file postmaster.c.

References AddToDataDirLockFile(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), ApplyLauncherRegister(), ARCHIVE_MODE_OFF, Assert, autovac_init(), BlockSig, bonjour_name, ChangeToDataDir(), 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(), LOCK_FILE_LINE_LISTEN_ADDR, 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, NULL, on_proc_exit(), optarg, opterr, optind, ParseLongOption(), pfree(), PG_SETMASK, PGC_POSTMASTER, PGC_S_ARGV, PGINVALID_SOCKET, PgStartTime, pgstat_init(), PM_STARTUP, 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(), unlink_external_pid_file(), userDoption, value, wal_level, WAL_LEVEL_MINIMAL, WARNING, whereToSendOutput, write_stderr, and XLogArchiveMode.

Referenced by main().

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

Definition at line 5854 of file postmaster.c.

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

Referenced by BackgroundWorkerStateChange().

5855 {
5856  dlist_iter iter;
5857  Backend *bp;
5858 
5859  dlist_foreach(iter, &BackendList)
5860  {
5861  bp = dlist_container(Backend, elem, iter.cur);
5862  if (bp->pid == pid)
5863  {
5864  bp->bgworker_notify = true;
5865  return true;
5866  }
5867  }
5868  return false;
5869 }
#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 3582 of file postmaster.c.

References AbortStartTime, Assert, AutoVacPID, BACKEND_TYPE_ALL, BACKEND_TYPE_NORMAL, BACKEND_TYPE_WALSND, BACKEND_TYPE_WORKER, BackupInProgress(), BgWriterPID, CancelBackup(), CheckpointerPID, CountChildren(), dlist_is_empty(), ereport, errmsg(), ExitPostmaster(), FatalError, ImmediateShutdown, 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, SignalSomeChildren(), SIGQUIT, SIGUSR2, StartCheckpointer, STARTUP_CRASHED, STARTUP_RUNNING, StartupDataBase, StartupPID, StartupStatus, WalReceiverPID, and WalWriterPID.

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

3583 {
3584  if (pmState == PM_WAIT_BACKUP)
3585  {
3586  /*
3587  * PM_WAIT_BACKUP state ends when online backup mode is not active.
3588  */
3589  if (!BackupInProgress())
3591  }
3592 
3593  if (pmState == PM_WAIT_READONLY)
3594  {
3595  /*
3596  * PM_WAIT_READONLY state ends when we have no regular backends that
3597  * have been started during recovery. We kill the startup and
3598  * walreceiver processes and transition to PM_WAIT_BACKENDS. Ideally,
3599  * we might like to kill these processes first and then wait for
3600  * backends to die off, but that doesn't work at present because
3601  * killing the startup process doesn't release its locks.
3602  */
3604  {
3605  if (StartupPID != 0)
3606  signal_child(StartupPID, SIGTERM);
3607  if (WalReceiverPID != 0)
3608  signal_child(WalReceiverPID, SIGTERM);
3610  }
3611  }
3612 
3613  /*
3614  * If we are in a state-machine state that implies waiting for backends to
3615  * exit, see if they're all gone, and change state if so.
3616  */
3617  if (pmState == PM_WAIT_BACKENDS)
3618  {
3619  /*
3620  * PM_WAIT_BACKENDS state ends when we have no regular backends
3621  * (including autovac workers), no bgworkers (including unconnected
3622  * ones), and no walwriter, autovac launcher or bgwriter. If we are
3623  * doing crash recovery or an immediate shutdown then we expect the
3624  * checkpointer to exit as well, otherwise not. The archiver, stats,
3625  * and syslogger processes are disregarded since they are not
3626  * connected to shared memory; we also disregard dead_end children
3627  * here. Walsenders are also disregarded, they will be terminated
3628  * later after writing the checkpoint record, like the archiver
3629  * process.
3630  */
3632  StartupPID == 0 &&
3633  WalReceiverPID == 0 &&
3634  BgWriterPID == 0 &&
3635  (CheckpointerPID == 0 ||
3637  WalWriterPID == 0 &&
3638  AutoVacPID == 0)
3639  {
3641  {
3642  /*
3643  * Start waiting for dead_end children to die. This state
3644  * change causes ServerLoop to stop creating new ones.
3645  */
3647 
3648  /*
3649  * We already SIGQUIT'd the archiver and stats processes, if
3650  * any, when we started immediate shutdown or entered
3651  * FatalError state.
3652  */
3653  }
3654  else
3655  {
3656  /*
3657  * If we get here, we are proceeding with normal shutdown. All
3658  * the regular children are gone, and it's time to tell the
3659  * checkpointer to do a shutdown checkpoint. All WAL senders
3660  * are told to switch to a stopping state so that the shutdown
3661  * checkpoint can go ahead.
3662  */
3664  /* Start the checkpointer if not running */
3665  if (CheckpointerPID == 0)
3667  /* And tell it to shut down */
3668  if (CheckpointerPID != 0)
3669  {
3672  pmState = PM_SHUTDOWN;
3673  }
3674  else
3675  {
3676  /*
3677  * If we failed to fork a checkpointer, just shut down.
3678  * Any required cleanup will happen at next restart. We
3679  * set FatalError so that an "abnormal shutdown" message
3680  * gets logged when we exit.
3681  */
3682  FatalError = true;
3684 
3685  /* Kill the walsenders, archiver and stats collector too */
3687  if (PgArchPID != 0)
3689  if (PgStatPID != 0)
3691  }
3692  }
3693  }
3694  }
3695 
3696  if (pmState == PM_SHUTDOWN_2)
3697  {
3698  /*
3699  * PM_SHUTDOWN_2 state ends when there's no other children than
3700  * dead_end children left. There shouldn't be any regular backends
3701  * left by now anyway; what we're really waiting for is walsenders and
3702  * archiver.
3703  *
3704  * Walreceiver should normally be dead by now, but not when a fast
3705  * shutdown is performed during recovery.
3706  */
3707  if (PgArchPID == 0 && CountChildren(BACKEND_TYPE_ALL) == 0 &&
3708  WalReceiverPID == 0)
3709  {
3711  }
3712  }
3713 
3714  if (pmState == PM_WAIT_DEAD_END)
3715  {
3716  /*
3717  * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
3718  * (ie, no dead_end children remain), and the archiver and stats
3719  * collector are gone too.
3720  *
3721  * The reason we wait for those two is to protect them against a new
3722  * postmaster starting conflicting subprocesses; this isn't an
3723  * ironclad protection, but it at least helps in the
3724  * shutdown-and-immediately-restart scenario. Note that they have
3725  * already been sent appropriate shutdown signals, either during a
3726  * normal state transition leading up to PM_WAIT_DEAD_END, or during
3727  * FatalError processing.
3728  */
3729  if (dlist_is_empty(&BackendList) &&
3730  PgArchPID == 0 && PgStatPID == 0)
3731  {
3732  /* These other guys should be dead already */
3733  Assert(StartupPID == 0);
3734  Assert(WalReceiverPID == 0);
3735  Assert(BgWriterPID == 0);
3736  Assert(CheckpointerPID == 0);
3737  Assert(WalWriterPID == 0);
3738  Assert(AutoVacPID == 0);
3739  /* syslogger is not considered here */
3741  }
3742  }
3743 
3744  /*
3745  * If we've been told to shut down, we exit as soon as there are no
3746  * remaining children. If there was a crash, cleanup will occur at the
3747  * next startup. (Before PostgreSQL 8.3, we tried to recover from the
3748  * crash before exiting, but that seems unwise if we are quitting because
3749  * we got SIGTERM from init --- there may well not be time for recovery
3750  * before init decides to SIGKILL us.)
3751  *
3752  * Note that the syslogger continues to run. It will exit when it sees
3753  * EOF on its input pipe, which happens when there are no more upstream
3754  * processes.
3755  */
3757  {
3758  if (FatalError)
3759  {
3760  ereport(LOG, (errmsg("abnormal database system shutdown")));
3761  ExitPostmaster(1);
3762  }
3763  else
3764  {
3765  /*
3766  * Terminate exclusive backup mode to avoid recovery after a clean
3767  * fast shutdown. Since an exclusive backup can only be taken
3768  * during normal running (and not, for example, while running
3769  * under Hot Standby) it only makes sense to do this if we reached
3770  * normal running. If we're still in recovery, the backup file is
3771  * one we're recovering *from*, and we must keep it around so that
3772  * recovery restarts from the right place.
3773  */
3775  CancelBackup();
3776 
3777  /* Normal exit from the postmaster is here */
3778  ExitPostmaster(0);
3779  }
3780  }
3781 
3782  /*
3783  * If the startup process failed, or the user does not want an automatic
3784  * restart after backend crashes, wait for all non-syslogger children to
3785  * exit, and then exit postmaster. We don't try to reinitialize when the
3786  * startup process fails, because more than likely it will just fail again
3787  * and we will keep trying forever.
3788  */
3789  if (pmState == PM_NO_CHILDREN &&
3791  ExitPostmaster(1);
3792 
3793  /*
3794  * If we need to recover from a crash, wait for all non-syslogger children
3795  * to exit, then reset shmem and StartupDataBase.
3796  */
3797  if (FatalError && pmState == PM_NO_CHILDREN)
3798  {
3799  ereport(LOG,
3800  (errmsg("all server processes terminated; reinitializing")));
3801 
3802  /* allow background workers to immediately restart */
3804 
3805  shmem_exit(1);
3807 
3809  Assert(StartupPID != 0);
3811  pmState = PM_STARTUP;
3812  /* crash recovery started, reset SIGKILL flag */
3813  AbortStartTime = 0;
3814  }
3815 }
void CancelBackup(void)
Definition: xlog.c:11360
static StartupStatusEnum StartupStatus
Definition: postmaster.c:266
#define BACKEND_TYPE_ALL
Definition: postmaster.c:146
#define StartupDataBase()
Definition: postmaster.c:541
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
static bool SignalSomeChildren(int signal, int targets)
Definition: postmaster.c:3861
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:142
#define LOG
Definition: elog.h:26
bool BackupInProgress(void)
Definition: xlog.c:11340
void ResetBackgroundWorkerCrashTimes(void)
Definition: bgworker.c:513
#define SIGQUIT
Definition: win32.h:189
#define SignalChildren(sig)
Definition: postmaster.c:420
static int Shutdown
Definition: postmaster.c:274
static pid_t BgWriterPID
Definition: postmaster.c:248
#define StartCheckpointer()
Definition: postmaster.c:543
static int CountChildren(int target)
Definition: postmaster.c:5188
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:4927
bool restart_after_crash
Definition: postmaster.c:244
static dlist_head BackendList
Definition: postmaster.c:183
#define BACKEND_TYPE_WALSND
Definition: postmaster.c:144
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:3835
#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:2489
static pid_t WalWriterPID
Definition: postmaster.c:250
#define Assert(condition)
Definition: c.h:675
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:346
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 2254 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(), bkend::pid, and signal_child().

Referenced by ProcessStartupPacket().

2255 {
2256  CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
2257  int backendPID;
2258  int32 cancelAuthCode;
2259  Backend *bp;
2260 
2261 #ifndef EXEC_BACKEND
2262  dlist_iter iter;
2263 #else
2264  int i;
2265 #endif
2266 
2267  backendPID = (int) ntohl(canc->backendPID);
2268  cancelAuthCode = (int32) ntohl(canc->cancelAuthCode);
2269 
2270  /*
2271  * See if we have a matching backend. In the EXEC_BACKEND case, we can no
2272  * longer access the postmaster's own backend list, and must rely on the
2273  * duplicate array in shared memory.
2274  */
2275 #ifndef EXEC_BACKEND
2276  dlist_foreach(iter, &BackendList)
2277  {
2278  bp = dlist_container(Backend, elem, iter.cur);
2279 #else
2280  for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
2281  {
2282  bp = (Backend *) &ShmemBackendArray[i];
2283 #endif
2284  if (bp->pid == backendPID)
2285  {
2286  if (bp->cancel_key == cancelAuthCode)
2287  {
2288  /* Found a match; signal that backend to cancel current op */
2289  ereport(DEBUG2,
2290  (errmsg_internal("processing cancel request: sending SIGINT to process %d",
2291  backendPID)));
2292  signal_child(bp->pid, SIGINT);
2293  }
2294  else
2295  /* Right PID, wrong key: no way, Jose */
2296  ereport(LOG,
2297  (errmsg("wrong key in cancel request for process %d",
2298  backendPID)));
2299  return;
2300  }
2301  }
2302 
2303  /* No matching backend */
2304  ereport(LOG,
2305  (errmsg("PID %d in cancel request did not match any process",
2306  backendPID)));
2307 }
#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:256
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
uint32 backendPID
Definition: pqcomm.h:196
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:3835
#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:5460
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 1930 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, NULL, StartupPacket::options, palloc0(), parse_bool(), 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().

1931 {
1932  int32 len;
1933  void *buf;
1934  ProtocolVersion proto;
1935  MemoryContext oldcontext;
1936 
1937  pq_startmsgread();
1938  if (pq_getbytes((char *) &len, 4) == EOF)
1939  {
1940  /*
1941  * EOF after SSLdone probably means the client didn't like our
1942  * response to NEGOTIATE_SSL_CODE. That's not an error condition, so
1943  * don't clutter the log with a complaint.
1944  */
1945  if (!SSLdone)
1947  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1948  errmsg("incomplete startup packet")));
1949  return STATUS_ERROR;
1950  }
1951 
1952  len = ntohl(len);
1953  len -= 4;
1954 
1955  if (len < (int32) sizeof(ProtocolVersion) ||
1957  {
1959  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1960  errmsg("invalid length of startup packet")));
1961  return STATUS_ERROR;
1962  }
1963 
1964  /*
1965  * Allocate at least the size of an old-style startup packet, plus one
1966  * extra byte, and make sure all are zeroes. This ensures we will have
1967  * null termination of all strings, in both fixed- and variable-length
1968  * packet layouts.
1969  */
1970  if (len <= (int32) sizeof(StartupPacket))
1971  buf = palloc0(sizeof(StartupPacket) + 1);
1972  else
1973  buf = palloc0(len + 1);
1974 
1975  if (pq_getbytes(buf, len) == EOF)
1976  {
1978  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1979  errmsg("incomplete startup packet")));
1980  return STATUS_ERROR;
1981  }
1982  pq_endmsgread();
1983 
1984  /*
1985  * The first field is either a protocol version number or a special
1986  * request code.
1987  */
1988  port->proto = proto = ntohl(*((ProtocolVersion *) buf));
1989 
1990  if (proto == CANCEL_REQUEST_CODE)
1991  {
1992  processCancelRequest(port, buf);
1993  /* Not really an error, but we don't want to proceed further */
1994  return STATUS_ERROR;
1995  }
1996 
1997  if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
1998  {
1999  char SSLok;
2000 
2001 #ifdef USE_SSL
2002  /* No SSL when disabled or on Unix sockets */
2003  if (!LoadedSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
2004  SSLok = 'N';
2005  else
2006  SSLok = 'S'; /* Support for SSL */
2007 #else
2008  SSLok = 'N'; /* No support for SSL */
2009 #endif
2010 
2011 retry1:
2012  if (send(port->sock, &SSLok, 1, 0) != 1)
2013  {
2014  if (errno == EINTR)
2015  goto retry1; /* if interrupted, just retry */
2018  errmsg("failed to send SSL negotiation response: %m")));
2019  return STATUS_ERROR; /* close the connection */
2020  }
2021 
2022 #ifdef USE_SSL
2023  if (SSLok == 'S' && secure_open_server(port) == -1)
2024  return STATUS_ERROR;
2025 #endif
2026  /* regular startup packet, cancel, etc packet should follow... */
2027  /* but not another SSL negotiation request */
2028  return ProcessStartupPacket(port, true);
2029  }
2030 
2031  /* Could add additional special packet types here */
2032 
2033  /*
2034  * Set FrontendProtocol now so that ereport() knows what format to send if
2035  * we fail during startup.
2036  */
2037  FrontendProtocol = proto;
2038 
2039  /* Check we can handle the protocol the frontend is using. */
2040 
2045  ereport(FATAL,
2046  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2047  errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
2048  PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
2052 
2053  /*
2054  * Now fetch parameters out of startup packet and save them into the Port
2055  * structure. All data structures attached to the Port struct must be
2056  * allocated in TopMemoryContext so that they will remain available in a
2057  * running backend (even after PostmasterContext is destroyed). We need
2058  * not worry about leaking this storage on failure, since we aren't in the
2059  * postmaster process anymore.</