/src/backend/postmaster/postmaster.c
C | 6093 lines | 3424 code | 772 blank | 1897 comment | 801 complexity | 85a6cfbd16d163cf65289491934ca360 MD5 | raw file
Possible License(s): AGPL-3.0
Large files files are truncated, but you can click here to view the full file
- /*-------------------------------------------------------------------------
- *
- * postmaster.c
- * This program acts as a clearing house for requests to the
- * POSTGRES system. Frontend programs send a startup message
- * to the Postmaster and the postmaster uses the info in the
- * message to setup a backend process.
- *
- * The postmaster also manages system-wide operations such as
- * startup and shutdown. The postmaster itself doesn't do those
- * operations, mind you --- it just forks off a subprocess to do them
- * at the right times. It also takes care of resetting the system
- * if a backend crashes.
- *
- * The postmaster process creates the shared memory and semaphore
- * pools during startup, but as a rule does not touch them itself.
- * In particular, it is not a member of the PGPROC array of backends
- * and so it cannot participate in lock-manager operations. Keeping
- * the postmaster away from shared memory operations makes it simpler
- * and more reliable. The postmaster is almost always able to recover
- * from crashes of individual backends by resetting shared memory;
- * if it did much with shared memory then it would be prone to crashing
- * along with the backends.
- *
- * When a request message is received, we now fork() immediately.
- * The child process performs authentication of the request, and
- * then becomes a backend if successful. This allows the auth code
- * to be written in a simple single-threaded style (as opposed to the
- * crufty "poor man's multitasking" code that used to be needed).
- * More importantly, it ensures that blockages in non-multithreaded
- * libraries like SSL or PAM cannot cause denial of service to other
- * clients.
- *
- *
- * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
- * Portions Copyright (c) 1994, Regents of the University of California
- *
- *
- * IDENTIFICATION
- * src/backend/postmaster/postmaster.c
- *
- * NOTES
- *
- * Initialization:
- * The Postmaster sets up shared memory data structures
- * for the backends.
- *
- * Synchronization:
- * The Postmaster shares memory with the backends but should avoid
- * touching shared memory, so as not to become stuck if a crashing
- * backend screws up locks or shared memory. Likewise, the Postmaster
- * should never block on messages from frontend clients.
- *
- * Garbage Collection:
- * The Postmaster cleans up after backends if they have an emergency
- * exit and/or core dump.
- *
- * Error Reporting:
- * Use write_stderr() only for reporting "interactive" errors
- * (essentially, bogus arguments on the command line). Once the
- * postmaster is launched, use ereport().
- *
- *-------------------------------------------------------------------------
- */
- #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>
- #ifdef HAVE_SYS_SELECT_H
- #include <sys/select.h>
- #endif
- #ifdef USE_BONJOUR
- #include <dns_sd.h>
- #endif
- #include "access/transam.h"
- #include "access/xlog.h"
- #include "bootstrap/bootstrap.h"
- #include "catalog/pg_control.h"
- #include "lib/ilist.h"
- #include "libpq/auth.h"
- #include "libpq/ip.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/walsender.h"
- #include "storage/fd.h"
- #include "storage/ipc.h"
- #include "storage/pg_shmem.h"
- #include "storage/pmsignal.h"
- #include "storage/proc.h"
- #include "tcop/tcopprot.h"
- #include "utils/builtins.h"
- #include "utils/datetime.h"
- #include "utils/dynamic_loader.h"
- #include "utils/memutils.h"
- #include "utils/ps_status.h"
- #include "utils/timeout.h"
- #ifdef EXEC_BACKEND
- #include "storage/spin.h"
- #endif
- /*
- * Possible types of a backend. Beyond being the possible bkend_type values in
- * struct bkend, these are OR-able request flag bits for SignalSomeChildren()
- * and CountChildren().
- */
- #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)
- /*
- * List of active backends (or child processes anyway; we don't actually
- * know whether a given child has become a backend or is still in the
- * authorization phase). This is used mainly to keep track of how many
- * children we have and send them appropriate signals when necessary.
- *
- * "Special" children such as the startup, bgwriter and autovacuum launcher
- * tasks are not in this list. Autovacuum worker and walsender are in it.
- * Also, "dead_end" children are in it: these are children launched just for
- * the purpose of sending a friendly rejection message to a would-be client.
- * We must track them because they are attached to shared memory, but we know
- * they will never become live backends. dead_end children are not assigned a
- * PMChildSlot.
- *
- * Background workers that request shared memory access during registration are
- * in this list, too.
- */
- typedef struct bkend
- {
- pid_t pid; /* process id of backend */
- long cancel_key; /* cancel key for cancels for this backend */
- int child_slot; /* PMChildSlot for this backend, if any */
- /*
- * Flavor of backend or auxiliary process. Note that BACKEND_TYPE_WALSND
- * backends initially announce themselves as BACKEND_TYPE_NORMAL, so if
- * bkend_type is normal, you should check for a recent transition.
- */
- int bkend_type;
- bool dead_end; /* is it going to send an error and quit? */
- bool bgworker_notify; /* gets bgworker start/stop notifications */
- dlist_node elem; /* list link in BackendList */
- } Backend;
- static dlist_head BackendList = DLIST_STATIC_INIT(BackendList);
- #ifdef EXEC_BACKEND
- static Backend *ShmemBackendArray;
- #endif
- BackgroundWorker *MyBgworkerEntry = NULL;
- /* The socket number we are listening for connections on */
- int PostPortNumber;
- /* The directory names for Unix socket(s) */
- char *Unix_socket_directories;
- /* The TCP listen address(es) */
- char *ListenAddresses;
- /*
- * ReservedBackends is the number of backends reserved for superuser use.
- * This number is taken out of the pool size given by MaxBackends so
- * number of backend slots available to non-superusers is
- * (MaxBackends - ReservedBackends). Note what this really means is
- * "if there are <= ReservedBackends connections available, only superusers
- * can make new connections" --- pre-existing superuser connections don't
- * count against the limit.
- */
- int ReservedBackends;
- /* The socket(s) we're listening to. */
- #define MAXLISTEN 64
- static pgsocket ListenSocket[MAXLISTEN];
- /*
- * Set by the -o option
- */
- static char ExtraOptions[MAXPGPATH];
- /*
- * These globals control the behavior of the postmaster in case some
- * backend dumps core. Normally, it kills all peers of the dead backend
- * and reinitializes shared memory. By specifying -s or -n, we can have
- * the postmaster stop (rather than kill) peers and not reinitialize
- * shared data structures. (Reinit is currently dead code, though.)
- */
- static bool Reinit = true;
- static int SendStop = false;
- /* still more option variables */
- bool EnableSSL = false;
- int PreAuthDelay = 0;
- int AuthenticationTimeout = 60;
- bool log_hostname; /* for ps display and logging */
- bool Log_connections = false;
- bool Db_user_namespace = false;
- bool enable_bonjour = false;
- char *bonjour_name;
- bool restart_after_crash = true;
- /* PIDs of special child processes; 0 when not running */
- static pid_t StartupPID = 0,
- BgWriterPID = 0,
- CheckpointerPID = 0,
- WalWriterPID = 0,
- WalReceiverPID = 0,
- AutoVacPID = 0,
- PgArchPID = 0,
- PgStatPID = 0,
- SysLoggerPID = 0;
- /* Startup/shutdown state */
- #define NoShutdown 0
- #define SmartShutdown 1
- #define FastShutdown 2
- #define ImmediateShutdown 3
- static int Shutdown = NoShutdown;
- static bool FatalError = false; /* T if recovering from backend crash */
- static bool RecoveryError = false; /* T if WAL recovery failed */
- /*
- * We use a simple state machine to control startup, shutdown, and
- * crash recovery (which is rather like shutdown followed by startup).
- *
- * After doing all the postmaster initialization work, we enter PM_STARTUP
- * state and the startup process is launched. The startup process begins by
- * reading the control file and other preliminary initialization steps.
- * In a normal startup, or after crash recovery, the startup process exits
- * with exit code 0 and we switch to PM_RUN state. However, archive recovery
- * is handled specially since it takes much longer and we would like to support
- * hot standby during archive recovery.
- *
- * When the startup process is ready to start archive recovery, it signals the
- * postmaster, and we switch to PM_RECOVERY state. The background writer and
- * checkpointer are launched, while the startup process continues applying WAL.
- * If Hot Standby is enabled, then, after reaching a consistent point in WAL
- * redo, startup process signals us again, and we switch to PM_HOT_STANDBY
- * state and begin accepting connections to perform read-only queries. When
- * archive recovery is finished, the startup process exits with exit code 0
- * and we switch to PM_RUN state.
- *
- * Normal child backends can only be launched when we are in PM_RUN or
- * PM_HOT_STANDBY state. (We also allow launch of normal
- * child backends in PM_WAIT_BACKUP state, but only for superusers.)
- * In other states we handle connection requests by launching "dead_end"
- * child processes, which will simply send the client an error message and
- * quit. (We track these in the BackendList so that we can know when they
- * are all gone; this is important because they're still connected to shared
- * memory, and would interfere with an attempt to destroy the shmem segment,
- * possibly leading to SHMALL failure when we try to make a new one.)
- * In PM_WAIT_DEAD_END state we are waiting for all the dead_end children
- * to drain out of the system, and therefore stop accepting connection
- * requests at all until the last existing child has quit (which hopefully
- * will not be very long).
- *
- * Notice that this state variable does not distinguish *why* we entered
- * states later than PM_RUN --- Shutdown and FatalError must be consulted
- * to find that out. FatalError is never true in PM_RECOVERY_* or PM_RUN
- * states, nor in PM_SHUTDOWN states (because we don't enter those states
- * when trying to recover from a crash). It can be true in PM_STARTUP state,
- * because we don't clear it until we've successfully started WAL redo.
- * Similarly, RecoveryError means that we have crashed during recovery, and
- * should not try to restart.
- */
- typedef enum
- {
- PM_INIT, /* postmaster starting */
- PM_STARTUP, /* waiting for startup subprocess */
- PM_RECOVERY, /* in archive recovery mode */
- PM_HOT_STANDBY, /* in hot standby mode */
- PM_RUN, /* normal "database is alive" state */
- PM_WAIT_BACKUP, /* waiting for online backup mode to end */
- PM_WAIT_READONLY, /* waiting for read only backends to exit */
- PM_WAIT_BACKENDS, /* waiting for live backends to exit */
- PM_SHUTDOWN, /* waiting for checkpointer to do shutdown
- * ckpt */
- PM_SHUTDOWN_2, /* waiting for archiver and walsenders to
- * finish */
- PM_WAIT_DEAD_END, /* waiting for dead_end children to exit */
- PM_NO_CHILDREN /* all important children have exited */
- } PMState;
- static PMState pmState = PM_INIT;
- /* Start time of abort processing at immediate shutdown or child crash */
- static time_t AbortStartTime;
- #define SIGKILL_CHILDREN_AFTER_SECS 5
- static bool ReachedNormalRunning = false; /* T if we've reached PM_RUN */
- bool ClientAuthInProgress = false; /* T during new-client
- * authentication */
- bool redirection_done = false; /* stderr redirected for syslogger? */
- /* received START_AUTOVAC_LAUNCHER signal */
- static volatile sig_atomic_t start_autovac_launcher = false;
- /* the launcher needs to be signalled to communicate some condition */
- static volatile bool avlauncher_needs_signal = false;
- /* set when there's a worker that needs to be started up */
- static volatile bool StartWorkerNeeded = true;
- static volatile bool HaveCrashedWorker = false;
- /*
- * State for assigning random salts and cancel keys.
- * Also, the global MyCancelKey passes the cancel key assigned to a given
- * backend from the postmaster to that backend (via fork).
- */
- static unsigned int random_seed = 0;
- static struct timeval random_start_time;
- #ifdef USE_BONJOUR
- static DNSServiceRef bonjour_sdref = NULL;
- #endif
- /*
- * postmaster.c - function prototypes
- */
- static void unlink_external_pid_file(int status, Datum arg);
- static void getInstallationPaths(const char *argv0);
- static void checkDataDir(void);
- static Port *ConnCreate(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) __attribute__((noreturn));
- static void ExitPostmaster(int status) __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 long PostmasterRandom(void);
- static void RandomSalt(char *md5Salt);
- static void signal_child(pid_t pid, int signal);
- static bool SignalSomeChildren(int signal, int targets);
- static bool SignalUnconnectedWorkers(int signal);
- static void TerminateChildren(int signal);
- #define SignalChildren(sig) SignalSomeChildren(sig, BACKEND_TYPE_ALL)
- static int CountChildren(int target);
- static int CountUnconnectedWorkers(void);
- static void maybe_start_bgworker(void);
- static bool CreateOptsFile(int argc, char *argv[], char *fullprogname);
- static pid_t StartChildProcess(AuxProcType type);
- static void StartAutovacuumWorker(void);
- static void InitPostmasterDeathWatchHandle(void);
- #ifdef EXEC_BACKEND
- #ifdef WIN32
- #define WNOHANG 0 /* ignored, so any integer value will do */
- static pid_t waitpid(pid_t pid, int *exitstatus, int options);
- static void WINAPI pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired);
- static HANDLE win32ChildQueue;
- typedef struct
- {
- HANDLE waitHandle;
- HANDLE procHandle;
- DWORD procId;
- } win32_deadchild_waitinfo;
- #endif /* WIN32 */
- static pid_t backend_forkexec(Port *port);
- static pid_t internal_forkexec(int argc, char *argv[], Port *port);
- /* Type for a socket that can be inherited to a client process */
- #ifdef WIN32
- typedef struct
- {
- SOCKET origsocket; /* Original socket value, or PGINVALID_SOCKET
- * if not a socket */
- WSAPROTOCOL_INFO wsainfo;
- } InheritableSocket;
- #else
- typedef int InheritableSocket;
- #endif
- /*
- * Structure contains all variables passed to exec:ed backends
- */
- typedef struct
- {
- Port port;
- InheritableSocket portsocket;
- char DataDir[MAXPGPATH];
- pgsocket ListenSocket[MAXLISTEN];
- long MyCancelKey;
- int MyPMChildSlot;
- #ifndef WIN32
- unsigned long UsedShmemSegID;
- #else
- HANDLE UsedShmemSegID;
- #endif
- void *UsedShmemSegAddr;
- slock_t *ShmemLock;
- VariableCache ShmemVariableCache;
- Backend *ShmemBackendArray;
- #ifndef HAVE_SPINLOCKS
- PGSemaphore SpinlockSemaArray;
- #endif
- LWLockPadded *MainLWLockArray;
- slock_t *ProcStructLock;
- PROC_HDR *ProcGlobal;
- PGPROC *AuxiliaryProcs;
- PGPROC *PreparedXactProcs;
- PMSignalData *PMSignalState;
- InheritableSocket pgStatSock;
- pid_t PostmasterPid;
- TimestampTz PgStartTime;
- TimestampTz PgReloadTime;
- pg_time_t first_syslogger_file_time;
- bool redirection_done;
- bool IsBinaryUpgrade;
- int max_safe_fds;
- int MaxBackends;
- #ifdef WIN32
- HANDLE PostmasterHandle;
- HANDLE initial_signal_pipe;
- HANDLE syslogPipe[2];
- #else
- int postmaster_alive_fds[2];
- int syslogPipe[2];
- #endif
- char my_exec_path[MAXPGPATH];
- char pkglib_path[MAXPGPATH];
- char ExtraOptions[MAXPGPATH];
- } BackendParameters;
- static void read_backend_variables(char *id, Port *port);
- static void restore_backend_variables(BackendParameters *param, Port *port);
- #ifndef WIN32
- static bool save_backend_variables(BackendParameters *param, Port *port);
- #else
- static bool save_backend_variables(BackendParameters *param, Port *port,
- HANDLE childProcess, pid_t childPid);
- #endif
- static void ShmemBackendArrayAdd(Backend *bn);
- static void ShmemBackendArrayRemove(Backend *bn);
- #endif /* EXEC_BACKEND */
- #define StartupDataBase() StartChildProcess(StartupProcess)
- #define StartBackgroundWriter() StartChildProcess(BgWriterProcess)
- #define StartCheckpointer() StartChildProcess(CheckpointerProcess)
- #define StartWalWriter() StartChildProcess(WalWriterProcess)
- #define StartWalReceiver() StartChildProcess(WalReceiverProcess)
- /* Macros to check exit status of a child process */
- #define EXIT_STATUS_0(st) ((st) == 0)
- #define EXIT_STATUS_1(st) (WIFEXITED(st) && WEXITSTATUS(st) == 1)
- #ifndef WIN32
- /*
- * File descriptors for pipe used to monitor if postmaster is alive.
- * First is POSTMASTER_FD_WATCH, second is POSTMASTER_FD_OWN.
- */
- int postmaster_alive_fds[2] = {-1, -1};
- #else
- /* Process handle of postmaster used for the same purpose on Windows */
- HANDLE PostmasterHandle;
- #endif
- /*
- * Postmaster main entry point
- */
- void
- PostmasterMain(int argc, char *argv[])
- {
- int opt;
- int status;
- char *userDoption = NULL;
- bool listen_addr_saved = false;
- int i;
- char *output_config_variable = NULL;
- MyProcPid = PostmasterPid = getpid();
- MyStartTime = time(NULL);
- IsPostmasterEnvironment = true;
- /*
- * for security, no dir or file created can be group or other accessible
- */
- umask(S_IRWXG | S_IRWXO);
- /*
- * By default, palloc() requests in the postmaster will be allocated in
- * the PostmasterContext, which is space that can be recycled by backends.
- * Allocated data that needs to be available to backends should be
- * allocated in TopMemoryContext.
- */
- PostmasterContext = AllocSetContextCreate(TopMemoryContext,
- "Postmaster",
- ALLOCSET_DEFAULT_MINSIZE,
- ALLOCSET_DEFAULT_INITSIZE,
- ALLOCSET_DEFAULT_MAXSIZE);
- MemoryContextSwitchTo(PostmasterContext);
- /* Initialize paths to installation files */
- getInstallationPaths(argv[0]);
- /*
- * Set up signal handlers for the postmaster process.
- *
- * CAUTION: when changing this list, check for side-effects on the signal
- * handling setup of child processes. See tcop/postgres.c,
- * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/walwriter.c,
- * postmaster/autovacuum.c, postmaster/pgarch.c, postmaster/pgstat.c,
- * postmaster/syslogger.c, postmaster/bgworker.c and
- * postmaster/checkpointer.c.
- */
- pqinitmask();
- PG_SETMASK(&BlockSig);
- pqsignal(SIGHUP, SIGHUP_handler); /* reread config file and have
- * children do same */
- pqsignal(SIGINT, pmdie); /* send SIGTERM and shut down */
- pqsignal(SIGQUIT, pmdie); /* send SIGQUIT and die */
- pqsignal(SIGTERM, pmdie); /* wait for children and shut down */
- pqsignal(SIGALRM, SIG_IGN); /* ignored */
- pqsignal(SIGPIPE, SIG_IGN); /* ignored */
- pqsignal(SIGUSR1, sigusr1_handler); /* message from child process */
- pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
- pqsignal(SIGCHLD, reaper); /* handle child termination */
- pqsignal(SIGTTIN, SIG_IGN); /* ignored */
- pqsignal(SIGTTOU, SIG_IGN); /* ignored */
- /* ignore SIGXFSZ, so that ulimit violations work like disk full */
- #ifdef SIGXFSZ
- pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
- #endif
- /*
- * Options setup
- */
- InitializeGUCOptions();
- opterr = 1;
- /*
- * Parse command-line options. CAUTION: keep this in sync with
- * tcop/postgres.c (the option sets should not conflict) and with the
- * common help() function in main/main.c.
- */
- while ((opt = getopt(argc, argv, "A:B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:W:-:")) != -1)
- {
- switch (opt)
- {
- case 'A':
- SetConfigOption("debug_assertions", optarg, PGC_POSTMASTER, PGC_S_ARGV);
- break;
- case 'B':
- SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
- break;
- case 'b':
- /* Undocumented flag used for binary upgrades */
- IsBinaryUpgrade = true;
- break;
- case 'C':
- output_config_variable = strdup(optarg);
- break;
- case 'D':
- userDoption = strdup(optarg);
- break;
- case 'd':
- set_debug_options(atoi(optarg), PGC_POSTMASTER, PGC_S_ARGV);
- break;
- case 'E':
- SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
- break;
- case 'e':
- SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
- break;
- case 'F':
- SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
- break;
- case 'f':
- if (!set_plan_disabling_options(optarg, PGC_POSTMASTER, PGC_S_ARGV))
- {
- write_stderr("%s: invalid argument for option -f: \"%s\"\n",
- progname, optarg);
- ExitPostmaster(1);
- }
- break;
- case 'h':
- SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
- break;
- case 'i':
- SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
- break;
- case 'j':
- /* only used by interactive backend */
- break;
- case 'k':
- SetConfigOption("unix_socket_directories", optarg, PGC_POSTMASTER, PGC_S_ARGV);
- break;
- case 'l':
- SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
- break;
- case 'N':
- SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
- break;
- case 'n':
- /* Don't reinit shared mem after abnormal exit */
- Reinit = false;
- break;
- case 'O':
- SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
- break;
- case 'o':
- /* Other options to pass to the backend on the command line */
- snprintf(ExtraOptions + strlen(ExtraOptions),
- sizeof(ExtraOptions) - strlen(ExtraOptions),
- " %s", optarg);
- break;
- case 'P':
- SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
- break;
- case 'p':
- SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
- break;
- case 'r':
- /* only used by single-user backend */
- break;
- case 'S':
- SetConfigOption("work_mem", optarg, PGC_POSTMASTER, PGC_S_ARGV);
- break;
- case 's':
- SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
- break;
- case 'T':
- /*
- * In the event that some backend dumps core, send SIGSTOP,
- * rather than SIGQUIT, to all its peers. This lets the wily
- * post_hacker collect core dumps from everyone.
- */
- SendStop = true;
- break;
- case 't':
- {
- const char *tmp = get_stats_option_name(optarg);
- if (tmp)
- {
- SetConfigOption(tmp, "true", PGC_POSTMASTER, PGC_S_ARGV);
- }
- else
- {
- write_stderr("%s: invalid argument for option -t: \"%s\"\n",
- progname, optarg);
- ExitPostmaster(1);
- }
- break;
- }
- case 'W':
- SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
- break;
- case 'c':
- case '-':
- {
- char *name,
- *value;
- ParseLongOption(optarg, &name, &value);
- if (!value)
- {
- if (opt == '-')
- ereport(ERROR,
- (errcode(ERRCODE_SYNTAX_ERROR),
- errmsg("--%s requires a value",
- optarg)));
- else
- ereport(ERROR,
- (errcode(ERRCODE_SYNTAX_ERROR),
- errmsg("-c %s requires a value",
- optarg)));
- }
- SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
- free(name);
- if (value)
- free(value);
- break;
- }
- default:
- write_stderr("Try \"%s --help\" for more information.\n",
- progname);
- ExitPostmaster(1);
- }
- }
- /*
- * Postmaster accepts no non-option switch arguments.
- */
- if (optind < argc)
- {
- write_stderr("%s: invalid argument: \"%s\"\n",
- progname, argv[optind]);
- write_stderr("Try \"%s --help\" for more information.\n",
- progname);
- ExitPostmaster(1);
- }
- /*
- * Locate the proper configuration files and data directory, and read
- * postgresql.conf for the first time.
- */
- if (!SelectConfigFiles(userDoption, progname))
- ExitPostmaster(2);
- if (output_config_variable != NULL)
- {
- /*
- * permission is handled because the user is reading inside the data
- * dir
- */
- puts(GetConfigOption(output_config_variable, false, false));
- ExitPostmaster(0);
- }
- /* Verify that DataDir looks reasonable */
- checkDataDir();
- /* And switch working directory into it */
- ChangeToDataDir();
- /*
- * Check for invalid combinations of GUC settings.
- */
- if (ReservedBackends >= MaxConnections)
- {
- write_stderr("%s: superuser_reserved_connections must be less than max_connections\n", progname);
- ExitPostmaster(1);
- }
- if (max_wal_senders >= MaxConnections)
- {
- write_stderr("%s: max_wal_senders must be less than max_connections\n", progname);
- ExitPostmaster(1);
- }
- if (XLogArchiveMode && wal_level == WAL_LEVEL_MINIMAL)
- ereport(ERROR,
- (errmsg("WAL archival (archive_mode=on) requires wal_level \"archive\", \"hot_standby\" or \"logical\"")));
- if (max_wal_senders > 0 && wal_level == WAL_LEVEL_MINIMAL)
- ereport(ERROR,
- (errmsg("WAL streaming (max_wal_senders > 0) requires wal_level \"archive\", \"hot_standby\" or \"logical\"")));
- /*
- * Other one-time internal sanity checks can go here, if they are fast.
- * (Put any slow processing further down, after postmaster.pid creation.)
- */
- if (!CheckDateTokenTables())
- {
- write_stderr("%s: invalid datetoken tables, please fix\n", progname);
- ExitPostmaster(1);
- }
- /*
- * Now that we are done processing the postmaster arguments, reset
- * getopt(3) library so that it will work correctly in subprocesses.
- */
- optind = 1;
- #ifdef HAVE_INT_OPTRESET
- optreset = 1; /* some systems need this too */
- #endif
- /* For debugging: display postmaster environment */
- {
- extern char **environ;
- char **p;
- ereport(DEBUG3,
- (errmsg_internal("%s: PostmasterMain: initial environment dump:",
- progname)));
- ereport(DEBUG3,
- (errmsg_internal("-----------------------------------------")));
- for (p = environ; *p; ++p)
- ereport(DEBUG3,
- (errmsg_internal("\t%s", *p)));
- ereport(DEBUG3,
- (errmsg_internal("-----------------------------------------")));
- }
- /*
- * Create lockfile for data directory.
- *
- * We want to do this before we try to grab the input sockets, because the
- * data directory interlock is more reliable than the socket-file
- * interlock (thanks to whoever decided to put socket files in /tmp :-().
- * For the same reason, it's best to grab the TCP socket(s) before the
- * Unix socket(s).
- */
- CreateDataDirLockFile(true);
- /*
- * Initialize SSL library, if specified.
- */
- #ifdef USE_SSL
- if (EnableSSL)
- secure_initialize();
- #endif
- /*
- * process any libraries that should be preloaded at postmaster start
- */
- process_shared_preload_libraries();
- /*
- * Now that loadable modules have had their chance to register background
- * workers, calculate MaxBackends.
- */
- InitializeMaxBackends();
- /*
- * Establish input sockets.
- */
- for (i = 0; i < MAXLISTEN; i++)
- ListenSocket[i] = PGINVALID_SOCKET;
- if (ListenAddresses)
- {
- char *rawstring;
- List *elemlist;
- ListCell *l;
- int success = 0;
- /* Need a modifiable copy of ListenAddresses */
- rawstring = pstrdup(ListenAddresses);
- /* Parse string into list of hostnames */
- if (!SplitIdentifierString(rawstring, ',', &elemlist))
- {
- /* syntax error in list */
- ereport(FATAL,
- (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
- errmsg("invalid list syntax in parameter \"%s\"",
- "listen_addresses")));
- }
- foreach(l, elemlist)
- {
- char *curhost = (char *) lfirst(l);
- if (strcmp(curhost, "*") == 0)
- status = StreamServerPort(AF_UNSPEC, NULL,
- (unsigned short) PostPortNumber,
- NULL,
- ListenSocket, MAXLISTEN);
- else
- status = StreamServerPort(AF_UNSPEC, curhost,
- (unsigned short) PostPortNumber,
- NULL,
- ListenSocket, MAXLISTEN);
- if (status == STATUS_OK)
- {
- success++;
- /* record the first successful host addr in lockfile */
- if (!listen_addr_saved)
- {
- AddToDataDirLockFile(LOCK_FILE_LINE_LISTEN_ADDR, curhost);
- listen_addr_saved = true;
- }
- }
- else
- ereport(WARNING,
- (errmsg("could not create listen socket for \"%s\"",
- curhost)));
- }
- if (!success && elemlist != NIL)
- ereport(FATAL,
- (errmsg("could not create any TCP/IP sockets")));
- list_free(elemlist);
- pfree(rawstring);
- }
- #ifdef USE_BONJOUR
- /* Register for Bonjour only if we opened TCP socket(s) */
- if (enable_bonjour && ListenSocket[0] != PGINVALID_SOCKET)
- {
- DNSServiceErrorType err;
- /*
- * We pass 0 for interface_index, which will result in registering on
- * all "applicable" interfaces. It's not entirely clear from the
- * DNS-SD docs whether this would be appropriate if we have bound to
- * just a subset of the available network interfaces.
- */
- err = DNSServiceRegister(&bonjour_sdref,
- 0,
- 0,
- bonjour_name,
- "_postgresql._tcp.",
- NULL,
- NULL,
- htons(PostPortNumber),
- 0,
- NULL,
- NULL,
- NULL);
- if (err != kDNSServiceErr_NoError)
- elog(LOG, "DNSServiceRegister() failed: error code %ld",
- (long) err);
- /*
- * We don't bother to read the mDNS daemon's reply, and we expect that
- * it will automatically terminate our registration when the socket is
- * closed at postmaster termination. So there's nothing more to be
- * done here. However, the bonjour_sdref is kept around so that
- * forked children can close their copies of the socket.
- */
- }
- #endif
- #ifdef HAVE_UNIX_SOCKETS
- if (Unix_socket_directories)
- {
- char *rawstring;
- List *elemlist;
- ListCell *l;
- int success = 0;
- /* Need a modifiable copy of Unix_socket_directories */
- rawstring = pstrdup(Unix_socket_directories);
- /* Parse string into list of directories */
- if (!SplitDirectoriesString(rawstring, ',', &elemlist))
- {
- /* syntax error in list */
- ereport(FATAL,
- (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
- errmsg("invalid list syntax in parameter \"%s\"",
- "unix_socket_directories")));
- }
- foreach(l, elemlist)
- {
- char *socketdir = (char *) lfirst(l);
- status = StreamServerPort(AF_UNIX, NULL,
- (unsigned short) PostPortNumber,
- socketdir,
- ListenSocket, MAXLISTEN);
- if (status == STATUS_OK)
- {
- success++;
- /* record the first successful Unix socket in lockfile */
- if (success == 1)
- AddToDataDirLockFile(LOCK_FILE_LINE_SOCKET_DIR, socketdir);
- }
- else
- ereport(WARNING,
- (errmsg("could not create Unix-domain socket in directory \"%s\"",
- socketdir)));
- }
- if (!success && elemlist != NIL)
- ereport(FATAL,
- (errmsg("could not create any Unix-domain sockets")));
- list_free_deep(elemlist);
- pfree(rawstring);
- }
- #endif
- /*
- * check that we have some socket to listen on
- */
- if (ListenSocket[0] == PGINVALID_SOCKET)
- ereport(FATAL,
- (errmsg("no socket created for listening")));
- /*
- * If no valid TCP ports, write an empty line for listen address,
- * indicating the Unix socket must be used. Note that this line is not
- * added to the lock file until there is a socket backing it.
- */
- if (!listen_addr_saved)
- AddToDataDirLockFile(LOCK_FILE_LINE_LISTEN_ADDR, "");
- /*
- * Set up shared memory and semaphores.
- */
- reset_shared(PostPortNumber);
- /*
- * Estimate number of openable files. This must happen after setting up
- * semaphores, because on some platforms semaphores count as open files.
- */
- set_max_safe_fds();
- /*
- * Set reference point for stack-depth checking.
- */
- set_stack_base();
- /*
- * Initialize pipe (or process handle on Windows) that allows children to
- * wake up from sleep on postmaster death.
- */
- InitPostmasterDeathWatchHandle();
- #ifdef WIN32
- /*
- * Initialize I/O completion port used to deliver list of dead children.
- */
- win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
- if (win32ChildQueue == NULL)
- ereport(FATAL,
- (errmsg("could not create I/O completion port for child queue")));
- #endif
- /*
- * Record postmaster options. We delay this till now to avoid recording
- * bogus options (eg, NBuffers too high for available memory).
- */
- if (!CreateOptsFile(argc, argv, my_exec_path))
- ExitPostmaster(1);
- #ifdef EXEC_BACKEND
- /* Write out nondefault GUC settings for child processes to use */
- write_nondefault_variables(PGC_POSTMASTER);
- #endif
- /*
- * Write the external PID file if requested
- */
- if (external_pid_file)
- {
- FILE *fpidfile = fopen(external_pid_file, "w");
- if (fpidfile)
- {
- fprintf(fpidfile, "%d\n", MyProcPid);
- fclose(fpidfile);
- /* Make PID file world readable */
- if (chmod(external_pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) != 0)
- write_stderr("%s: could not change permissions of external PID file \"%s\": %s\n",
- progname, external_pid_file, strerror(errno));
- }
- else
- write_stderr("%s: could not write external PID file \"%s\": %s\n",
- progname, external_pid_file, strerror(errno));
- on_proc_exit(unlink_external_pid_file, 0);
- }
- /*
- * If enabled, start up syslogger collection subprocess
- */
- SysLoggerPID = SysLogger_Start();
- /*
- * Reset whereToSendOutput from DestDebug (its starting state) to
- * DestNone. This stops ereport from sending log messages to stderr unless
- * Log_destination permits. We don't do this until the postmaster is
- * fully launched, since startup failures may as well be reported to
- * stderr.
- *
- * If we are in fact disabling logging to stderr, first emit a log message
- * saying so, to provide a breadcrumb trail for users who may not remember
- * that their logging is configured to go somewhere else.
- */
- if (!(Log_destination & LOG_DESTINATION_STDERR))
- ereport(LOG,
- (errmsg("ending log output to stderr"),
- errhint("Future log output will go to log destination \"%s\".",
- Log_destination_string)));
- whereToSendOutput = DestNone;
- /*
- * Initialize stats collection subsystem (this does NOT start the
- * collector process!)
- */
- pgstat_init();
- /*
- * Initialize the autovacuum subsystem (again, no process start yet)
- */
- autovac_init();
- /*
- * Load configuration files for client authentication.
- */
- if (!load_hba())
- {
- /*
- * It makes no sense to continue if we fail to load the HBA file,
- * since there is no way to connect to the database in this case.
- */
- ereport(FATAL,
- (errmsg("could not load pg_hba.conf")));
- }
- if (!load_ident())
- {
- /*
- * We can start up without the IDENT file, although it means that you
- * cannot log in using any of the authentication methods that need a
- * user name mapping. load_ident() already logged the details of error
- * to the log.
- */
- }
- /*
- * Remove old temporary files. At this point there can be no other
- * Postgres processes running in this directory, so this should be safe.
- */
- RemovePgTempFiles();
- /*
- * Remember postmaster startup time
- */
- PgStartTime = GetCurrentTimestamp();
- /* PostmasterRandom wants its own copy */
- gettimeofday(&random_start_time, NULL);
- /*
- * We're ready to rock and roll...
- */
- StartupPID = StartupDataBase();
- Assert(StartupPID != 0);
- pmState = PM_STARTUP;
- /* Some workers may be scheduled to start now */
- maybe_start_bgworker();
- status = ServerLoop();
- /*
- * ServerLoop probably shouldn't ever return, but if it does, close down.
- */
- ExitPostmaster(status != STATUS_OK);
- abort(); /* not reached */
- }
- /*
- * on_proc_exit callback to delete external_pid_file
- */
- static void
- unlink_external_pid_file(int status, Datum arg)
- {
- if (external_pid_file)
- unlink(external_pid_file);
- }
- /*
- * Compute and check the directory paths to files that are part of the
- * installation (as deduced from the postgres executable's own location)
- */
- static void
- getInstallationPaths(const char *argv0)
- {
- DIR *pdir;
- /* Locate the postgres executable itself */
- if (find_my_exec(argv0, my_exec_path) < 0)
- elog(FATAL, "%s: could not locate my own executable path", argv0);
- #ifdef EXEC_BACKEND
- /* Locate executable backend before we change working directory */
- if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
- postgres_exec_path) < 0)
- ereport(FATAL,
- (errmsg("%s: could not locate matching postgres executable",
- argv0)));
- #endif
- /*
- * Locate the pkglib directory --- this has to be set early in case we try
- * to load any modules from it in response to postgresql.conf entries.
- */
- get_pkglib_path(my_exec_path, pkglib_path);
- /*
- * Verify that there's a readable directory there; otherwise the Postgres
- * installation is incomplete or corrupt. (A typical cause of this
- * failure is that the postgres executable has been moved or hardlinked to
- * some directory that's not a sibling of the installation lib/
- * directory.)
- */
- pdir = AllocateDir(pkglib_path);
- if (pdir == NULL)
- ereport(ERROR,
- (errcode_for_file_access(),
- errmsg("could not open directory \"%s\": %m",
- pkglib_path),
- errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
- my_exec_path)));
- FreeDir(pdir);
- /*
- * XXX is it worth similarly checking the share/ directory? If the lib/
- * directory is there, then share/ probably is too.
- */
- }
- /*
- * Validate the proposed data directory
- */
- static void
- checkDataDir(void)
- {
- char path[MAXPGPATH];
- FILE *fp;
- struct stat stat_buf;
- Assert(DataDir);
- if (stat(DataDir, &stat_buf) != 0)
- {
- if (errno == ENOENT)
- ereport(FATAL,
- (errcode_for_file_access(),
- errmsg("data directory \"%s\" does not exist",
- DataDir)));
- else
- ereport(FATAL,
- (errcode_for_file_access(),
- errmsg("could not read permissions of directory \"%s\": %m",
- DataDir)));
- }
- /* eventual chdir would fail anyway, but let's test ... */
- if (!S_ISDIR(stat_buf.st_mode))
- ereport(FATAL,
- (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
- errmsg("specified data directory \"%s\" is not a directory",
- DataDir)));
- /*
- * Check that the directory belongs to my userid; if not, reject.
- *
- * This check is an essential part of the interlock that prevents two
- * postmasters from starting in the same directory (see CreateLockFile()).
- * Do not remove or weaken it.
- *
- * XXX can we safely enable this check on Windows?
- */
- #if !defined(WIN32) && !defined(__CYGWIN__)
- if (stat_buf.st_uid != geteuid())
- ereport(FATAL,
- (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
- errmsg("data directory \"%s\" has wrong ownership",
- DataDir),
- errhint("The server must be started by the user that owns the data directory.")));
- #endif
- /*
- * Check if the directory has group or world access. If so, reject.
- *
- * It would be possible to allow weaker constraints (for example, allow
- * group access) but we cannot make a general assumption that that is
- * okay; for example there are platforms where nearly all users
- * customarily belong to the same group. Perhaps this test should be
- * configurable.
- *
- * XXX temporarily suppress check when on Windows, because there may not
- * be proper support for Unix-y file permissions. Need to think of a
- * reasonable check to apply on Windows.
- */
- #if !defined(WIN32) && !defined(__CYGWIN__)
- if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
- ereport(FATAL,
- (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
- errmsg("data directory \"%s\" has group or world access",
- DataDir),
- errdetail("Permissions should be u=rwx (0700).")));
- #endif
- /* Look for PG_VERSION before looking for pg_control */
- ValidatePgVersion(DataDir);
- snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
- fp = AllocateFile(path, PG_BINARY_R);
- if (fp == NULL)
- {
- write_stderr("%s: could not find the database system\n"
- "Expected to find it in the directory \"%s\",\n"
- "but could not open file \"%s\": %s\n",
- progname, DataDir, path, strerror(errno));
- ExitPostmaster(2);
- }
- FreeFile(fp);
- }
- /*
- * Determine how long should we let ServerLoop sleep.
- *
- * In normal conditions we wait at most one minute, to ensure that the other
- * background tasks handled by ServerLoop get done even when no requests are
- * arriving. However, if there are background workers waiting to be started,
- * we don't actually sleep so that they are quickly serviced.
- */
- static void
- DetermineSleepTime(struct timeval * timeout)
- {
- TimestampTz next_wakeup = 0;
- /*
- * Normal case: either there are no background workers at all, or we're in
- * a shutdown sequence (during which we ignore bgworkers altogether).
- */
- if (Shutdown > NoShutdown ||
- (!StartWorkerNeeded && !HaveCrashedWorker))
- {
- if (AbortStartTime > 0)
- {
- /* time left to abort; clamp to 0 in case it already expired */
- timeout->tv_sec = Max(SIGKILL_CHILDREN_AFTER_SECS -
- (time(NULL) - AbortStartTime), 0);
- timeout->tv_usec = 0;
- }
- else
- {
- timeout->tv_sec = 60;
- timeout->tv_usec = 0;
- }
- return;
- }
- if (StartWorkerNeeded)
- {
- timeout->tv_sec = 0;
- timeout->tv_usec = 0;
- return;
- }
- if (HaveCrashedWorker)
- {
- slist_mutable_iter siter;
- /*
- * When there are crashed bgworkers, we sleep just long enough that
- * they are restarted when they request to be. Scan the list to
- * determine the minimum of all wakeup times according to most recent
- * crash time and requested restart interval.
- */
- slist_foreach_modify(siter, &BackgroundWorkerList)
- {
- RegisteredBgWorker *rw;
- TimestampTz this_wakeup;
- rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
- if (rw->rw_crashed_at == 0)
- continue;
- if (rw->rw_worker.bgw_restart_time == BGW_NEVER_RESTART
- || rw->rw_terminate)
- {
- ForgetBackgroundWorker(&siter);
- continue;
- }
- this_wakeup = TimestampTzPlusMilliseconds(rw->rw_crashed_at,
- 1000L * rw->rw_worker.bgw_restart_time);
- if (next_wakeup == 0 || this_wakeup < next_wakeup)
- next_wakeup = this_wakeup;
- }
- }
- if (next_wakeup != 0)
- {
- long secs;
- int microsecs;
- TimestampDifference(GetCurrentTimestamp(), next_wakeup,
- &secs, µsecs);
- timeout->tv_sec = secs;
- timeout->tv_usec = microsecs;
- /* Ensure we don't exceed one minute */
- if (timeout->tv_sec > 60)
- {
- timeout->tv_sec = 60;
- timeout->tv_usec = 0;
- }
- }
- else
- {
- timeout->tv_sec = 60;
- timeout->tv_usec = 0;
- }
- }
- /*
- * Main idle loop of postmaster
- */
- static int
- ServerLoop(void)
- {
- fd_set readmask;
- int nSockets;
- time_t now,
- last_touch_time;
- last_touch_time = time(NULL);
- nSockets = initMasks(&readmask);
- for (;;)
- {
- fd_set rmask;
- int selres;
- /*
- * Wait for a connection request to arrive.
- *
- * If we are in PM_WAIT_DEAD_END state, then we don't want to accept
- * any new connections, so we don't call select() at all; just sleep
- * for a little bit with signals unblocked.
- */
- memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
- PG_SETMASK(&UnBlockSig);
- if (pmState == PM_WAIT_DEAD_END)
- {
- pg_usleep(100000L); /* 100 msec seems reasonable */
- selres = 0;
- }
- else
- {
- /* must set timeout each time; some OSes change it! */
- struct timeval timeout;
- DetermineSleepTime(&timeout);
- selres = select(nSockets, &rmask, NULL, NULL, &timeout);
- }
- /*
- * Block all signals until we wait again. (This makes it safe for our
- * signal handlers to do nontrivial work.)
- */
- PG_SETMASK(&BlockSig);
- /* Now check the select() result */
- if (selres < 0)
- {
- if (errno != EINTR && errno != EWOULDBLOCK)
- {
- ereport(LOG,
- (errcode_for_socket_access(),
- errmsg("select() failed in postmaster: %m")));
- return STATUS_ERROR;
- }
- }
- /*
- * New connection pending on any of our sockets? If so, fork a child
- * process to deal with it.
- */
- if (selres > 0)
- {
- int i;
- for (i = 0; i < MAXLISTEN; i++)
- {
- if (ListenSocket[i] == PGINVALID_SOCKET)
- break;
- if (FD_ISSET(ListenSocket[i], &rmask))
- {
- Port *port;
- port = ConnCreate(ListenSocket[i]);
- if (port)
- {
- BackendStartup(port);
- /*
- * We no longer need the open socket or port structure
- * in this process
- */
- StreamClose(port->sock);
- ConnFree(port);
- }
- }
- }
- }
- /* If we have lost the log collector, try to start a new one */
- if (SysLoggerPID == 0 && Logging_collector)
- SysLoggerPID = SysLogger_Start();
- /*
- * If no background writer process is running, and we are not in a
- * state that prevents it, start one. It doesn't matter if this
- * fails, we'll just try again later. Likewise for the checkpointer.
- */
- if (pmState == PM_RUN || pmState == PM_RECOVERY ||
- pmState == PM_HOT_STANDBY)
- {
- if (CheckpointerPID == 0)
- CheckpointerPID = StartCheckpointer();
- if (BgWriterPID == 0)
- BgWriterPID = StartBackgroundWriter();
- }
- /*
- * Likewise, if we have lost the walwriter process, try to start a new
- * one. But this is needed only in normal operation (else we cannot
- * be writing any new WAL).
- */
- if (WalWriterPID == 0 && pmState == PM_RUN)
- WalWriterPID = StartWalWriter();
- /*
- * If we have lost the autovacuum launcher, try to start a new one. We
- * don't want autovacuum to run in binary upgrade mode because
- * autovacuum might update relfrozenxid for empty tables before the
- * physical files are put in place.
- */
- if (!IsBinaryUpgrade && AutoVacPID == 0 &&
- (AutoVacuumingActive() || start_autovac_launcher) &&
- pmState == PM_RUN)
- {
- AutoVacPID = StartAutoVacLauncher();
- if (AutoVacPID != 0)
- start_autovac_launcher = false; /* signal processed */
- }
- /* If we have lost the archiver, try to start a new one */
- if (XLogArchivingActive() && PgArchPID == 0 && pmState == PM_RUN)
- PgArchPID = pgarch_start();
- /* If we have lost the stats collector, try to start a new one */
- if (PgStatPID == 0 && pmState == PM_RUN)
- PgStatPID = pgstat_start();
- /* If we need to signal the autovacuum launcher, do so now */
- if (avlauncher_needs_signal)
- {
- avlauncher_needs_signal = false;
- if (AutoVacPID != 0)
- kill(AutoVacPID, SIGUSR2);
- }
- /* Get other worker processes running, if needed */
- if (StartWorkerNeeded || HaveCrashedWorker)
- maybe_start_bgworker();
- /*
- * Touch Unix socket and lock files every 58 minutes, to ensure that
- * they are not removed by overzealous /tmp-cleaning tasks. We assume
- * no one runs cleaners with cutoff times of less than an hour ...
- */
- now = time(NULL);
- if (now - last_touch_time >= 58 * SECS_PER_MINUTE)
- {
- TouchSocketFiles();
- TouchSocketLockFiles();
- last_touch_time = now;
- }
- /*
- * If we already sent SIGQUIT to children and they are slow to shut
- * down, it's time to send them SIGKILL. This doesn't happen
- * normally, but under certain conditions backends can get stuck while
- * shutting down. This is a last measure to get them unwedged.
- *
- * Note we also do this during recovery from a process crash.
- */
- if ((Shutdown >= ImmediateShutdown || (FatalError && !SendStop)) &&
- AbortStartTime > 0 &&
- now - AbortStartTime >= SIGKILL_CHILDREN_AFTER_SECS)
- {
- /* We were gentle with them before. Not anymore */
- TerminateChildren(SIGKILL);
- /* reset flag so we don't SIGKILL again */
- AbortStartTime = 0;
- /*
- * Additionally, unless we're recovering from a process crash,
- * it's now the time for postmaster to abandon ship.
- */
- if (!FatalError)
- ExitPostmaster(1);
- }
- }
- }
- /*
- * Initialise the masks for select() for the ports we are listening on.
- * Return the number of sockets to listen on.
- */
- static int
- initMasks(fd_set *rmask)
- {
- int maxsock = -1;
- int i;
- FD_ZERO(rmask);
- for (i = 0; i < MAXLISTEN; i++)
- {
- int fd = ListenSocket[i];
- if (fd == PGINVALID_SOCKET)
- break;
- FD_SET(fd, rmask);
- if (fd > maxsock)
- maxsock = fd;
- }
- return maxsock + 1;
- }
- /*
- * Read a client's startup packet and do something according to it.
- *
- * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
- * not return at all.
- *
- * (Note that ereport(FATAL) stuff is sent to the client, so only use it
- * if that's what you want. Return STATUS_ERROR if you don't want to
- * send anything to the client, which would typically be appropriate
- * if we detect a communications failure.)
- */
- static int
- ProcessStartupPacket(Port *port, bool SSLdone)
- {
- int32 len;
- void *buf;
- ProtocolVersion proto;…
Large files files are truncated, but you can click here to view the full file