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/pidfile.h"
#include "utils/ps_status.h"
#include "utils/timeout.h"
#include "utils/varlena.h"
Include dependency graph for postmaster.c:

Go to the source code of this file.

Data Structures

struct  bkend
 

Macros

#define BACKEND_TYPE_NORMAL   0x0001 /* normal backend */
 
#define BACKEND_TYPE_AUTOVAC   0x0002 /* autovacuum worker process */
 
#define BACKEND_TYPE_WALSND   0x0004 /* walsender process */
 
#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */
 
#define BACKEND_TYPE_ALL   0x000F /* OR of all the above */
 
#define BACKEND_TYPE_WORKER   (BACKEND_TYPE_AUTOVAC | BACKEND_TYPE_BGWORKER)
 
#define MAXLISTEN   64
 
#define NoShutdown   0
 
#define SmartShutdown   1
 
#define FastShutdown   2
 
#define ImmediateShutdown   3
 
#define SIGKILL_CHILDREN_AFTER_SECS   5
 
#define SignalChildren(sig)   SignalSomeChildren(sig, BACKEND_TYPE_ALL)
 
#define PgArchStartupAllowed()
 
#define StartupDataBase()   StartChildProcess(StartupProcess)
 
#define StartBackgroundWriter()   StartChildProcess(BgWriterProcess)
 
#define StartCheckpointer()   StartChildProcess(CheckpointerProcess)
 
#define StartWalWriter()   StartChildProcess(WalWriterProcess)
 
#define StartWalReceiver()   StartChildProcess(WalReceiverProcess)
 
#define EXIT_STATUS_0(st)   ((st) == 0)
 
#define EXIT_STATUS_1(st)   (WIFEXITED(st) && WEXITSTATUS(st) == 1)
 
#define EXIT_STATUS_3(st)   (WIFEXITED(st) && WEXITSTATUS(st) == 3)
 
#define OPTS_FILE   "postmaster.opts"
 
#define MAX_BGWORKERS_TO_LAUNCH   100
 

Typedefs

typedef struct bkend Backend
 

Enumerations

enum  StartupStatusEnum { STARTUP_NOT_RUNNING, STARTUP_RUNNING, STARTUP_SIGNALED, STARTUP_CRASHED }
 
enum  PMState {
  PM_INIT, PM_STARTUP, PM_RECOVERY, PM_HOT_STANDBY,
  PM_RUN, PM_WAIT_BACKUP, PM_WAIT_READONLY, PM_WAIT_BACKENDS,
  PM_SHUTDOWN, PM_SHUTDOWN_2, PM_WAIT_DEAD_END, PM_NO_CHILDREN
}
 

Functions

static void CloseServerPorts (int status, Datum arg)
 
static void unlink_external_pid_file (int status, Datum arg)
 
static void getInstallationPaths (const char *argv0)
 
static void checkDataDir (void)
 
static PortConnCreate (int serverFd)
 
static void ConnFree (Port *port)
 
static void reset_shared (int port)
 
static void SIGHUP_handler (SIGNAL_ARGS)
 
static void pmdie (SIGNAL_ARGS)
 
static void reaper (SIGNAL_ARGS)
 
static void sigusr1_handler (SIGNAL_ARGS)
 
static void startup_die (SIGNAL_ARGS)
 
static void dummy_handler (SIGNAL_ARGS)
 
static void StartupPacketTimeoutHandler (void)
 
static void CleanupBackend (int pid, int exitstatus)
 
static bool CleanupBackgroundWorker (int pid, int exitstatus)
 
static void HandleChildCrash (int pid, int exitstatus, const char *procname)
 
static void LogChildExit (int lev, const char *procname, int pid, int exitstatus)
 
static void PostmasterStateMachine (void)
 
static void BackendInitialize (Port *port)
 
static void BackendRun (Port *port) pg_attribute_noreturn()
 
static void ExitPostmaster (int status) pg_attribute_noreturn()
 
static int ServerLoop (void)
 
static int BackendStartup (Port *port)
 
static int ProcessStartupPacket (Port *port, bool SSLdone)
 
static void processCancelRequest (Port *port, void *pkt)
 
static int initMasks (fd_set *rmask)
 
static void report_fork_failure_to_client (Port *port, int errnum)
 
static CAC_state canAcceptConnections (void)
 
static bool RandomCancelKey (int32 *cancel_key)
 
static void signal_child (pid_t pid, int signal)
 
static bool SignalSomeChildren (int signal, int targets)
 
static void TerminateChildren (int signal)
 
static int CountChildren (int target)
 
static bool assign_backendlist_entry (RegisteredBgWorker *rw)
 
static void maybe_start_bgworkers (void)
 
static bool CreateOptsFile (int argc, char *argv[], char *fullprogname)
 
static pid_t StartChildProcess (AuxProcType type)
 
static void StartAutovacuumWorker (void)
 
static void MaybeStartWalReceiver (void)
 
static void InitPostmasterDeathWatchHandle (void)
 
void PostmasterMain (int argc, char *argv[])
 
static void DetermineSleepTime (struct timeval *timeout)
 
void ClosePostmasterPorts (bool am_syslogger)
 
int MaxLivePostmasterChildren (void)
 
void BackgroundWorkerInitializeConnection (char *dbname, char *username)
 
void BackgroundWorkerInitializeConnectionByOid (Oid dboid, Oid useroid)
 
void BackgroundWorkerBlockSignals (void)
 
void BackgroundWorkerUnblockSignals (void)
 
static bool do_start_bgworker (RegisteredBgWorker *rw)
 
static bool bgworker_should_start_now (BgWorkerStartTime start_time)
 
bool PostmasterMarkPIDForWorkerNotify (int pid)
 

Variables

static dlist_head BackendList = DLIST_STATIC_INIT(BackendList)
 
BackgroundWorkerMyBgworkerEntry = NULL
 
int PostPortNumber
 
char * Unix_socket_directories
 
char * ListenAddresses
 
int ReservedBackends
 
static pgsocket ListenSocket [MAXLISTEN]
 
static char ExtraOptions [MAXPGPATH]
 
static bool Reinit = true
 
static int SendStop = false
 
bool EnableSSL = false
 
int PreAuthDelay = 0
 
int AuthenticationTimeout = 60
 
bool log_hostname
 
bool Log_connections = false
 
bool Db_user_namespace = false
 
bool enable_bonjour = false
 
char * bonjour_name
 
bool restart_after_crash = true
 
static pid_t StartupPID = 0
 
static pid_t BgWriterPID = 0
 
static pid_t CheckpointerPID = 0
 
static pid_t WalWriterPID = 0
 
static pid_t WalReceiverPID = 0
 
static pid_t AutoVacPID = 0
 
static pid_t PgArchPID = 0
 
static pid_t PgStatPID = 0
 
static pid_t SysLoggerPID = 0
 
static StartupStatusEnum StartupStatus = STARTUP_NOT_RUNNING
 
static int Shutdown = NoShutdown
 
static bool FatalError = false
 
static PMState pmState = PM_INIT
 
static time_t AbortStartTime = 0
 
static bool ReachedNormalRunning = false
 
bool ClientAuthInProgress = false
 
bool redirection_done = false
 
static volatile sig_atomic_t start_autovac_launcher = false
 
static volatile bool avlauncher_needs_signal = false
 
static volatile sig_atomic_t WalReceiverRequested = false
 
static volatile bool StartWorkerNeeded = true
 
static volatile bool HaveCrashedWorker = false
 
static unsigned int random_seed = 0
 
static struct timeval random_start_time
 
int postmaster_alive_fds [2] = {-1, -1}
 

Macro Definition Documentation

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

Definition at line 144 of file postmaster.c.

Referenced by pmdie(), and StartAutovacuumWorker().

#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */

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

Referenced by CountChildren(), and SignalSomeChildren().

#define BACKEND_TYPE_WORKER   (BACKEND_TYPE_AUTOVAC | BACKEND_TYPE_BGWORKER)

Definition at line 149 of file postmaster.c.

Referenced by PostmasterStateMachine().

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

Definition at line 554 of file postmaster.c.

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

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

Definition at line 555 of file postmaster.c.

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

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

Definition at line 556 of file postmaster.c.

Referenced by reaper().

#define FastShutdown   2

Definition at line 272 of file postmaster.c.

Referenced by pmdie().

#define ImmediateShutdown   3

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

Definition at line 442 of file postmaster.c.

Referenced by reaper(), and ServerLoop().

#define SIGKILL_CHILDREN_AFTER_SECS   5

Definition at line 346 of file postmaster.c.

Referenced by DetermineSleepTime(), and ServerLoop().

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

Definition at line 425 of file postmaster.c.

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

#define SmartShutdown   1

Definition at line 271 of file postmaster.c.

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

#define StartBackgroundWriter ( )    StartChildProcess(BgWriterProcess)

Definition at line 548 of file postmaster.c.

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

#define StartCheckpointer ( )    StartChildProcess(CheckpointerProcess)

Definition at line 549 of file postmaster.c.

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

#define StartupDataBase ( )    StartChildProcess(StartupProcess)

Definition at line 547 of file postmaster.c.

Referenced by PostmasterMain(), and PostmasterStateMachine().

#define StartWalReceiver ( )    StartChildProcess(WalReceiverProcess)

Definition at line 551 of file postmaster.c.

Referenced by MaybeStartWalReceiver().

#define StartWalWriter ( )    StartChildProcess(WalWriterProcess)

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

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

Definition at line 259 of file postmaster.c.

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

Function Documentation

static bool assign_backendlist_entry ( RegisteredBgWorker rw)
static

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

5751 {
5752  Backend *bn;
5753 
5754  /*
5755  * Compute the cancel key that will be assigned to this session. We
5756  * probably don't need cancel keys for background workers, but we'd better
5757  * have something random in the field to prevent unfriendly people from
5758  * sending cancels to them.
5759  */
5761  {
5762  ereport(LOG,
5763  (errcode(ERRCODE_INTERNAL_ERROR),
5764  errmsg("could not generate random cancel key")));
5765  return false;
5766  }
5767 
5768  bn = malloc(sizeof(Backend));
5769  if (bn == NULL)
5770  {
5771  ereport(LOG,
5772  (errcode(ERRCODE_OUT_OF_MEMORY),
5773  errmsg("out of memory")));
5774  return false;
5775  }
5776 
5777  bn->cancel_key = MyCancelKey;
5780  bn->dead_end = false;
5781  bn->bgworker_notify = false;
5782 
5783  rw->rw_backend = bn;
5784  rw->rw_child_slot = bn->child_slot;
5785 
5786  return true;
5787 }
struct bkend * rw_backend
int errcode(int sqlerrcode)
Definition: elog.c:575
#define LOG
Definition: elog.h:26
bool bgworker_notify
Definition: postmaster.c:180
int AssignPostmasterChildSlot(void)
Definition: pmsignal.c:151
#define malloc(a)
Definition: header.h:50
int32 MyCancelKey
Definition: globals.c:42
int32 cancel_key
Definition: postmaster.c:170
bool dead_end
Definition: postmaster.c:179
#define ereport(elevel, rest)
Definition: elog.h:122
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:146
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:5186
int child_slot
Definition: postmaster.c:171
int bkend_type
Definition: postmaster.c:178
#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 4111 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().

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

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

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

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

Definition at line 5573 of file postmaster.c.

References BlockSig, and PG_SETMASK.

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

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

5528 {
5530 
5531  /* XXX is this the right errcode? */
5533  ereport(FATAL,
5534  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5535  errmsg("database connection requirement not indicated during registration")));
5536 
5538 
5539  /* it had better not gotten out of "init" mode yet */
5540  if (!IsInitProcessingMode())
5541  ereport(ERROR,
5542  (errmsg("invalid processing mode in background worker")));
5544 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define SetProcessingMode(mode)
Definition: miscadmin.h:374
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:190
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
#define ereport(elevel, rest)
Definition: elog.h:122
static char * username
Definition: initdb.c: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:39
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:369
void BackgroundWorkerInitializeConnectionByOid ( Oid  dboid,
Oid  useroid 
)

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

5551 {
5553 
5554  /* XXX is this the right errcode? */
5556  ereport(FATAL,
5557  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5558  errmsg("database connection requirement not indicated during registration")));
5559 
5560  InitPostgres(NULL, dboid, NULL, useroid, NULL);
5561 
5562  /* it had better not gotten out of "init" mode yet */
5563  if (!IsInitProcessingMode())
5564  ereport(ERROR,
5565  (errmsg("invalid processing mode in background worker")));
5567 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define SetProcessingMode(mode)
Definition: miscadmin.h:374
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:190
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
#define ereport(elevel, rest)
Definition: elog.h:122
#define 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:369
void BackgroundWorkerUnblockSignals ( void  )

Definition at line 5579 of file postmaster.c.

References PG_SETMASK, and UnBlockSig.

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

5580 {
5582 }
#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 5706 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().

5707 {
5708  switch (pmState)
5709  {
5710  case PM_NO_CHILDREN:
5711  case PM_WAIT_DEAD_END:
5712  case PM_SHUTDOWN_2:
5713  case PM_SHUTDOWN:
5714  case PM_WAIT_BACKENDS:
5715  case PM_WAIT_READONLY:
5716  case PM_WAIT_BACKUP:
5717  break;
5718 
5719  case PM_RUN:
5721  return true;
5722  /* fall through */
5723 
5724  case PM_HOT_STANDBY:
5726  return true;
5727  /* fall through */
5728 
5729  case PM_RECOVERY:
5730  case PM_STARTUP:
5731  case PM_INIT:
5733  return true;
5734  /* fall through */
5735 
5736  }
5737 
5738  return false;
5739 }
static time_t start_time
Definition: pg_ctl.c:103
static PMState pmState
Definition: postmaster.c:339
static CAC_state canAcceptConnections ( void  )
static

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

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

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

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

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

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

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

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

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

Definition at line 1376 of file postmaster.c.

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

Referenced by PostmasterMain().

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

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

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

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

Referenced by ConnCreate(), and ServerLoop().

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

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

5228 {
5229  dlist_iter iter;
5230  int cnt = 0;
5231 
5232  dlist_foreach(iter, &BackendList)
5233  {
5234  Backend *bp = dlist_container(Backend, elem, iter.cur);
5235 
5236  if (bp->dead_end)
5237  continue;
5238 
5239  /*
5240  * Since target == BACKEND_TYPE_ALL is the most common case, we test
5241  * it first and avoid touching shared memory for every child.
5242  */
5243  if (target != BACKEND_TYPE_ALL)
5244  {
5245  /*
5246  * Assign bkend_type for any recently announced WAL Sender
5247  * processes.
5248  */
5249  if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
5252 
5253  if (!(target & bp->bkend_type))
5254  continue;
5255  }
5256 
5257  cnt++;
5258  }
5259  return cnt;
5260 }
#define BACKEND_TYPE_ALL
Definition: postmaster.c:147
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:143
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static dlist_head BackendList
Definition: postmaster.c:184
#define BACKEND_TYPE_WALSND
Definition: postmaster.c:145
bool dead_end
Definition: postmaster.c:179
int child_slot
Definition: postmaster.c:171
int bkend_type
Definition: postmaster.c:178
dlist_node * cur
Definition: ilist.h:161
bool IsPostmasterChildWalSender(int slot)
Definition: pmsignal.c:207
static bool CreateOptsFile ( int  argc,
char *  argv[],
char *  fullprogname 
)
static

Definition at line 5477 of file postmaster.c.

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

Referenced by PostmasterMain().

5478 {
5479  FILE *fp;
5480  int i;
5481 
5482 #define OPTS_FILE "postmaster.opts"
5483 
5484  if ((fp = fopen(OPTS_FILE, "w")) == NULL)
5485  {
5486  elog(LOG, "could not create file \"%s\": %m", OPTS_FILE);
5487  return false;
5488  }
5489 
5490  fprintf(fp, "%s", fullprogname);
5491  for (i = 1; i < argc; i++)
5492  fprintf(fp, " \"%s\"", argv[i]);
5493  fputs("\n", fp);
5494 
5495  if (fclose(fp))
5496  {
5497  elog(LOG, "could not write file \"%s\": %m", OPTS_FILE);
5498  return false;
5499  }
5500 
5501  return true;
5502 }
#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 1571 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().

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

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

5616 {
5617  pid_t worker_pid;
5618 
5619  Assert(rw->rw_pid == 0);
5620 
5621  /*
5622  * Allocate and assign the Backend element. Note we must do this before
5623  * forking, so that we can handle out of memory properly.
5624  *
5625  * Treat failure as though the worker had crashed. That way, the
5626  * postmaster will wait a bit before attempting to start it again; if it
5627  * tried again right away, most likely it'd find itself repeating the
5628  * out-of-memory or fork failure condition.
5629  */
5630  if (!assign_backendlist_entry(rw))
5631  {
5633  return false;
5634  }
5635 
5636  ereport(DEBUG1,
5637  (errmsg("starting background worker process \"%s\"",
5638  rw->rw_worker.bgw_name)));
5639 
5640 #ifdef EXEC_BACKEND
5641  switch ((worker_pid = bgworker_forkexec(rw->rw_shmem_slot)))
5642 #else
5643  switch ((worker_pid = fork_process()))
5644 #endif
5645  {
5646  case -1:
5647  /* in postmaster, fork failed ... */
5648  ereport(LOG,
5649  (errmsg("could not fork worker process: %m")));
5650  /* undo what assign_backendlist_entry did */
5652  rw->rw_child_slot = 0;
5653  free(rw->rw_backend);
5654  rw->rw_backend = NULL;
5655  /* mark entry as crashed, so we'll try again later */
5657  break;
5658 
5659 #ifndef EXEC_BACKEND
5660  case 0:
5661  /* in postmaster child ... */
5663 
5664  /* Close the postmaster's sockets */
5665  ClosePostmasterPorts(false);
5666 
5667  /*
5668  * Before blowing away PostmasterContext, save this bgworker's
5669  * data where it can find it.
5670  */
5673  memcpy(MyBgworkerEntry, &rw->rw_worker, sizeof(BackgroundWorker));
5674 
5675  /* Release postmaster's working memory context */
5679 
5681 
5682  exit(1); /* should not get here */
5683  break;
5684 #endif
5685  default:
5686  /* in postmaster, fork successful ... */
5687  rw->rw_pid = worker_pid;
5688  rw->rw_backend->pid = rw->rw_pid;
5690  /* add new worker to lists of backends */
5692 #ifdef EXEC_BACKEND
5693  ShmemBackendArrayAdd(rw->rw_backend);
5694 #endif
5695  return true;
5696  }
5697 
5698  return false;
5699 }
struct bkend * rw_backend
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
#define DEBUG1
Definition: elog.h:25
void InitPostmasterChild(void)
Definition: miscinit.c:176
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
pid_t fork_process(void)
Definition: fork_process.c:31
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:190
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:185
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:181
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2449
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:5750
static dlist_head BackendList
Definition: postmaster.c:184
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:43
#define free(a)
Definition: header.h:65
#define NULL
Definition: c.h:229
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:90
#define Assert(condition)
Definition: c.h:676
pid_t pid
Definition: postmaster.c:169
int errmsg(const char *fmt,...)
Definition: elog.c:797
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:707
BackgroundWorker rw_worker
MemoryContext PostmasterContext
Definition: mcxt.c:45
static void dummy_handler ( SIGNAL_ARGS  )
static

Definition at line 5167 of file postmaster.c.

Referenced by PostmasterMain().

5168 {
5169 }
static void ExitPostmaster ( int  status)
static

Definition at line 4958 of file postmaster.c.

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

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

4959 {
4960 #ifdef HAVE_PTHREAD_IS_THREADED_NP
4961 
4962  /*
4963  * There is no known cause for a postmaster to become multithreaded after
4964  * startup. Recheck to account for the possibility of unknown causes.
4965  * This message uses LOG level, because an unclean shutdown at this point
4966  * would usually not look much different from a clean shutdown.
4967  */
4968  if (pthread_is_threaded_np() != 0)
4969  ereport(LOG,
4970  (errcode(ERRCODE_INTERNAL_ERROR),
4971  errmsg_internal("postmaster became multithreaded"),
4972  errdetail("Please report this to <pgsql-bugs@postgresql.org>.")));
4973 #endif
4974 
4975  /* should cleanup shared memory and kill all backends */
4976 
4977  /*
4978  * Not sure of the semantics here. When the Postmaster dies, should the
4979  * backends all be killed? probably not.
4980  *
4981  * MUST -- vadim 05-10-1999
4982  */
4983 
4984  proc_exit(status);
4985 }
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 1424 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().

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

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

Definition at line 1909 of file postmaster.c.

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

Referenced by ServerLoop().

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

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

6376 {
6377 #ifndef WIN32
6378 
6379  /*
6380  * Create a pipe. Postmaster holds the write end of the pipe open
6381  * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
6382  * the read file descriptor to select() to wake up in case postmaster
6383  * dies, or check for postmaster death with a (read() == 0). Children must
6384  * close the write end as soon as possible after forking, because EOF
6385  * won't be signaled in the read end until all processes have closed the
6386  * write fd. That is taken care of in ClosePostmasterPorts().
6387  */
6389  if (pipe(postmaster_alive_fds) < 0)
6390  ereport(FATAL,
6392  errmsg_internal("could not create pipe to monitor postmaster death: %m")));
6393 
6394  /*
6395  * Set O_NONBLOCK to allow testing for the fd's presence with a read()
6396  * call.
6397  */
6398  if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
6399  ereport(FATAL,
6401  errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
6402 #else
6403 
6404  /*
6405  * On Windows, we use a process handle for the same purpose.
6406  */
6407  if (DuplicateHandle(GetCurrentProcess(),
6408  GetCurrentProcess(),
6409  GetCurrentProcess(),
6410  &PostmasterHandle,
6411  0,
6412  TRUE,
6413  DUPLICATE_SAME_ACCESS) == 0)
6414  ereport(FATAL,
6415  (errmsg_internal("could not duplicate postmaster handle: error code %lu",
6416  GetLastError())));
6417 #endif /* WIN32 */
6418 }
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:563
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
#define Assert(condition)
Definition: c.h:676
#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 3535 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().

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

Definition at line 5517 of file postmaster.c.

References autovacuum_max_workers, max_worker_processes, and MaxConnections.

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

5518 {
5519  return 2 * (MaxConnections + autovacuum_max_workers + 1 +
5521 }
int MaxConnections
Definition: globals.c:124
int autovacuum_max_workers
Definition: autovacuum.c:114
int max_worker_processes
Definition: globals.c:125
static void maybe_start_bgworkers ( void  )
static

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

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

Definition at line 5460 of file postmaster.c.

References NoShutdown, PM_HOT_STANDBY, PM_RECOVERY, PM_STARTUP, PM_WAIT_READONLY, pmState, Shutdown, StartWalReceiver, WalReceiverPID, and WalReceiverRequested.

Referenced by ServerLoop(), and sigusr1_handler().

5461 {
5462  if (WalReceiverPID == 0 &&
5463  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5465  Shutdown == NoShutdown)
5466  {
5468  WalReceiverRequested = false;
5469  }
5470 }
static pid_t WalReceiverPID
Definition: postmaster.c:252
static volatile sig_atomic_t WalReceiverRequested
Definition: postmaster.c:362
static int Shutdown
Definition: postmaster.c:275
static PMState pmState
Definition: postmaster.c:339
#define NoShutdown
Definition: postmaster.c:270
#define StartWalReceiver()
Definition: postmaster.c:551
static void pmdie ( SIGNAL_ARGS  )
static

Definition at line 2594 of file postmaster.c.

References AbortStartTime, AddToDataDirLockFile(), AutoVacPID, BACKEND_TYPE_AUTOVAC, BACKEND_TYPE_BGWORKER, BACKEND_TYPE_NORMAL, BgWriterPID, BlockSig, DEBUG2, ereport, errmsg(), errmsg_internal(), FastShutdown, ImmediateShutdown, LOCK_FILE_LINE_PM_STATUS, LOG, NULL, PG_SETMASK, PM_HOT_STANDBY, PM_RECOVERY, PM_RUN, PM_STARTUP, PM_STATUS_STOPPING, PM_WAIT_BACKENDS, PM_WAIT_BACKUP, PM_WAIT_READONLY, pmState, PostmasterStateMachine(), Shutdown, signal_child(), SignalSomeChildren(), SIGQUIT, SmartShutdown, StartupPID, TerminateChildren(), UnBlockSig, WalReceiverPID, and WalWriterPID.

Referenced by PostmasterMain().

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

Definition at line 573 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_PM_STATUS, LOCK_FILE_LINE_SOCKET_DIR, LOG, Log_destination, LOG_DESTINATION_STDERR, Log_destination_string, LOG_METAINFO_DATAFILE, max_wal_senders, MaxConnections, MAXLISTEN, maybe_start_bgworkers(), MemoryContextSwitchTo(), my_exec_path, MyProcPid, MyStartTime, name, NIL, NULL, on_proc_exit(), optarg, opterr, optind, ParseLongOption(), pfree(), PG_SETMASK, PGC_POSTMASTER, PGC_S_ARGV, PGINVALID_SOCKET, PgStartTime, pgstat_init(), PM_STARTUP, PM_STATUS_STARTING, pmdie(), pmState, PostmasterContext, PostmasterPid, PostPortNumber, pqinitmask(), pqsignal(), pqsignal_no_restart(), process_shared_preload_libraries(), progname, pstrdup(), random_start_time, reaper(), Reinit, RemovePgTempFiles(), RemovePromoteSignalFiles(), ReservedBackends, reset_shared(), S_IRGRP, S_IROTH, S_IRWXG, S_IRWXO, secure_initialize(), SelectConfigFiles(), SendStop, ServerLoop(), set_debug_options(), set_max_safe_fds(), set_plan_disabling_options(), set_stack_base(), SetConfigOption(), SIG_IGN, SIGALRM, SIGCHLD, SIGHUP, SIGHUP_handler(), SIGPIPE, SIGQUIT, SIGTTIN, SIGTTOU, SIGUSR1, sigusr1_handler(), SIGUSR2, snprintf(), SplitDirectoriesString(), SplitIdentifierString(), srandom(), STARTUP_RUNNING, StartupDataBase, StartupPID, StartupStatus, status(), STATUS_OK, StreamServerPort(), strerror(), success, SysLogger_Start(), SysLoggerPID, TopMemoryContext, Unix_socket_directories, unlink(), unlink_external_pid_file(), userDoption, value, wal_level, WAL_LEVEL_MINIMAL, WARNING, whereToSendOutput, write_stderr, and XLogArchiveMode.

Referenced by main().

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

Definition at line 5911 of file postmaster.c.

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

Referenced by BackgroundWorkerStateChange().

5912 {
5913  dlist_iter iter;
5914  Backend *bp;
5915 
5916  dlist_foreach(iter, &BackendList)
5917  {
5918  bp = dlist_container(Backend, elem, iter.cur);
5919  if (bp->pid == pid)
5920  {
5921  bp->bgworker_notify = true;
5922  return true;
5923  }
5924  }
5925  return false;
5926 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
bool bgworker_notify
Definition: postmaster.c:180
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static dlist_head BackendList
Definition: postmaster.c:184
dlist_node * cur
Definition: ilist.h:161
pid_t pid
Definition: postmaster.c:169
static void PostmasterStateMachine ( void  )
static

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

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

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

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

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

1945 {
1946  int32 len;
1947  void *buf;
1948  ProtocolVersion proto;
1949  MemoryContext oldcontext;
1950 
1951  pq_startmsgread();
1952  if (pq_getbytes((char *) &len, 4) == EOF)
1953  {
1954  /*
1955  * EOF after SSLdone probably means the client didn't like our
1956  * response to NEGOTIATE_SSL_CODE. That's not an error condition, so
1957  * don't clutter the log with a complaint.
1958  */
1959  if (!SSLdone)
1961  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1962  errmsg("incomplete startup packet")));
1963  return STATUS_ERROR;
1964  }
1965 
1966  len = ntohl(len);
1967  len -= 4;
1968 
1969  if (len < (int32) sizeof(ProtocolVersion) ||
1971  {
1973  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1974  errmsg("invalid length of startup packet")));
1975  return STATUS_ERROR;
1976  }
1977 
1978  /*
1979  * Allocate at least the size of an old-style startup packet, plus one
1980  * extra byte, and make sure all are zeroes. This ensures we will have
1981  * null termination of all strings, in both fixed- and variable-length
1982  * packet layouts.
1983  */
1984  if (len <= (int32) sizeof(StartupPacket))
1985  buf = palloc0(sizeof(StartupPacket) + 1);
1986  else
1987  buf = palloc0(len + 1);
1988 
1989  if (pq_getbytes(buf, len) == EOF)
1990  {
1992  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1993  errmsg("incomplete startup packet")));
1994  return STATUS_ERROR;
1995  }
1996  pq_endmsgread();
1997 
1998  /*
1999  * The first field is either a protocol version number or a special
2000  * request code.
2001  */
2002  port->proto = proto = ntohl(*((ProtocolVersion *) buf));
2003 
2004  if (proto == CANCEL_REQUEST_CODE)
2005  {
2006  processCancelRequest(port, buf);
2007  /* Not really an error, but we don't want to proceed further */
2008  return STATUS_ERROR;
2009  }
2010 
2011  if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
2012  {