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(), 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 549 of file postmaster.c.

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

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

Definition at line 550 of file postmaster.c.

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

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

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

Referenced by reaper(), and ServerLoop().

#define SIGKILL_CHILDREN_AFTER_SECS   5

Definition at line 345 of file postmaster.c.

Referenced by DetermineSleepTime(), and ServerLoop().

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

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

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

#define StartCheckpointer ( )    StartChildProcess(CheckpointerProcess)

Definition at line 544 of file postmaster.c.

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

#define StartupDataBase ( )    StartChildProcess(StartupProcess)

Definition at line 542 of file postmaster.c.

Referenced by PostmasterMain(), and PostmasterStateMachine().

#define StartWalReceiver ( )    StartChildProcess(WalReceiverProcess)

Definition at line 546 of file postmaster.c.

Referenced by sigusr1_handler().

#define StartWalWriter ( )    StartChildProcess(WalWriterProcess)

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

5690 {
5691  Backend *bn;
5692 
5693  /*
5694  * Compute the cancel key that will be assigned to this session. We
5695  * probably don't need cancel keys for background workers, but we'd better
5696  * have something random in the field to prevent unfriendly people from
5697  * sending cancels to them.
5698  */
5700  {
5701  ereport(LOG,
5702  (errcode(ERRCODE_INTERNAL_ERROR),
5703  errmsg("could not generate random cancel key")));
5704  return false;
5705  }
5706 
5707  bn = malloc(sizeof(Backend));
5708  if (bn == NULL)
5709  {
5710  ereport(LOG,
5711  (errcode(ERRCODE_OUT_OF_MEMORY),
5712  errmsg("out of memory")));
5713  return false;
5714  }
5715 
5716  bn->cancel_key = MyCancelKey;
5719  bn->dead_end = false;
5720  bn->bgworker_notify = false;
5721 
5722  rw->rw_backend = bn;
5723  rw->rw_child_slot = bn->child_slot;
5724 
5725  return true;
5726 }
struct bkend * rw_backend
int errcode(int sqlerrcode)
Definition: elog.c:575
#define LOG
Definition: elog.h:26
bool bgworker_notify
Definition: postmaster.c:179
int AssignPostmasterChildSlot(void)
Definition: pmsignal.c:151
#define malloc(a)
Definition: header.h:50
int32 MyCancelKey
Definition: globals.c:42
int32 cancel_key
Definition: postmaster.c:169
bool dead_end
Definition: postmaster.c:178
#define ereport(elevel, rest)
Definition: elog.h:122
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:145
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:5143
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:43
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void BackendInitialize ( Port port)
static

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

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

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

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

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

Definition at line 5512 of file postmaster.c.

References BlockSig, and PG_SETMASK.

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

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

5467 {
5469 
5470  /* XXX is this the right errcode? */
5472  ereport(FATAL,
5473  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5474  errmsg("database connection requirement not indicated during registration")));
5475 
5477 
5478  /* it had better not gotten out of "init" mode yet */
5479  if (!IsInitProcessingMode())
5480  ereport(ERROR,
5481  (errmsg("invalid processing mode in background worker")));
5483 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define SetProcessingMode(mode)
Definition: miscadmin.h:376
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:371
void BackgroundWorkerInitializeConnectionByOid ( Oid  dboid,
Oid  useroid 
)

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

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

Definition at line 5518 of file postmaster.c.

References PG_SETMASK, and UnBlockSig.

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

5519 {
5521 }
#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 5645 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().

5646 {
5647  switch (pmState)
5648  {
5649  case PM_NO_CHILDREN:
5650  case PM_WAIT_DEAD_END:
5651  case PM_SHUTDOWN_2:
5652  case PM_SHUTDOWN:
5653  case PM_WAIT_BACKENDS:
5654  case PM_WAIT_READONLY:
5655  case PM_WAIT_BACKUP:
5656  break;
5657 
5658  case PM_RUN:
5660  return true;
5661  /* fall through */
5662 
5663  case PM_HOT_STANDBY:
5665  return true;
5666  /* fall through */
5667 
5668  case PM_RECOVERY:
5669  case PM_STARTUP:
5670  case PM_INIT:
5672  return true;
5673  /* fall through */
5674 
5675  }
5676 
5677  return false;
5678 }
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 2312 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().

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

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

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

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

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

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

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

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

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

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

Referenced by PostmasterMain().

1366 {
1367  int i;
1368 
1369  /*
1370  * First, explicitly close all the socket FDs. We used to just let this
1371  * happen implicitly at postmaster exit, but it's better to close them
1372  * before we remove the postmaster.pid lockfile; otherwise there's a race
1373  * condition if a new postmaster wants to re-use the TCP port number.
1374  */
1375  for (i = 0; i < MAXLISTEN; i++)
1376  {
1377  if (ListenSocket[i] != PGINVALID_SOCKET)
1378  {
1381  }
1382  }
1383 
1384  /*
1385  * Next, remove any filesystem entries for Unix sockets. To avoid race
1386  * conditions against incoming postmasters, this must happen after closing
1387  * the sockets and before removing lock files.
1388  */
1390 
1391  /*
1392  * We don't do anything about socket lock files here; those will be
1393  * removed in a later on_proc_exit callback.
1394  */
1395 }
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 2368 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().

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

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

Referenced by ConnCreate(), and ServerLoop().

2413 {
2414 #ifdef USE_SSL
2415  secure_close(conn);
2416 #endif
2417  if (conn->gss)
2418  free(conn->gss);
2419  free(conn);
2420 }
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 5184 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().

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

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

Referenced by PostmasterMain().

5417 {
5418  FILE *fp;
5419  int i;
5420 
5421 #define OPTS_FILE "postmaster.opts"
5422 
5423  if ((fp = fopen(OPTS_FILE, "w")) == NULL)
5424  {
5425  elog(LOG, "could not create file \"%s\": %m", OPTS_FILE);
5426  return false;
5427  }
5428 
5429  fprintf(fp, "%s", fullprogname);
5430  for (i = 1; i < argc; i++)
5431  fprintf(fp, " \"%s\"", argv[i]);
5432  fputs("\n", fp);
5433 
5434  if (fclose(fp))
5435  {
5436  elog(LOG, "could not write file \"%s\": %m", OPTS_FILE);
5437  return false;
5438  }
5439 
5440  return true;
5441 }
#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 1560 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().

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

5555 {
5556  pid_t worker_pid;
5557 
5558  Assert(rw->rw_pid == 0);
5559 
5560  /*
5561  * Allocate and assign the Backend element. Note we must do this before
5562  * forking, so that we can handle out of memory properly.
5563  *
5564  * Treat failure as though the worker had crashed. That way, the
5565  * postmaster will wait a bit before attempting to start it again; if it
5566  * tried again right away, most likely it'd find itself repeating the
5567  * out-of-memory or fork failure condition.
5568  */
5569  if (!assign_backendlist_entry(rw))
5570  {
5572  return false;
5573  }
5574 
5575  ereport(DEBUG1,
5576  (errmsg("starting background worker process \"%s\"",
5577  rw->rw_worker.bgw_name)));
5578 
5579 #ifdef EXEC_BACKEND
5580  switch ((worker_pid = bgworker_forkexec(rw->rw_shmem_slot)))
5581 #else
5582  switch ((worker_pid = fork_process()))
5583 #endif
5584  {
5585  case -1:
5586  /* in postmaster, fork failed ... */
5587  ereport(LOG,
5588  (errmsg("could not fork worker process: %m")));
5589  /* undo what assign_backendlist_entry did */
5591  rw->rw_child_slot = 0;
5592  free(rw->rw_backend);
5593  rw->rw_backend = NULL;
5594  /* mark entry as crashed, so we'll try again later */
5596  break;
5597 
5598 #ifndef EXEC_BACKEND
5599  case 0:
5600  /* in postmaster child ... */
5602 
5603  /* Close the postmaster's sockets */
5604  ClosePostmasterPorts(false);
5605 
5606  /*
5607  * Before blowing away PostmasterContext, save this bgworker's
5608  * data where it can find it.
5609  */
5612  memcpy(MyBgworkerEntry, &rw->rw_worker, sizeof(BackgroundWorker));
5613 
5614  /* Release postmaster's working memory context */
5618 
5620 
5621  exit(1); /* should not get here */
5622  break;
5623 #endif
5624  default:
5625  /* in postmaster, fork successful ... */
5626  rw->rw_pid = worker_pid;
5627  rw->rw_backend->pid = rw->rw_pid;
5629  /* add new worker to lists of backends */
5631 #ifdef EXEC_BACKEND
5632  ShmemBackendArrayAdd(rw->rw_backend);
5633 #endif
5634  return true;
5635  }
5636 
5637  return false;
5638 }
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:2434
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:5689
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 5124 of file postmaster.c.

Referenced by PostmasterMain().

5125 {
5126 }
static void ExitPostmaster ( int  status)
static

Definition at line 4923 of file postmaster.c.

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

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

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

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

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

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

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

Referenced by ServerLoop().

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

6315 {
6316 #ifndef WIN32
6317 
6318  /*
6319  * Create a pipe. Postmaster holds the write end of the pipe open
6320  * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
6321  * the read file descriptor to select() to wake up in case postmaster
6322  * dies, or check for postmaster death with a (read() == 0). Children must
6323  * close the write end as soon as possible after forking, because EOF
6324  * won't be signaled in the read end until all processes have closed the
6325  * write fd. That is taken care of in ClosePostmasterPorts().
6326  */
6328  if (pipe(postmaster_alive_fds) < 0)
6329  ereport(FATAL,
6331  errmsg_internal("could not create pipe to monitor postmaster death: %m")));
6332 
6333  /*
6334  * Set O_NONBLOCK to allow testing for the fd's presence with a read()
6335  * call.
6336  */
6337  if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
6338  ereport(FATAL,
6340  errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
6341 #else
6342 
6343  /*
6344  * On Windows, we use a process handle for the same purpose.
6345  */
6346  if (DuplicateHandle(GetCurrentProcess(),
6347  GetCurrentProcess(),
6348  GetCurrentProcess(),
6349  &PostmasterHandle,
6350  0,
6351  TRUE,
6352  DUPLICATE_SAME_ACCESS) == 0)
6353  ereport(FATAL,
6354  (errmsg_internal("could not duplicate postmaster handle: error code %lu",
6355  GetLastError())));
6356 #endif /* WIN32 */
6357 }
int MyProcPid
Definition: globals.c:39
#define FATAL
Definition: elog.h:52
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
int errcode_for_socket_access(void)
Definition: elog.c:669
pid_t PostmasterPid
Definition: globals.c:87
int postmaster_alive_fds[2]
Definition: postmaster.c:558
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 3508 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().

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

Definition at line 5456 of file postmaster.c.

References autovacuum_max_workers, max_worker_processes, and MaxConnections.

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

5457 {
5458  return 2 * (MaxConnections + autovacuum_max_workers + 1 +
5460 }
int MaxConnections
Definition: globals.c:124
int autovacuum_max_workers
Definition: autovacuum.c:113
int max_worker_processes
Definition: globals.c:125
static void maybe_start_bgworkers ( void  )
static

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

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

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

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

Definition at line 5850 of file postmaster.c.

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

Referenced by BackgroundWorkerStateChange().

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

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

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

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

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

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

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