1 /*-------------------------------------------------------------------------
4 * This program acts as a clearing house for requests to the
5 * POSTGRES system. Frontend programs send a startup message
6 * to the Postmaster and the postmaster uses the info in the
7 * message to setup a backend process.
9 * The postmaster also manages system-wide operations such as
10 * startup and shutdown. The postmaster itself doesn't do those
11 * operations, mind you --- it just forks off a subprocess to do them
12 * at the right times. It also takes care of resetting the system
13 * if a backend crashes.
15 * The postmaster process creates the shared memory and semaphore
16 * pools during startup, but as a rule does not touch them itself.
17 * In particular, it is not a member of the PGPROC array of backends
18 * and so it cannot participate in lock-manager operations. Keeping
19 * the postmaster away from shared memory operations makes it simpler
20 * and more reliable. The postmaster is almost always able to recover
21 * from crashes of individual backends by resetting shared memory;
22 * if it did much with shared memory then it would be prone to crashing
23 * along with the backends.
25 * When a request message is received, we now fork() immediately.
26 * The child process performs authentication of the request, and
27 * then becomes a backend if successful. This allows the auth code
28 * to be written in a simple single-threaded style (as opposed to the
29 * crufty "poor man's multitasking" code that used to be needed).
30 * More importantly, it ensures that blockages in non-multithreaded
31 * libraries like SSL or PAM cannot cause denial of service to other
35 * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
36 * Portions Copyright (c) 1994, Regents of the University of California
40 * src/backend/postmaster/postmaster.c
45 * The Postmaster sets up shared memory data structures
49 * The Postmaster shares memory with the backends but should avoid
50 * touching shared memory, so as not to become stuck if a crashing
51 * backend screws up locks or shared memory. Likewise, the Postmaster
52 * should never block on messages from frontend clients.
55 * The Postmaster cleans up after backends if they have an emergency
56 * exit and/or core dump.
59 * Use write_stderr() only for reporting "interactive" errors
60 * (essentially, bogus arguments on the command line). Once the
61 * postmaster is launched, use ereport().
63 *-------------------------------------------------------------------------
74 #include <sys/socket.h>
76 #include <sys/param.h>
77 #include <netinet/in.h>
78 #include <arpa/inet.h>
82 #ifdef HAVE_SYS_SELECT_H
83 #include <sys/select.h>
91 #include <systemd/sd-daemon.h>
94 #ifdef HAVE_PTHREAD_IS_THREADED_NP
98 #include "access/transam.h"
99 #include "access/xlog.h"
100 #include "bootstrap/bootstrap.h"
101 #include "catalog/pg_control.h"
102 #include "common/ip.h"
103 #include "lib/ilist.h"
104 #include "libpq/auth.h"
105 #include "libpq/libpq.h"
106 #include "libpq/pqsignal.h"
107 #include "miscadmin.h"
108 #include "pg_getopt.h"
110 #include "postmaster/autovacuum.h"
111 #include "postmaster/bgworker_internals.h"
112 #include "postmaster/fork_process.h"
113 #include "postmaster/pgarch.h"
114 #include "postmaster/postmaster.h"
115 #include "postmaster/syslogger.h"
116 #include "replication/logicallauncher.h"
117 #include "replication/walsender.h"
118 #include "storage/fd.h"
119 #include "storage/ipc.h"
120 #include "storage/pg_shmem.h"
121 #include "storage/pmsignal.h"
122 #include "storage/proc.h"
123 #include "tcop/tcopprot.h"
124 #include "utils/builtins.h"
125 #include "utils/datetime.h"
126 #include "utils/dynamic_loader.h"
127 #include "utils/memutils.h"
128 #include "utils/pidfile.h"
129 #include "utils/ps_status.h"
130 #include "utils/timeout.h"
131 #include "utils/varlena.h"
134 #include "storage/spin.h"
139 * Possible types of a backend. Beyond being the possible bkend_type values in
140 * struct bkend, these are OR-able request flag bits for SignalSomeChildren()
141 * and CountChildren().
143 #define BACKEND_TYPE_NORMAL 0x0001 /* normal backend */
144 #define BACKEND_TYPE_AUTOVAC 0x0002 /* autovacuum worker process */
145 #define BACKEND_TYPE_WALSND 0x0004 /* walsender process */
146 #define BACKEND_TYPE_BGWORKER 0x0008 /* bgworker process */
147 #define BACKEND_TYPE_ALL 0x000F /* OR of all the above */
149 #define BACKEND_TYPE_WORKER (BACKEND_TYPE_AUTOVAC | BACKEND_TYPE_BGWORKER)
152 * List of active backends (or child processes anyway; we don't actually
153 * know whether a given child has become a backend or is still in the
154 * authorization phase). This is used mainly to keep track of how many
155 * children we have and send them appropriate signals when necessary.
157 * "Special" children such as the startup, bgwriter and autovacuum launcher
158 * tasks are not in this list. Autovacuum worker and walsender are in it.
159 * Also, "dead_end" children are in it: these are children launched just for
160 * the purpose of sending a friendly rejection message to a would-be client.
161 * We must track them because they are attached to shared memory, but we know
162 * they will never become live backends. dead_end children are not assigned a
165 * Background workers are in this list, too.
169 pid_t pid; /* process id of backend */
170 int32 cancel_key; /* cancel key for cancels for this backend */
171 int child_slot; /* PMChildSlot for this backend, if any */
174 * Flavor of backend or auxiliary process. Note that BACKEND_TYPE_WALSND
175 * backends initially announce themselves as BACKEND_TYPE_NORMAL, so if
176 * bkend_type is normal, you should check for a recent transition.
179 bool dead_end; /* is it going to send an error and quit? */
180 bool bgworker_notify; /* gets bgworker start/stop notifications */
181 dlist_node elem; /* list link in BackendList */
184 static dlist_head BackendList = DLIST_STATIC_INIT(BackendList);
187 static Backend *ShmemBackendArray;
190 BackgroundWorker *MyBgworkerEntry = NULL;
194 /* The socket number we are listening for connections on */
197 /* The directory names for Unix socket(s) */
198 char *Unix_socket_directories;
200 /* The TCP listen address(es) */
201 char *ListenAddresses;
204 * ReservedBackends is the number of backends reserved for superuser use.
205 * This number is taken out of the pool size given by MaxBackends so
206 * number of backend slots available to non-superusers is
207 * (MaxBackends - ReservedBackends). Note what this really means is
208 * "if there are <= ReservedBackends connections available, only superusers
209 * can make new connections" --- pre-existing superuser connections don't
210 * count against the limit.
212 int ReservedBackends;
214 /* The socket(s) we're listening to. */
216 static pgsocket ListenSocket[MAXLISTEN];
219 * Set by the -o option
221 static char ExtraOptions[MAXPGPATH];
224 * These globals control the behavior of the postmaster in case some
225 * backend dumps core. Normally, it kills all peers of the dead backend
226 * and reinitializes shared memory. By specifying -s or -n, we can have
227 * the postmaster stop (rather than kill) peers and not reinitialize
228 * shared data structures. (Reinit is currently dead code, though.)
230 static bool Reinit = true;
231 static int SendStop = false;
233 /* still more option variables */
234 bool EnableSSL = false;
236 int PreAuthDelay = 0;
237 int AuthenticationTimeout = 60;
239 bool log_hostname; /* for ps display and logging */
240 bool Log_connections = false;
241 bool Db_user_namespace = false;
243 bool enable_bonjour = false;
245 bool restart_after_crash = true;
247 /* PIDs of special child processes; 0 when not running */
248 static pid_t StartupPID = 0,
258 /* Startup process's status */
263 STARTUP_SIGNALED, /* we sent it a SIGQUIT or SIGKILL */
267 static StartupStatusEnum StartupStatus = STARTUP_NOT_RUNNING;
269 /* Startup/shutdown state */
271 #define SmartShutdown 1
272 #define FastShutdown 2
273 #define ImmediateShutdown 3
275 static int Shutdown = NoShutdown;
277 static bool FatalError = false; /* T if recovering from backend crash */
280 * We use a simple state machine to control startup, shutdown, and
281 * crash recovery (which is rather like shutdown followed by startup).
283 * After doing all the postmaster initialization work, we enter PM_STARTUP
284 * state and the startup process is launched. The startup process begins by
285 * reading the control file and other preliminary initialization steps.
286 * In a normal startup, or after crash recovery, the startup process exits
287 * with exit code 0 and we switch to PM_RUN state. However, archive recovery
288 * is handled specially since it takes much longer and we would like to support
289 * hot standby during archive recovery.
291 * When the startup process is ready to start archive recovery, it signals the
292 * postmaster, and we switch to PM_RECOVERY state. The background writer and
293 * checkpointer are launched, while the startup process continues applying WAL.
294 * If Hot Standby is enabled, then, after reaching a consistent point in WAL
295 * redo, startup process signals us again, and we switch to PM_HOT_STANDBY
296 * state and begin accepting connections to perform read-only queries. When
297 * archive recovery is finished, the startup process exits with exit code 0
298 * and we switch to PM_RUN state.
300 * Normal child backends can only be launched when we are in PM_RUN or
301 * PM_HOT_STANDBY state. (We also allow launch of normal
302 * child backends in PM_WAIT_BACKUP state, but only for superusers.)
303 * In other states we handle connection requests by launching "dead_end"
304 * child processes, which will simply send the client an error message and
305 * quit. (We track these in the BackendList so that we can know when they
306 * are all gone; this is important because they're still connected to shared
307 * memory, and would interfere with an attempt to destroy the shmem segment,
308 * possibly leading to SHMALL failure when we try to make a new one.)
309 * In PM_WAIT_DEAD_END state we are waiting for all the dead_end children
310 * to drain out of the system, and therefore stop accepting connection
311 * requests at all until the last existing child has quit (which hopefully
312 * will not be very long).
314 * Notice that this state variable does not distinguish *why* we entered
315 * states later than PM_RUN --- Shutdown and FatalError must be consulted
316 * to find that out. FatalError is never true in PM_RECOVERY_* or PM_RUN
317 * states, nor in PM_SHUTDOWN states (because we don't enter those states
318 * when trying to recover from a crash). It can be true in PM_STARTUP state,
319 * because we don't clear it until we've successfully started WAL redo.
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
333 PM_SHUTDOWN_2, /* waiting for archiver and walsenders to
335 PM_WAIT_DEAD_END, /* waiting for dead_end children to exit */
336 PM_NO_CHILDREN /* all important children have exited */
339 static PMState pmState = PM_INIT;
341 /* Start time of SIGKILL timeout during immediate shutdown or child crash */
342 /* Zero means timeout is not running */
343 static time_t AbortStartTime = 0;
345 /* Length of said timeout */
346 #define SIGKILL_CHILDREN_AFTER_SECS 5
348 static bool ReachedNormalRunning = false; /* T if we've reached PM_RUN */
350 bool ClientAuthInProgress = false; /* T during new-client
353 bool redirection_done = false; /* stderr redirected for syslogger? */
355 /* received START_AUTOVAC_LAUNCHER signal */
356 static volatile sig_atomic_t start_autovac_launcher = false;
358 /* the launcher needs to be signalled to communicate some condition */
359 static volatile bool avlauncher_needs_signal = false;
361 /* received START_WALRECEIVER signal */
362 static volatile sig_atomic_t WalReceiverRequested = false;
364 /* set when there's a worker that needs to be started up */
365 static volatile bool StartWorkerNeeded = true;
366 static volatile bool HaveCrashedWorker = false;
368 #ifndef HAVE_STRONG_RANDOM
370 * State for assigning cancel keys.
371 * Also, the global MyCancelKey passes the cancel key assigned to a given
372 * backend from the postmaster to that backend (via fork).
374 static unsigned int random_seed = 0;
375 static struct timeval random_start_time;
379 /* Set when and if SSL has been initialized properly */
380 static bool LoadedSSL = false;
384 static DNSServiceRef bonjour_sdref = NULL;
388 * postmaster.c - function prototypes
390 static void CloseServerPorts(int status, Datum arg);
391 static void unlink_external_pid_file(int status, Datum arg);
392 static void getInstallationPaths(const char *argv0);
393 static void checkDataDir(void);
394 static Port *ConnCreate(int serverFd);
395 static void ConnFree(Port *port);
396 static void reset_shared(int port);
397 static void SIGHUP_handler(SIGNAL_ARGS);
398 static void pmdie(SIGNAL_ARGS);
399 static void reaper(SIGNAL_ARGS);
400 static void sigusr1_handler(SIGNAL_ARGS);
401 static void startup_die(SIGNAL_ARGS);
402 static void dummy_handler(SIGNAL_ARGS);
403 static void StartupPacketTimeoutHandler(void);
404 static void CleanupBackend(int pid, int exitstatus);
405 static bool CleanupBackgroundWorker(int pid, int exitstatus);
406 static void HandleChildCrash(int pid, int exitstatus, const char *procname);
407 static void LogChildExit(int lev, const char *procname,
408 int pid, int exitstatus);
409 static void PostmasterStateMachine(void);
410 static void BackendInitialize(Port *port);
411 static void BackendRun(Port *port) pg_attribute_noreturn();
412 static void ExitPostmaster(int status) pg_attribute_noreturn();
413 static int ServerLoop(void);
414 static int BackendStartup(Port *port);
415 static int ProcessStartupPacket(Port *port, bool SSLdone);
416 static void processCancelRequest(Port *port, void *pkt);
417 static int initMasks(fd_set *rmask);
418 static void report_fork_failure_to_client(Port *port, int errnum);
419 static CAC_state canAcceptConnections(void);
420 static bool RandomCancelKey(int32 *cancel_key);
421 static void signal_child(pid_t pid, int signal);
422 static bool SignalSomeChildren(int signal, int targets);
423 static void TerminateChildren(int signal);
425 #define SignalChildren(sig) SignalSomeChildren(sig, BACKEND_TYPE_ALL)
427 static int CountChildren(int target);
428 static bool assign_backendlist_entry(RegisteredBgWorker *rw);
429 static void maybe_start_bgworkers(void);
430 static bool CreateOptsFile(int argc, char *argv[], char *fullprogname);
431 static pid_t StartChildProcess(AuxProcType type);
432 static void StartAutovacuumWorker(void);
433 static void MaybeStartWalReceiver(void);
434 static void InitPostmasterDeathWatchHandle(void);
437 * Archiver is allowed to start up at the current postmaster state?
439 * If WAL archiving is enabled always, we are allowed to start archiver
440 * even during recovery.
442 #define PgArchStartupAllowed() \
443 ((XLogArchivingActive() && pmState == PM_RUN) || \
444 (XLogArchivingAlways() && \
445 (pmState == PM_RECOVERY || pmState == PM_HOT_STANDBY)))
450 #define WNOHANG 0 /* ignored, so any integer value will do */
452 static pid_t waitpid(pid_t pid, int *exitstatus, int options);
453 static void WINAPI pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired);
455 static HANDLE win32ChildQueue;
462 } win32_deadchild_waitinfo;
465 static pid_t backend_forkexec(Port *port);
466 static pid_t internal_forkexec(int argc, char *argv[], Port *port);
468 /* Type for a socket that can be inherited to a client process */
472 SOCKET origsocket; /* Original socket value, or PGINVALID_SOCKET
474 WSAPROTOCOL_INFO wsainfo;
477 typedef int InheritableSocket;
481 * Structure contains all variables passed to exec:ed backends
486 InheritableSocket portsocket;
487 char DataDir[MAXPGPATH];
488 pgsocket ListenSocket[MAXLISTEN];
492 unsigned long UsedShmemSegID;
494 HANDLE UsedShmemSegID;
496 void *UsedShmemSegAddr;
498 VariableCache ShmemVariableCache;
499 Backend *ShmemBackendArray;
500 #ifndef HAVE_SPINLOCKS
501 PGSemaphore *SpinlockSemaArray;
503 int NamedLWLockTrancheRequests;
504 NamedLWLockTranche *NamedLWLockTrancheArray;
505 LWLockPadded *MainLWLockArray;
506 slock_t *ProcStructLock;
507 PROC_HDR *ProcGlobal;
508 PGPROC *AuxiliaryProcs;
509 PGPROC *PreparedXactProcs;
510 PMSignalData *PMSignalState;
511 InheritableSocket pgStatSock;
513 TimestampTz PgStartTime;
514 TimestampTz PgReloadTime;
515 pg_time_t first_syslogger_file_time;
516 bool redirection_done;
517 bool IsBinaryUpgrade;
521 HANDLE PostmasterHandle;
522 HANDLE initial_signal_pipe;
523 HANDLE syslogPipe[2];
525 int postmaster_alive_fds[2];
528 char my_exec_path[MAXPGPATH];
529 char pkglib_path[MAXPGPATH];
530 char ExtraOptions[MAXPGPATH];
533 static void read_backend_variables(char *id, Port *port);
534 static void restore_backend_variables(BackendParameters *param, Port *port);
537 static bool save_backend_variables(BackendParameters *param, Port *port);
539 static bool save_backend_variables(BackendParameters *param, Port *port,
540 HANDLE childProcess, pid_t childPid);
543 static void ShmemBackendArrayAdd(Backend *bn);
544 static void ShmemBackendArrayRemove(Backend *bn);
545 #endif /* EXEC_BACKEND */
547 #define StartupDataBase() StartChildProcess(StartupProcess)
548 #define StartBackgroundWriter() StartChildProcess(BgWriterProcess)
549 #define StartCheckpointer() StartChildProcess(CheckpointerProcess)
550 #define StartWalWriter() StartChildProcess(WalWriterProcess)
551 #define StartWalReceiver() StartChildProcess(WalReceiverProcess)
553 /* Macros to check exit status of a child process */
554 #define EXIT_STATUS_0(st) ((st) == 0)
555 #define EXIT_STATUS_1(st) (WIFEXITED(st) && WEXITSTATUS(st) == 1)
556 #define EXIT_STATUS_3(st) (WIFEXITED(st) && WEXITSTATUS(st) == 3)
560 * File descriptors for pipe used to monitor if postmaster is alive.
561 * First is POSTMASTER_FD_WATCH, second is POSTMASTER_FD_OWN.
563 int postmaster_alive_fds[2] = {-1, -1};
565 /* Process handle of postmaster used for the same purpose on Windows */
566 HANDLE PostmasterHandle;
570 * Postmaster main entry point
573 PostmasterMain(int argc, char *argv[])
577 char *userDoption = NULL;
578 bool listen_addr_saved = false;
580 char *output_config_variable = NULL;
582 MyProcPid = PostmasterPid = getpid();
584 MyStartTime = time(NULL);
586 IsPostmasterEnvironment = true;
589 * for security, no dir or file created can be group or other accessible
591 umask(S_IRWXG | S_IRWXO);
594 * Initialize random(3) so we don't get the same values in every run.
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.
601 srandom((unsigned int) (MyProcPid ^ MyStartTime));
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.
609 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
611 ALLOCSET_DEFAULT_SIZES);
612 MemoryContextSwitchTo(PostmasterContext);
614 /* Initialize paths to installation files */
615 getInstallationPaths(argv[0]);
618 * Set up signal handlers for the postmaster process.
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.
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.
637 PG_SETMASK(&BlockSig);
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
648 pqsignal_no_restart(SIGUSR2, dummy_handler); /* unused, reserve for
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 */
655 pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
661 InitializeGUCOptions();
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.
670 while ((opt = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:W:-:")) != -1)
675 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
679 /* Undocumented flag used for binary upgrades */
680 IsBinaryUpgrade = true;
684 output_config_variable = strdup(optarg);
688 userDoption = strdup(optarg);
692 set_debug_options(atoi(optarg), PGC_POSTMASTER, PGC_S_ARGV);
696 SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
700 SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
704 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
708 if (!set_plan_disabling_options(optarg, PGC_POSTMASTER, PGC_S_ARGV))
710 write_stderr("%s: invalid argument for option -f: \"%s\"\n",
717 SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
721 SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
725 /* only used by interactive backend */
729 SetConfigOption("unix_socket_directories", optarg, PGC_POSTMASTER, PGC_S_ARGV);
733 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
737 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
741 /* Don't reinit shared mem after abnormal exit */
746 SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
750 /* Other options to pass to the backend on the command line */
751 snprintf(ExtraOptions + strlen(ExtraOptions),
752 sizeof(ExtraOptions) - strlen(ExtraOptions),
757 SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
761 SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
765 /* only used by single-user backend */
769 SetConfigOption("work_mem", optarg, PGC_POSTMASTER, PGC_S_ARGV);
773 SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
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.
788 const char *tmp = get_stats_option_name(optarg);
792 SetConfigOption(tmp, "true", PGC_POSTMASTER, PGC_S_ARGV);
796 write_stderr("%s: invalid argument for option -t: \"%s\"\n",
804 SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
813 ParseLongOption(optarg, &name, &value);
818 (errcode(ERRCODE_SYNTAX_ERROR),
819 errmsg("--%s requires a value",
823 (errcode(ERRCODE_SYNTAX_ERROR),
824 errmsg("-c %s requires a value",
828 SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
836 write_stderr("Try \"%s --help\" for more information.\n",
843 * Postmaster accepts no non-option switch arguments.
847 write_stderr("%s: invalid argument: \"%s\"\n",
848 progname, argv[optind]);
849 write_stderr("Try \"%s --help\" for more information.\n",
855 * Locate the proper configuration files and data directory, and read
856 * postgresql.conf for the first time.
858 if (!SelectConfigFiles(userDoption, progname))
861 if (output_config_variable != NULL)
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
868 const char *config_val = GetConfigOption(output_config_variable,
871 puts(config_val ? config_val : "");
875 /* Verify that DataDir looks reasonable */
878 /* And switch working directory into it */
882 * Check for invalid combinations of GUC settings.
884 if (ReservedBackends >= MaxConnections)
886 write_stderr("%s: superuser_reserved_connections must be less than max_connections\n", progname);
889 if (max_wal_senders >= MaxConnections)
891 write_stderr("%s: max_wal_senders must be less than max_connections\n", progname);
894 if (XLogArchiveMode > ARCHIVE_MODE_OFF && wal_level == WAL_LEVEL_MINIMAL)
896 (errmsg("WAL archival cannot be enabled when wal_level is \"minimal\"")));
897 if (max_wal_senders > 0 && wal_level == WAL_LEVEL_MINIMAL)
899 (errmsg("WAL streaming (max_wal_senders > 0) requires wal_level \"replica\" or \"logical\"")));
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.)
905 if (!CheckDateTokenTables())
907 write_stderr("%s: invalid datetoken tables, please fix\n", progname);
912 * Now that we are done processing the postmaster arguments, reset
913 * getopt(3) library so that it will work correctly in subprocesses.
916 #ifdef HAVE_INT_OPTRESET
917 optreset = 1; /* some systems need this too */
920 /* For debugging: display postmaster environment */
922 extern char **environ;
926 (errmsg_internal("%s: PostmasterMain: initial environment dump:",
929 (errmsg_internal("-----------------------------------------")));
930 for (p = environ; *p; ++p)
932 (errmsg_internal("\t%s", *p)));
934 (errmsg_internal("-----------------------------------------")));
938 * Create lockfile for data directory.
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
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.
951 CreateDataDirLockFile(true);
953 /* read control file (error checking and contains config) */
954 LocalProcessControlFile(false);
957 * Initialize SSL library, if specified.
962 (void) secure_initialize(true);
968 * Register the apply launcher. Since it registers a background worker,
969 * it needs to be called before InitializeMaxBackends(), and it's probably
970 * a good idea to call it before any modules had chance to take the
971 * background worker slots.
973 ApplyLauncherRegister();
976 * process any libraries that should be preloaded at postmaster start
978 process_shared_preload_libraries();
981 * Now that loadable modules have had their chance to register background
982 * workers, calculate MaxBackends.
984 InitializeMaxBackends();
987 * Establish input sockets.
989 * First, mark them all closed, and set up an on_proc_exit function that's
990 * charged with closing the sockets again at postmaster shutdown.
992 for (i = 0; i < MAXLISTEN; i++)
993 ListenSocket[i] = PGINVALID_SOCKET;
995 on_proc_exit(CloseServerPorts, 0);
1004 /* Need a modifiable copy of ListenAddresses */
1005 rawstring = pstrdup(ListenAddresses);
1007 /* Parse string into list of hostnames */
1008 if (!SplitIdentifierString(rawstring, ',', &elemlist))
1010 /* syntax error in list */
1012 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1013 errmsg("invalid list syntax in parameter \"%s\"",
1014 "listen_addresses")));
1017 foreach(l, elemlist)
1019 char *curhost = (char *) lfirst(l);
1021 if (strcmp(curhost, "*") == 0)
1022 status = StreamServerPort(AF_UNSPEC, NULL,
1023 (unsigned short) PostPortNumber,
1025 ListenSocket, MAXLISTEN);
1027 status = StreamServerPort(AF_UNSPEC, curhost,
1028 (unsigned short) PostPortNumber,
1030 ListenSocket, MAXLISTEN);
1032 if (status == STATUS_OK)
1035 /* record the first successful host addr in lockfile */
1036 if (!listen_addr_saved)
1038 AddToDataDirLockFile(LOCK_FILE_LINE_LISTEN_ADDR, curhost);
1039 listen_addr_saved = true;
1044 (errmsg("could not create listen socket for \"%s\"",
1048 if (!success && elemlist != NIL)
1050 (errmsg("could not create any TCP/IP sockets")));
1052 list_free(elemlist);
1057 /* Register for Bonjour only if we opened TCP socket(s) */
1058 if (enable_bonjour && ListenSocket[0] != PGINVALID_SOCKET)
1060 DNSServiceErrorType err;
1063 * We pass 0 for interface_index, which will result in registering on
1064 * all "applicable" interfaces. It's not entirely clear from the
1065 * DNS-SD docs whether this would be appropriate if we have bound to
1066 * just a subset of the available network interfaces.
1068 err = DNSServiceRegister(&bonjour_sdref,
1072 "_postgresql._tcp.",
1075 htons(PostPortNumber),
1080 if (err != kDNSServiceErr_NoError)
1081 elog(LOG, "DNSServiceRegister() failed: error code %ld",
1085 * We don't bother to read the mDNS daemon's reply, and we expect that
1086 * it will automatically terminate our registration when the socket is
1087 * closed at postmaster termination. So there's nothing more to be
1088 * done here. However, the bonjour_sdref is kept around so that
1089 * forked children can close their copies of the socket.
1094 #ifdef HAVE_UNIX_SOCKETS
1095 if (Unix_socket_directories)
1102 /* Need a modifiable copy of Unix_socket_directories */
1103 rawstring = pstrdup(Unix_socket_directories);
1105 /* Parse string into list of directories */
1106 if (!SplitDirectoriesString(rawstring, ',', &elemlist))
1108 /* syntax error in list */
1110 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1111 errmsg("invalid list syntax in parameter \"%s\"",
1112 "unix_socket_directories")));
1115 foreach(l, elemlist)
1117 char *socketdir = (char *) lfirst(l);
1119 status = StreamServerPort(AF_UNIX, NULL,
1120 (unsigned short) PostPortNumber,
1122 ListenSocket, MAXLISTEN);
1124 if (status == STATUS_OK)
1127 /* record the first successful Unix socket in lockfile */
1129 AddToDataDirLockFile(LOCK_FILE_LINE_SOCKET_DIR, socketdir);
1133 (errmsg("could not create Unix-domain socket in directory \"%s\"",
1137 if (!success && elemlist != NIL)
1139 (errmsg("could not create any Unix-domain sockets")));
1141 list_free_deep(elemlist);
1147 * check that we have some socket to listen on
1149 if (ListenSocket[0] == PGINVALID_SOCKET)
1151 (errmsg("no socket created for listening")));
1154 * If no valid TCP ports, write an empty line for listen address,
1155 * indicating the Unix socket must be used. Note that this line is not
1156 * added to the lock file until there is a socket backing it.
1158 if (!listen_addr_saved)
1159 AddToDataDirLockFile(LOCK_FILE_LINE_LISTEN_ADDR, "");
1162 * Set up shared memory and semaphores.
1164 reset_shared(PostPortNumber);
1167 * Estimate number of openable files. This must happen after setting up
1168 * semaphores, because on some platforms semaphores count as open files.
1173 * Set reference point for stack-depth checking.
1178 * Initialize pipe (or process handle on Windows) that allows children to
1179 * wake up from sleep on postmaster death.
1181 InitPostmasterDeathWatchHandle();
1186 * Initialize I/O completion port used to deliver list of dead children.
1188 win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
1189 if (win32ChildQueue == NULL)
1191 (errmsg("could not create I/O completion port for child queue")));
1195 * Record postmaster options. We delay this till now to avoid recording
1196 * bogus options (eg, NBuffers too high for available memory).
1198 if (!CreateOptsFile(argc, argv, my_exec_path))
1202 /* Write out nondefault GUC settings for child processes to use */
1203 write_nondefault_variables(PGC_POSTMASTER);
1207 * Write the external PID file if requested
1209 if (external_pid_file)
1211 FILE *fpidfile = fopen(external_pid_file, "w");
1215 fprintf(fpidfile, "%d\n", MyProcPid);
1218 /* Make PID file world readable */
1219 if (chmod(external_pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) != 0)
1220 write_stderr("%s: could not change permissions of external PID file \"%s\": %s\n",
1221 progname, external_pid_file, strerror(errno));
1224 write_stderr("%s: could not write external PID file \"%s\": %s\n",
1225 progname, external_pid_file, strerror(errno));
1227 on_proc_exit(unlink_external_pid_file, 0);
1231 * Remove old temporary files. At this point there can be no other
1232 * Postgres processes running in this directory, so this should be safe.
1234 RemovePgTempFiles();
1237 * Forcibly remove the files signaling a standby promotion request.
1238 * Otherwise, the existence of those files triggers a promotion too early,
1239 * whether a user wants that or not.
1241 * This removal of files is usually unnecessary because they can exist
1242 * only during a few moments during a standby promotion. However there is
1243 * a race condition: if pg_ctl promote is executed and creates the files
1244 * during a promotion, the files can stay around even after the server is
1245 * brought up to new master. Then, if new standby starts by using the
1246 * backup taken from that master, the files can exist at the server
1247 * startup and should be removed in order to avoid an unexpected
1250 * Note that promotion signal files need to be removed before the startup
1251 * process is invoked. Because, after that, they can be used by
1252 * postmaster's SIGUSR1 signal handler.
1254 RemovePromoteSignalFiles();
1256 /* Remove any outdated file holding the current log filenames. */
1257 if (unlink(LOG_METAINFO_DATAFILE) < 0 && errno != ENOENT)
1259 (errcode_for_file_access(),
1260 errmsg("could not remove file \"%s\": %m",
1261 LOG_METAINFO_DATAFILE)));
1264 * If enabled, start up syslogger collection subprocess
1266 SysLoggerPID = SysLogger_Start();
1269 * Reset whereToSendOutput from DestDebug (its starting state) to
1270 * DestNone. This stops ereport from sending log messages to stderr unless
1271 * Log_destination permits. We don't do this until the postmaster is
1272 * fully launched, since startup failures may as well be reported to
1275 * If we are in fact disabling logging to stderr, first emit a log message
1276 * saying so, to provide a breadcrumb trail for users who may not remember
1277 * that their logging is configured to go somewhere else.
1279 if (!(Log_destination & LOG_DESTINATION_STDERR))
1281 (errmsg("ending log output to stderr"),
1282 errhint("Future log output will go to log destination \"%s\".",
1283 Log_destination_string)));
1285 whereToSendOutput = DestNone;
1288 * Initialize stats collection subsystem (this does NOT start the
1289 * collector process!)
1294 * Initialize the autovacuum subsystem (again, no process start yet)
1299 * Load configuration files for client authentication.
1304 * It makes no sense to continue if we fail to load the HBA file,
1305 * since there is no way to connect to the database in this case.
1308 (errmsg("could not load pg_hba.conf")));
1313 * We can start up without the IDENT file, although it means that you
1314 * cannot log in using any of the authentication methods that need a
1315 * user name mapping. load_ident() already logged the details of error
1320 #ifdef HAVE_PTHREAD_IS_THREADED_NP
1323 * On macOS, libintl replaces setlocale() with a version that calls
1324 * CFLocaleCopyCurrent() when its second argument is "" and every relevant
1325 * environment variable is unset or empty. CFLocaleCopyCurrent() makes
1326 * the process multithreaded. The postmaster calls sigprocmask() and
1327 * calls fork() without an immediate exec(), both of which have undefined
1328 * behavior in a multithreaded program. A multithreaded postmaster is the
1329 * normal case on Windows, which offers neither fork() nor sigprocmask().
1331 if (pthread_is_threaded_np() != 0)
1333 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1334 errmsg("postmaster became multithreaded during startup"),
1335 errhint("Set the LC_ALL environment variable to a valid locale.")));
1339 * Remember postmaster startup time
1341 PgStartTime = GetCurrentTimestamp();
1342 #ifndef HAVE_STRONG_RANDOM
1343 /* RandomCancelKey wants its own copy */
1344 gettimeofday(&random_start_time, NULL);
1348 * Report postmaster status in the postmaster.pid file, to allow pg_ctl to
1349 * see what's happening.
1351 AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_STARTING);
1354 * We're ready to rock and roll...
1356 StartupPID = StartupDataBase();
1357 Assert(StartupPID != 0);
1358 StartupStatus = STARTUP_RUNNING;
1359 pmState = PM_STARTUP;
1361 /* Some workers may be scheduled to start now */
1362 maybe_start_bgworkers();
1364 status = ServerLoop();
1367 * ServerLoop probably shouldn't ever return, but if it does, close down.
1369 ExitPostmaster(status != STATUS_OK);
1371 abort(); /* not reached */
1376 * on_proc_exit callback to close server's listen sockets
1379 CloseServerPorts(int status, Datum arg)
1384 * First, explicitly close all the socket FDs. We used to just let this
1385 * happen implicitly at postmaster exit, but it's better to close them
1386 * before we remove the postmaster.pid lockfile; otherwise there's a race
1387 * condition if a new postmaster wants to re-use the TCP port number.
1389 for (i = 0; i < MAXLISTEN; i++)
1391 if (ListenSocket[i] != PGINVALID_SOCKET)
1393 StreamClose(ListenSocket[i]);
1394 ListenSocket[i] = PGINVALID_SOCKET;
1399 * Next, remove any filesystem entries for Unix sockets. To avoid race
1400 * conditions against incoming postmasters, this must happen after closing
1401 * the sockets and before removing lock files.
1403 RemoveSocketFiles();
1406 * We don't do anything about socket lock files here; those will be
1407 * removed in a later on_proc_exit callback.
1412 * on_proc_exit callback to delete external_pid_file
1415 unlink_external_pid_file(int status, Datum arg)
1417 if (external_pid_file)
1418 unlink(external_pid_file);
1423 * Compute and check the directory paths to files that are part of the
1424 * installation (as deduced from the postgres executable's own location)
1427 getInstallationPaths(const char *argv0)
1431 /* Locate the postgres executable itself */
1432 if (find_my_exec(argv0, my_exec_path) < 0)
1433 elog(FATAL, "%s: could not locate my own executable path", argv0);
1436 /* Locate executable backend before we change working directory */
1437 if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1438 postgres_exec_path) < 0)
1440 (errmsg("%s: could not locate matching postgres executable",
1445 * Locate the pkglib directory --- this has to be set early in case we try
1446 * to load any modules from it in response to postgresql.conf entries.
1448 get_pkglib_path(my_exec_path, pkglib_path);
1451 * Verify that there's a readable directory there; otherwise the Postgres
1452 * installation is incomplete or corrupt. (A typical cause of this
1453 * failure is that the postgres executable has been moved or hardlinked to
1454 * some directory that's not a sibling of the installation lib/
1457 pdir = AllocateDir(pkglib_path);
1460 (errcode_for_file_access(),
1461 errmsg("could not open directory \"%s\": %m",
1463 errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1468 * XXX is it worth similarly checking the share/ directory? If the lib/
1469 * directory is there, then share/ probably is too.
1475 * Validate the proposed data directory
1480 char path[MAXPGPATH];
1482 struct stat stat_buf;
1486 if (stat(DataDir, &stat_buf) != 0)
1488 if (errno == ENOENT)
1490 (errcode_for_file_access(),
1491 errmsg("data directory \"%s\" does not exist",
1495 (errcode_for_file_access(),
1496 errmsg("could not read permissions of directory \"%s\": %m",
1500 /* eventual chdir would fail anyway, but let's test ... */
1501 if (!S_ISDIR(stat_buf.st_mode))
1503 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1504 errmsg("specified data directory \"%s\" is not a directory",
1508 * Check that the directory belongs to my userid; if not, reject.
1510 * This check is an essential part of the interlock that prevents two
1511 * postmasters from starting in the same directory (see CreateLockFile()).
1512 * Do not remove or weaken it.
1514 * XXX can we safely enable this check on Windows?
1516 #if !defined(WIN32) && !defined(__CYGWIN__)
1517 if (stat_buf.st_uid != geteuid())
1519 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1520 errmsg("data directory \"%s\" has wrong ownership",
1522 errhint("The server must be started by the user that owns the data directory.")));
1526 * Check if the directory has group or world access. If so, reject.
1528 * It would be possible to allow weaker constraints (for example, allow
1529 * group access) but we cannot make a general assumption that that is
1530 * okay; for example there are platforms where nearly all users
1531 * customarily belong to the same group. Perhaps this test should be
1534 * XXX temporarily suppress check when on Windows, because there may not
1535 * be proper support for Unix-y file permissions. Need to think of a
1536 * reasonable check to apply on Windows.
1538 #if !defined(WIN32) && !defined(__CYGWIN__)
1539 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
1541 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1542 errmsg("data directory \"%s\" has group or world access",
1544 errdetail("Permissions should be u=rwx (0700).")));
1547 /* Look for PG_VERSION before looking for pg_control */
1548 ValidatePgVersion(DataDir);
1550 snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1552 fp = AllocateFile(path, PG_BINARY_R);
1555 write_stderr("%s: could not find the database system\n"
1556 "Expected to find it in the directory \"%s\",\n"
1557 "but could not open file \"%s\": %s\n",
1558 progname, DataDir, path, strerror(errno));
1565 * Determine how long should we let ServerLoop sleep.
1567 * In normal conditions we wait at most one minute, to ensure that the other
1568 * background tasks handled by ServerLoop get done even when no requests are
1569 * arriving. However, if there are background workers waiting to be started,
1570 * we don't actually sleep so that they are quickly serviced. Other exception
1571 * cases are as shown in the code.
1574 DetermineSleepTime(struct timeval *timeout)
1576 TimestampTz next_wakeup = 0;
1579 * Normal case: either there are no background workers at all, or we're in
1580 * a shutdown sequence (during which we ignore bgworkers altogether).
1582 if (Shutdown > NoShutdown ||
1583 (!StartWorkerNeeded && !HaveCrashedWorker))
1585 if (AbortStartTime != 0)
1587 /* time left to abort; clamp to 0 in case it already expired */
1588 timeout->tv_sec = SIGKILL_CHILDREN_AFTER_SECS -
1589 (time(NULL) - AbortStartTime);
1590 timeout->tv_sec = Max(timeout->tv_sec, 0);
1591 timeout->tv_usec = 0;
1595 timeout->tv_sec = 60;
1596 timeout->tv_usec = 0;
1601 if (StartWorkerNeeded)
1603 timeout->tv_sec = 0;
1604 timeout->tv_usec = 0;
1608 if (HaveCrashedWorker)
1610 slist_mutable_iter siter;
1613 * When there are crashed bgworkers, we sleep just long enough that
1614 * they are restarted when they request to be. Scan the list to
1615 * determine the minimum of all wakeup times according to most recent
1616 * crash time and requested restart interval.
1618 slist_foreach_modify(siter, &BackgroundWorkerList)
1620 RegisteredBgWorker *rw;
1621 TimestampTz this_wakeup;
1623 rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
1625 if (rw->rw_crashed_at == 0)
1628 if (rw->rw_worker.bgw_restart_time == BGW_NEVER_RESTART
1629 || rw->rw_terminate)
1631 ForgetBackgroundWorker(&siter);
1635 this_wakeup = TimestampTzPlusMilliseconds(rw->rw_crashed_at,
1636 1000L * rw->rw_worker.bgw_restart_time);
1637 if (next_wakeup == 0 || this_wakeup < next_wakeup)
1638 next_wakeup = this_wakeup;
1642 if (next_wakeup != 0)
1647 TimestampDifference(GetCurrentTimestamp(), next_wakeup,
1649 timeout->tv_sec = secs;
1650 timeout->tv_usec = microsecs;
1652 /* Ensure we don't exceed one minute */
1653 if (timeout->tv_sec > 60)
1655 timeout->tv_sec = 60;
1656 timeout->tv_usec = 0;
1661 timeout->tv_sec = 60;
1662 timeout->tv_usec = 0;
1667 * Main idle loop of postmaster
1669 * NB: Needs to be called with signals blocked
1676 time_t last_lockfile_recheck_time,
1679 last_lockfile_recheck_time = last_touch_time = time(NULL);
1681 nSockets = initMasks(&readmask);
1690 * Wait for a connection request to arrive.
1692 * We block all signals except while sleeping. That makes it safe for
1693 * signal handlers, which again block all signals while executing, to
1694 * do nontrivial work.
1696 * If we are in PM_WAIT_DEAD_END state, then we don't want to accept
1697 * any new connections, so we don't call select(), and just sleep.
1699 memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
1701 if (pmState == PM_WAIT_DEAD_END)
1703 PG_SETMASK(&UnBlockSig);
1705 pg_usleep(100000L); /* 100 msec seems reasonable */
1708 PG_SETMASK(&BlockSig);
1712 /* must set timeout each time; some OSes change it! */
1713 struct timeval timeout;
1715 /* Needs to run with blocked signals! */
1716 DetermineSleepTime(&timeout);
1718 PG_SETMASK(&UnBlockSig);
1720 selres = select(nSockets, &rmask, NULL, NULL, &timeout);
1722 PG_SETMASK(&BlockSig);
1725 /* Now check the select() result */
1728 if (errno != EINTR && errno != EWOULDBLOCK)
1731 (errcode_for_socket_access(),
1732 errmsg("select() failed in postmaster: %m")));
1733 return STATUS_ERROR;
1738 * New connection pending on any of our sockets? If so, fork a child
1739 * process to deal with it.
1745 for (i = 0; i < MAXLISTEN; i++)
1747 if (ListenSocket[i] == PGINVALID_SOCKET)
1749 if (FD_ISSET(ListenSocket[i], &rmask))
1753 port = ConnCreate(ListenSocket[i]);
1756 BackendStartup(port);
1759 * We no longer need the open socket or port structure
1762 StreamClose(port->sock);
1769 /* If we have lost the log collector, try to start a new one */
1770 if (SysLoggerPID == 0 && Logging_collector)
1771 SysLoggerPID = SysLogger_Start();
1774 * If no background writer process is running, and we are not in a
1775 * state that prevents it, start one. It doesn't matter if this
1776 * fails, we'll just try again later. Likewise for the checkpointer.
1778 if (pmState == PM_RUN || pmState == PM_RECOVERY ||
1779 pmState == PM_HOT_STANDBY)
1781 if (CheckpointerPID == 0)
1782 CheckpointerPID = StartCheckpointer();
1783 if (BgWriterPID == 0)
1784 BgWriterPID = StartBackgroundWriter();
1788 * Likewise, if we have lost the walwriter process, try to start a new
1789 * one. But this is needed only in normal operation (else we cannot
1790 * be writing any new WAL).
1792 if (WalWriterPID == 0 && pmState == PM_RUN)
1793 WalWriterPID = StartWalWriter();
1796 * If we have lost the autovacuum launcher, try to start a new one. We
1797 * don't want autovacuum to run in binary upgrade mode because
1798 * autovacuum might update relfrozenxid for empty tables before the
1799 * physical files are put in place.
1801 if (!IsBinaryUpgrade && AutoVacPID == 0 &&
1802 (AutoVacuumingActive() || start_autovac_launcher) &&
1805 AutoVacPID = StartAutoVacLauncher();
1806 if (AutoVacPID != 0)
1807 start_autovac_launcher = false; /* signal processed */
1810 /* If we have lost the stats collector, try to start a new one */
1811 if (PgStatPID == 0 &&
1812 (pmState == PM_RUN || pmState == PM_HOT_STANDBY))
1813 PgStatPID = pgstat_start();
1815 /* If we have lost the archiver, try to start a new one. */
1816 if (PgArchPID == 0 && PgArchStartupAllowed())
1817 PgArchPID = pgarch_start();
1819 /* If we need to signal the autovacuum launcher, do so now */
1820 if (avlauncher_needs_signal)
1822 avlauncher_needs_signal = false;
1823 if (AutoVacPID != 0)
1824 kill(AutoVacPID, SIGUSR2);
1827 /* If we need to start a WAL receiver, try to do that now */
1828 if (WalReceiverRequested)
1829 MaybeStartWalReceiver();
1831 /* Get other worker processes running, if needed */
1832 if (StartWorkerNeeded || HaveCrashedWorker)
1833 maybe_start_bgworkers();
1835 #ifdef HAVE_PTHREAD_IS_THREADED_NP
1838 * With assertions enabled, check regularly for appearance of
1839 * additional threads. All builds check at start and exit.
1841 Assert(pthread_is_threaded_np() == 0);
1845 * Lastly, check to see if it's time to do some things that we don't
1846 * want to do every single time through the loop, because they're a
1847 * bit expensive. Note that there's up to a minute of slop in when
1848 * these tasks will be performed, since DetermineSleepTime() will let
1849 * us sleep at most that long; except for SIGKILL timeout which has
1850 * special-case logic there.
1855 * If we already sent SIGQUIT to children and they are slow to shut
1856 * down, it's time to send them SIGKILL. This doesn't happen
1857 * normally, but under certain conditions backends can get stuck while
1858 * shutting down. This is a last measure to get them unwedged.
1860 * Note we also do this during recovery from a process crash.
1862 if ((Shutdown >= ImmediateShutdown || (FatalError && !SendStop)) &&
1863 AbortStartTime != 0 &&
1864 (now - AbortStartTime) >= SIGKILL_CHILDREN_AFTER_SECS)
1866 /* We were gentle with them before. Not anymore */
1867 TerminateChildren(SIGKILL);
1868 /* reset flag so we don't SIGKILL again */
1873 * Once a minute, verify that postmaster.pid hasn't been removed or
1874 * overwritten. If it has, we force a shutdown. This avoids having
1875 * postmasters and child processes hanging around after their database
1876 * is gone, and maybe causing problems if a new database cluster is
1877 * created in the same place. It also provides some protection
1878 * against a DBA foolishly removing postmaster.pid and manually
1879 * starting a new postmaster. Data corruption is likely to ensue from
1880 * that anyway, but we can minimize the damage by aborting ASAP.
1882 if (now - last_lockfile_recheck_time >= 1 * SECS_PER_MINUTE)
1884 if (!RecheckDataDirLockFile())
1887 (errmsg("performing immediate shutdown because data directory lock file is invalid")));
1888 kill(MyProcPid, SIGQUIT);
1890 last_lockfile_recheck_time = now;
1894 * Touch Unix socket and lock files every 58 minutes, to ensure that
1895 * they are not removed by overzealous /tmp-cleaning tasks. We assume
1896 * no one runs cleaners with cutoff times of less than an hour ...
1898 if (now - last_touch_time >= 58 * SECS_PER_MINUTE)
1901 TouchSocketLockFiles();
1902 last_touch_time = now;
1908 * Initialise the masks for select() for the ports we are listening on.
1909 * Return the number of sockets to listen on.
1912 initMasks(fd_set *rmask)
1919 for (i = 0; i < MAXLISTEN; i++)
1921 int fd = ListenSocket[i];
1923 if (fd == PGINVALID_SOCKET)
1936 * Read a client's startup packet and do something according to it.
1938 * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
1939 * not return at all.
1941 * (Note that ereport(FATAL) stuff is sent to the client, so only use it
1942 * if that's what you want. Return STATUS_ERROR if you don't want to
1943 * send anything to the client, which would typically be appropriate
1944 * if we detect a communications failure.)
1947 ProcessStartupPacket(Port *port, bool SSLdone)
1951 ProtocolVersion proto;
1952 MemoryContext oldcontext;
1955 if (pq_getbytes((char *) &len, 4) == EOF)
1958 * EOF after SSLdone probably means the client didn't like our
1959 * response to NEGOTIATE_SSL_CODE. That's not an error condition, so
1960 * don't clutter the log with a complaint.
1964 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1965 errmsg("incomplete startup packet")));
1966 return STATUS_ERROR;
1972 if (len < (int32) sizeof(ProtocolVersion) ||
1973 len > MAX_STARTUP_PACKET_LENGTH)
1976 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1977 errmsg("invalid length of startup packet")));
1978 return STATUS_ERROR;
1982 * Allocate at least the size of an old-style startup packet, plus one
1983 * extra byte, and make sure all are zeroes. This ensures we will have
1984 * null termination of all strings, in both fixed- and variable-length
1987 if (len <= (int32) sizeof(StartupPacket))
1988 buf = palloc0(sizeof(StartupPacket) + 1);
1990 buf = palloc0(len + 1);
1992 if (pq_getbytes(buf, len) == EOF)
1995 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1996 errmsg("incomplete startup packet")));
1997 return STATUS_ERROR;
2002 * The first field is either a protocol version number or a special
2005 port->proto = proto = ntohl(*((ProtocolVersion *) buf));
2007 if (proto == CANCEL_REQUEST_CODE)
2009 processCancelRequest(port, buf);
2010 /* Not really an error, but we don't want to proceed further */
2011 return STATUS_ERROR;
2014 if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
2019 /* No SSL when disabled or on Unix sockets */
2020 if (!LoadedSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
2023 SSLok = 'S'; /* Support for SSL */
2025 SSLok = 'N'; /* No support for SSL */
2029 if (send(port->sock, &SSLok, 1, 0) != 1)
2032 goto retry1; /* if interrupted, just retry */
2034 (errcode_for_socket_access(),
2035 errmsg("failed to send SSL negotiation response: %m")));
2036 return STATUS_ERROR; /* close the connection */
2040 if (SSLok == 'S' && secure_open_server(port) == -1)
2041 return STATUS_ERROR;
2043 /* regular startup packet, cancel, etc packet should follow... */
2044 /* but not another SSL negotiation request */
2045 return ProcessStartupPacket(port, true);
2048 /* Could add additional special packet types here */
2051 * Set FrontendProtocol now so that ereport() knows what format to send if
2052 * we fail during startup.
2054 FrontendProtocol = proto;
2056 /* Check we can handle the protocol the frontend is using. */
2058 if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
2059 PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
2060 (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
2061 PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
2063 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2064 errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
2065 PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
2066 PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST),
2067 PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST),
2068 PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))));
2071 * Now fetch parameters out of startup packet and save them into the Port
2072 * structure. All data structures attached to the Port struct must be
2073 * allocated in TopMemoryContext so that they will remain available in a
2074 * running backend (even after PostmasterContext is destroyed). We need
2075 * not worry about leaking this storage on failure, since we aren't in the
2076 * postmaster process anymore.
2078 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2080 if (PG_PROTOCOL_MAJOR(proto) >= 3)
2082 int32 offset = sizeof(ProtocolVersion);
2085 * Scan packet body for name/option pairs. We can assume any string
2086 * beginning within the packet body is null-terminated, thanks to
2087 * zeroing extra byte above.
2089 port->guc_options = NIL;
2091 while (offset < len)
2093 char *nameptr = ((char *) buf) + offset;
2097 if (*nameptr == '\0')
2098 break; /* found packet terminator */
2099 valoffset = offset + strlen(nameptr) + 1;
2100 if (valoffset >= len)
2101 break; /* missing value, will complain below */
2102 valptr = ((char *) buf) + valoffset;
2104 if (strcmp(nameptr, "database") == 0)
2105 port->database_name = pstrdup(valptr);
2106 else if (strcmp(nameptr, "user") == 0)
2107 port->user_name = pstrdup(valptr);
2108 else if (strcmp(nameptr, "options") == 0)
2109 port->cmdline_options = pstrdup(valptr);
2110 else if (strcmp(nameptr, "replication") == 0)
2113 * Due to backward compatibility concerns the replication
2114 * parameter is a hybrid beast which allows the value to be
2115 * either boolean or the string 'database'. The latter
2116 * connects to a specific database which is e.g. required for
2117 * logical decoding while.
2119 if (strcmp(valptr, "database") == 0)
2121 am_walsender = true;
2122 am_db_walsender = true;
2124 else if (!parse_bool(valptr, &am_walsender))
2126 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2127 errmsg("invalid value for parameter \"%s\": \"%s\"",
2130 errhint("Valid values are: \"false\", 0, \"true\", 1, \"database\".")));
2134 /* Assume it's a generic GUC option */
2135 port->guc_options = lappend(port->guc_options,
2137 port->guc_options = lappend(port->guc_options,
2140 offset = valoffset + strlen(valptr) + 1;
2144 * If we didn't find a packet terminator exactly at the end of the
2145 * given packet length, complain.
2147 if (offset != len - 1)
2149 (errcode(ERRCODE_PROTOCOL_VIOLATION),
2150 errmsg("invalid startup packet layout: expected terminator as last byte")));
2155 * Get the parameters from the old-style, fixed-width-fields startup
2156 * packet as C strings. The packet destination was cleared first so a
2157 * short packet has zeros silently added. We have to be prepared to
2158 * truncate the pstrdup result for oversize fields, though.
2160 StartupPacket *packet = (StartupPacket *) buf;
2162 port->database_name = pstrdup(packet->database);
2163 if (strlen(port->database_name) > sizeof(packet->database))
2164 port->database_name[sizeof(packet->database)] = '\0';
2165 port->user_name = pstrdup(packet->user);
2166 if (strlen(port->user_name) > sizeof(packet->user))
2167 port->user_name[sizeof(packet->user)] = '\0';
2168 port->cmdline_options = pstrdup(packet->options);
2169 if (strlen(port->cmdline_options) > sizeof(packet->options))
2170 port->cmdline_options[sizeof(packet->options)] = '\0';
2171 port->guc_options = NIL;
2174 /* Check a user name was given. */
2175 if (port->user_name == NULL || port->user_name[0] == '\0')
2177 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
2178 errmsg("no PostgreSQL user name specified in startup packet")));
2180 /* The database defaults to the user name. */
2181 if (port->database_name == NULL || port->database_name[0] == '\0')
2182 port->database_name = pstrdup(port->user_name);
2184 if (Db_user_namespace)
2187 * If user@, it is a global user, remove '@'. We only want to do this
2188 * if there is an '@' at the end and no earlier in the user string or
2189 * they may fake as a local user of another database attaching to this
2192 if (strchr(port->user_name, '@') ==
2193 port->user_name + strlen(port->user_name) - 1)
2194 *strchr(port->user_name, '@') = '\0';
2197 /* Append '@' and dbname */
2198 port->user_name = psprintf("%s@%s", port->user_name, port->database_name);
2203 * Truncate given database and user names to length of a Postgres name.
2204 * This avoids lookup failures when overlength names are given.
2206 if (strlen(port->database_name) >= NAMEDATALEN)
2207 port->database_name[NAMEDATALEN - 1] = '\0';
2208 if (strlen(port->user_name) >= NAMEDATALEN)
2209 port->user_name[NAMEDATALEN - 1] = '\0';
2212 * Normal walsender backends, e.g. for streaming replication, are not
2213 * connected to a particular database. But walsenders used for logical
2214 * replication need to connect to a specific database. We allow streaming
2215 * replication commands to be issued even if connected to a database as it
2216 * can make sense to first make a basebackup and then stream changes
2217 * starting from that.
2219 if (am_walsender && !am_db_walsender)
2220 port->database_name[0] = '\0';
2223 * Done putting stuff in TopMemoryContext.
2225 MemoryContextSwitchTo(oldcontext);
2228 * If we're going to reject the connection due to database state, say so
2229 * now instead of wasting cycles on an authentication exchange. (This also
2230 * allows a pg_ping utility to be written.)
2232 switch (port->canAcceptConnections)
2236 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
2237 errmsg("the database system is starting up")));
2241 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
2242 errmsg("the database system is shutting down")));
2246 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
2247 errmsg("the database system is in recovery mode")));
2251 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
2252 errmsg("sorry, too many clients already")));
2254 case CAC_WAITBACKUP:
2255 /* OK for now, will check in InitPostgres */
2266 * The client has sent a cancel request packet, not a normal
2267 * start-a-new-connection packet. Perform the necessary processing.
2268 * Nothing is sent back to the client.
2271 processCancelRequest(Port *port, void *pkt)
2273 CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
2275 int32 cancelAuthCode;
2278 #ifndef EXEC_BACKEND
2284 backendPID = (int) ntohl(canc->backendPID);
2285 cancelAuthCode = (int32) ntohl(canc->cancelAuthCode);
2288 * See if we have a matching backend. In the EXEC_BACKEND case, we can no
2289 * longer access the postmaster's own backend list, and must rely on the
2290 * duplicate array in shared memory.
2292 #ifndef EXEC_BACKEND
2293 dlist_foreach(iter, &BackendList)
2295 bp = dlist_container(Backend, elem, iter.cur);
2297 for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
2299 bp = (Backend *) &ShmemBackendArray[i];
2301 if (bp->pid == backendPID)
2303 if (bp->cancel_key == cancelAuthCode)
2305 /* Found a match; signal that backend to cancel current op */
2307 (errmsg_internal("processing cancel request: sending SIGINT to process %d",
2309 signal_child(bp->pid, SIGINT);
2312 /* Right PID, wrong key: no way, Jose */
2314 (errmsg("wrong key in cancel request for process %d",
2320 /* No matching backend */
2322 (errmsg("PID %d in cancel request did not match any process",
2327 * canAcceptConnections --- check to see if database state allows connections.
2330 canAcceptConnections(void)
2332 CAC_state result = CAC_OK;
2335 * Can't start backends when in startup/shutdown/inconsistent recovery
2338 * In state PM_WAIT_BACKUP only superusers can connect (this must be
2339 * allowed so that a superuser can end online backup mode); we return
2340 * CAC_WAITBACKUP code to indicate that this must be checked later. Note
2341 * that neither CAC_OK nor CAC_WAITBACKUP can safely be returned until we
2342 * have checked for too many children.
2344 if (pmState != PM_RUN)
2346 if (pmState == PM_WAIT_BACKUP)
2347 result = CAC_WAITBACKUP; /* allow superusers only */
2348 else if (Shutdown > NoShutdown)
2349 return CAC_SHUTDOWN; /* shutdown is pending */
2350 else if (!FatalError &&
2351 (pmState == PM_STARTUP ||
2352 pmState == PM_RECOVERY))
2353 return CAC_STARTUP; /* normal startup */
2354 else if (!FatalError &&
2355 pmState == PM_HOT_STANDBY)
2356 result = CAC_OK; /* connection OK during hot standby */
2358 return CAC_RECOVERY; /* else must be crash recovery */
2362 * Don't start too many children.
2364 * We allow more connections than we can have backends here because some
2365 * might still be authenticating; they might fail auth, or some existing
2366 * backend might exit before the auth cycle is completed. The exact
2367 * MaxBackends limit is enforced when a new backend tries to join the
2368 * shared-inval backend array.
2370 * The limit here must match the sizes of the per-child-process arrays;
2371 * see comments for MaxLivePostmasterChildren().
2373 if (CountChildren(BACKEND_TYPE_ALL) >= MaxLivePostmasterChildren())
2374 result = CAC_TOOMANY;
2381 * ConnCreate -- create a local connection data structure
2383 * Returns NULL on failure, other than out-of-memory which is fatal.
2386 ConnCreate(int serverFd)
2390 if (!(port = (Port *) calloc(1, sizeof(Port))))
2393 (errcode(ERRCODE_OUT_OF_MEMORY),
2394 errmsg("out of memory")));
2398 if (StreamConnection(serverFd, port) != STATUS_OK)
2400 if (port->sock != PGINVALID_SOCKET)
2401 StreamClose(port->sock);
2407 * Allocate GSSAPI specific state struct
2409 #ifndef EXEC_BACKEND
2410 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2411 port->gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
2415 (errcode(ERRCODE_OUT_OF_MEMORY),
2416 errmsg("out of memory")));
2427 * ConnFree -- free a local connection data structure
2430 ConnFree(Port *conn)
2442 * ClosePostmasterPorts -- close all the postmaster's open sockets
2444 * This is called during child process startup to release file descriptors
2445 * that are not needed by that child process. The postmaster still has
2446 * them open, of course.
2448 * Note: we pass am_syslogger as a boolean because we don't want to set
2449 * the global variable yet when this is called.
2452 ClosePostmasterPorts(bool am_syslogger)
2459 * Close the write end of postmaster death watch pipe. It's important to
2460 * do this as early as possible, so that if postmaster dies, others won't
2461 * think that it's still running because we're holding the pipe open.
2463 if (close(postmaster_alive_fds[POSTMASTER_FD_OWN]))
2465 (errcode_for_file_access(),
2466 errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
2467 postmaster_alive_fds[POSTMASTER_FD_OWN] = -1;
2470 /* Close the listen sockets */
2471 for (i = 0; i < MAXLISTEN; i++)
2473 if (ListenSocket[i] != PGINVALID_SOCKET)
2475 StreamClose(ListenSocket[i]);
2476 ListenSocket[i] = PGINVALID_SOCKET;
2480 /* If using syslogger, close the read side of the pipe */
2484 if (syslogPipe[0] >= 0)
2485 close(syslogPipe[0]);
2489 CloseHandle(syslogPipe[0]);
2495 /* If using Bonjour, close the connection to the mDNS daemon */
2497 close(DNSServiceRefSockFD(bonjour_sdref));
2503 * reset_shared -- reset shared memory and semaphores
2506 reset_shared(int port)
2509 * Create or re-create shared memory and semaphores.
2511 * Note: in each "cycle of life" we will normally assign the same IPC keys
2512 * (if using SysV shmem and/or semas), since the port number is used to
2513 * determine IPC keys. This helps ensure that we will clean up dead IPC
2514 * objects if the postmaster crashes and is restarted.
2516 CreateSharedMemoryAndSemaphores(false, port);
2521 * SIGHUP -- reread config files, and tell children to do same
2524 SIGHUP_handler(SIGNAL_ARGS)
2526 int save_errno = errno;
2528 PG_SETMASK(&BlockSig);
2530 if (Shutdown <= SmartShutdown)
2533 (errmsg("received SIGHUP, reloading configuration files")));
2534 ProcessConfigFile(PGC_SIGHUP);
2535 SignalChildren(SIGHUP);
2536 if (StartupPID != 0)
2537 signal_child(StartupPID, SIGHUP);
2538 if (BgWriterPID != 0)
2539 signal_child(BgWriterPID, SIGHUP);
2540 if (CheckpointerPID != 0)
2541 signal_child(CheckpointerPID, SIGHUP);
2542 if (WalWriterPID != 0)
2543 signal_child(WalWriterPID, SIGHUP);
2544 if (WalReceiverPID != 0)
2545 signal_child(WalReceiverPID, SIGHUP);
2546 if (AutoVacPID != 0)
2547 signal_child(AutoVacPID, SIGHUP);
2549 signal_child(PgArchPID, SIGHUP);
2550 if (SysLoggerPID != 0)
2551 signal_child(SysLoggerPID, SIGHUP);
2553 signal_child(PgStatPID, SIGHUP);
2555 /* Reload authentication config files too */
2558 (errmsg("pg_hba.conf was not reloaded")));
2562 (errmsg("pg_ident.conf was not reloaded")));
2565 /* Reload SSL configuration as well */
2568 if (secure_initialize(false) == 0)
2572 (errmsg("SSL configuration was not reloaded")));
2582 /* Update the starting-point file for future children */
2583 write_nondefault_variables(PGC_SIGHUP);
2587 PG_SETMASK(&UnBlockSig);
2594 * pmdie -- signal handler for processing various postmaster signals.
2599 int save_errno = errno;
2601 PG_SETMASK(&BlockSig);
2604 (errmsg_internal("postmaster received signal %d",
2605 postgres_signal_arg)));
2607 switch (postgres_signal_arg)
2614 * Wait for children to end their work, then shut down.
2616 if (Shutdown >= SmartShutdown)
2618 Shutdown = SmartShutdown;
2620 (errmsg("received smart shutdown request")));
2623 AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_STOPPING);
2625 sd_notify(0, "STOPPING=1");
2628 if (pmState == PM_RUN || pmState == PM_RECOVERY ||
2629 pmState == PM_HOT_STANDBY || pmState == PM_STARTUP)
2631 /* autovac workers are told to shut down immediately */
2632 /* and bgworkers too; does this need tweaking? */
2633 SignalSomeChildren(SIGTERM,
2634 BACKEND_TYPE_AUTOVAC | BACKEND_TYPE_BGWORKER);
2635 /* and the autovac launcher too */
2636 if (AutoVacPID != 0)
2637 signal_child(AutoVacPID, SIGTERM);
2638 /* and the bgwriter too */
2639 if (BgWriterPID != 0)
2640 signal_child(BgWriterPID, SIGTERM);
2641 /* and the walwriter too */
2642 if (WalWriterPID != 0)
2643 signal_child(WalWriterPID, SIGTERM);
2646 * If we're in recovery, we can't kill the startup process
2647 * right away, because at present doing so does not release
2648 * its locks. We might want to change this in a future
2649 * release. For the time being, the PM_WAIT_READONLY state
2650 * indicates that we're waiting for the regular (read only)
2651 * backends to die off; once they do, we'll kill the startup
2652 * and walreceiver processes.
2654 pmState = (pmState == PM_RUN) ?
2655 PM_WAIT_BACKUP : PM_WAIT_READONLY;
2659 * Now wait for online backup mode to end and backends to exit. If
2660 * that is already the case, PostmasterStateMachine will take the
2663 PostmasterStateMachine();
2671 * Abort all children with SIGTERM (rollback active transactions
2672 * and exit) and shut down when they are gone.
2674 if (Shutdown >= FastShutdown)
2676 Shutdown = FastShutdown;
2678 (errmsg("received fast shutdown request")));
2681 AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_STOPPING);
2683 sd_notify(0, "STOPPING=1");
2686 if (StartupPID != 0)
2687 signal_child(StartupPID, SIGTERM);
2688 if (BgWriterPID != 0)
2689 signal_child(BgWriterPID, SIGTERM);
2690 if (WalReceiverPID != 0)
2691 signal_child(WalReceiverPID, SIGTERM);
2692 if (pmState == PM_RECOVERY)
2694 SignalSomeChildren(SIGTERM, BACKEND_TYPE_BGWORKER);
2697 * Only startup, bgwriter, walreceiver, possibly bgworkers,
2698 * and/or checkpointer should be active in this state; we just
2699 * signaled the first four, and we don't want to kill
2702 pmState = PM_WAIT_BACKENDS;
2704 else if (pmState == PM_RUN ||
2705 pmState == PM_WAIT_BACKUP ||
2706 pmState == PM_WAIT_READONLY ||
2707 pmState == PM_WAIT_BACKENDS ||
2708 pmState == PM_HOT_STANDBY)
2711 (errmsg("aborting any active transactions")));
2712 /* shut down all backends and workers */
2713 SignalSomeChildren(SIGTERM,
2714 BACKEND_TYPE_NORMAL | BACKEND_TYPE_AUTOVAC |
2715 BACKEND_TYPE_BGWORKER);
2716 /* and the autovac launcher too */
2717 if (AutoVacPID != 0)
2718 signal_child(AutoVacPID, SIGTERM);
2719 /* and the walwriter too */
2720 if (WalWriterPID != 0)
2721 signal_child(WalWriterPID, SIGTERM);
2722 pmState = PM_WAIT_BACKENDS;
2726 * Now wait for backends to exit. If there are none,
2727 * PostmasterStateMachine will take the next step.
2729 PostmasterStateMachine();
2735 * Immediate Shutdown:
2737 * abort all children with SIGQUIT, wait for them to exit,
2738 * terminate remaining ones with SIGKILL, then exit without
2739 * attempt to properly shut down the data base system.
2741 if (Shutdown >= ImmediateShutdown)
2743 Shutdown = ImmediateShutdown;
2745 (errmsg("received immediate shutdown request")));
2748 AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_STOPPING);
2750 sd_notify(0, "STOPPING=1");
2753 TerminateChildren(SIGQUIT);
2754 pmState = PM_WAIT_BACKENDS;
2756 /* set stopwatch for them to die */
2757 AbortStartTime = time(NULL);
2760 * Now wait for backends to exit. If there are none,
2761 * PostmasterStateMachine will take the next step.
2763 PostmasterStateMachine();
2767 PG_SETMASK(&UnBlockSig);
2773 * Reaper -- signal handler to cleanup after a child process dies.
2778 int save_errno = errno;
2779 int pid; /* process id of dead child process */
2780 int exitstatus; /* its exit status */
2782 PG_SETMASK(&BlockSig);
2785 (errmsg_internal("reaping dead processes")));
2787 while ((pid = waitpid(-1, &exitstatus, WNOHANG)) > 0)
2790 * Check if this child was a startup process.
2792 if (pid == StartupPID)
2797 * Startup process exited in response to a shutdown request (or it
2798 * completed normally regardless of the shutdown request).
2800 if (Shutdown > NoShutdown &&
2801 (EXIT_STATUS_0(exitstatus) || EXIT_STATUS_1(exitstatus)))
2803 StartupStatus = STARTUP_NOT_RUNNING;
2804 pmState = PM_WAIT_BACKENDS;
2805 /* PostmasterStateMachine logic does the rest */
2809 if (EXIT_STATUS_3(exitstatus))
2812 (errmsg("shutdown at recovery target")));
2813 StartupStatus = STARTUP_NOT_RUNNING;
2814 Shutdown = SmartShutdown;
2815 TerminateChildren(SIGTERM);
2816 pmState = PM_WAIT_BACKENDS;
2817 /* PostmasterStateMachine logic does the rest */
2822 * Unexpected exit of startup process (including FATAL exit)
2823 * during PM_STARTUP is treated as catastrophic. There are no
2824 * other processes running yet, so we can just exit.
2826 if (pmState == PM_STARTUP && !EXIT_STATUS_0(exitstatus))
2828 LogChildExit(LOG, _("startup process"),
2831 (errmsg("aborting startup due to startup process failure")));
2836 * After PM_STARTUP, any unexpected exit (including FATAL exit) of
2837 * the startup process is catastrophic, so kill other children,
2838 * and set StartupStatus so we don't try to reinitialize after
2839 * they're gone. Exception: if StartupStatus is STARTUP_SIGNALED,
2840 * then we previously sent the startup process a SIGQUIT; so
2841 * that's probably the reason it died, and we do want to try to
2842 * restart in that case.
2844 if (!EXIT_STATUS_0(exitstatus))
2846 if (StartupStatus == STARTUP_SIGNALED)
2847 StartupStatus = STARTUP_NOT_RUNNING;
2849 StartupStatus = STARTUP_CRASHED;
2850 HandleChildCrash(pid, exitstatus,
2851 _("startup process"));
2856 * Startup succeeded, commence normal operations
2858 StartupStatus = STARTUP_NOT_RUNNING;
2860 Assert(AbortStartTime == 0);
2861 ReachedNormalRunning = true;
2865 * Crank up the background tasks, if we didn't do that already
2866 * when we entered consistent recovery state. It doesn't matter
2867 * if this fails, we'll just try again later.
2869 if (CheckpointerPID == 0)
2870 CheckpointerPID = StartCheckpointer();
2871 if (BgWriterPID == 0)
2872 BgWriterPID = StartBackgroundWriter();
2873 if (WalWriterPID == 0)
2874 WalWriterPID = StartWalWriter();
2877 * Likewise, start other special children as needed. In a restart
2878 * situation, some of them may be alive already.
2880 if (!IsBinaryUpgrade && AutoVacuumingActive() && AutoVacPID == 0)
2881 AutoVacPID = StartAutoVacLauncher();
2882 if (PgArchStartupAllowed() && PgArchPID == 0)
2883 PgArchPID = pgarch_start();
2885 PgStatPID = pgstat_start();
2887 /* workers may be scheduled to start now */
2888 maybe_start_bgworkers();
2890 /* at this point we are really open for business */
2892 (errmsg("database system is ready to accept connections")));
2895 AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_READY);
2897 sd_notify(0, "READY=1");
2904 * Was it the bgwriter? Normal exit can be ignored; we'll start a new
2905 * one at the next iteration of the postmaster's main loop, if
2906 * necessary. Any other exit condition is treated as a crash.
2908 if (pid == BgWriterPID)
2911 if (!EXIT_STATUS_0(exitstatus))
2912 HandleChildCrash(pid, exitstatus,
2913 _("background writer process"));
2918 * Was it the checkpointer?
2920 if (pid == CheckpointerPID)
2922 CheckpointerPID = 0;
2923 if (EXIT_STATUS_0(exitstatus) && pmState == PM_SHUTDOWN)
2926 * OK, we saw normal exit of the checkpointer after it's been
2927 * told to shut down. We expect that it wrote a shutdown
2928 * checkpoint. (If for some reason it didn't, recovery will
2929 * occur on next postmaster start.)
2931 * At this point we should have no normal backend children
2932 * left (else we'd not be in PM_SHUTDOWN state) but we might
2933 * have dead_end children to wait for.
2935 * If we have an archiver subprocess, tell it to do a last
2936 * archive cycle and quit. Likewise, if we have walsender
2937 * processes, tell them to send any remaining WAL and quit.
2939 Assert(Shutdown > NoShutdown);
2941 /* Waken archiver for the last time */
2943 signal_child(PgArchPID, SIGUSR2);
2946 * Waken walsenders for the last time. No regular backends
2947 * should be around anymore.
2949 SignalChildren(SIGUSR2);
2951 pmState = PM_SHUTDOWN_2;
2954 * We can also shut down the stats collector now; there's
2955 * nothing left for it to do.
2958 signal_child(PgStatPID, SIGQUIT);
2963 * Any unexpected exit of the checkpointer (including FATAL
2964 * exit) is treated as a crash.
2966 HandleChildCrash(pid, exitstatus,
2967 _("checkpointer process"));
2974 * Was it the wal writer? Normal exit can be ignored; we'll start a
2975 * new one at the next iteration of the postmaster's main loop, if
2976 * necessary. Any other exit condition is treated as a crash.
2978 if (pid == WalWriterPID)
2981 if (!EXIT_STATUS_0(exitstatus))
2982 HandleChildCrash(pid, exitstatus,
2983 _("WAL writer process"));
2988 * Was it the wal receiver? If exit status is zero (normal) or one
2989 * (FATAL exit), we assume everything is all right just like normal
2990 * backends. (If we need a new wal receiver, we'll start one at the
2991 * next iteration of the postmaster's main loop.)
2993 if (pid == WalReceiverPID)
2996 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2997 HandleChildCrash(pid, exitstatus,
2998 _("WAL receiver process"));
3003 * Was it the autovacuum launcher? Normal exit can be ignored; we'll
3004 * start a new one at the next iteration of the postmaster's main
3005 * loop, if necessary. Any other exit condition is treated as a
3008 if (pid == AutoVacPID)
3011 if (!EXIT_STATUS_0(exitstatus))
3012 HandleChildCrash(pid, exitstatus,
3013 _("autovacuum launcher process"));
3018 * Was it the archiver? If so, just try to start a new one; no need
3019 * to force reset of the rest of the system. (If fail, we'll try
3020 * again in future cycles of the main loop.). Unless we were waiting
3021 * for it to shut down; don't restart it in that case, and
3022 * PostmasterStateMachine() will advance to the next shutdown step.
3024 if (pid == PgArchPID)
3027 if (!EXIT_STATUS_0(exitstatus))
3028 LogChildExit(LOG, _("archiver process"),
3030 if (PgArchStartupAllowed())
3031 PgArchPID = pgarch_start();
3036 * Was it the statistics collector? If so, just try to start a new
3037 * one; no need to force reset of the rest of the system. (If fail,
3038 * we'll try again in future cycles of the main loop.)
3040 if (pid == PgStatPID)
3043 if (!EXIT_STATUS_0(exitstatus))
3044 LogChildExit(LOG, _("statistics collector process"),
3046 if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
3047 PgStatPID = pgstat_start();
3051 /* Was it the system logger? If so, try to start a new one */
3052 if (pid == SysLoggerPID)
3055 /* for safety's sake, launch new logger *first* */
3056 SysLoggerPID = SysLogger_Start();
3057 if (!EXIT_STATUS_0(exitstatus))
3058 LogChildExit(LOG, _("system logger process"),
3063 /* Was it one of our background workers? */
3064 if (CleanupBackgroundWorker(pid, exitstatus))
3066 /* have it be restarted */
3067 HaveCrashedWorker = true;
3072 * Else do standard backend child cleanup.
3074 CleanupBackend(pid, exitstatus);
3075 } /* loop over pending child-death reports */
3078 * After cleaning out the SIGCHLD queue, see if we have any state changes
3079 * or actions to make.
3081 PostmasterStateMachine();
3083 /* Done with signal handler */
3084 PG_SETMASK(&UnBlockSig);
3090 * Scan the bgworkers list and see if the given PID (which has just stopped
3091 * or crashed) is in it. Handle its shutdown if so, and return true. If not a
3092 * bgworker, return false.
3094 * This is heavily based on CleanupBackend. One important difference is that
3095 * we don't know yet that the dying process is a bgworker, so we must be silent
3096 * until we're sure it is.
3099 CleanupBackgroundWorker(int pid,
3100 int exitstatus) /* child's exit status */
3102 char namebuf[MAXPGPATH];
3103 slist_mutable_iter iter;
3105 slist_foreach_modify(iter, &BackgroundWorkerList)
3107 RegisteredBgWorker *rw;
3109 rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
3111 if (rw->rw_pid != pid)
3115 /* see CleanupBackend */
3116 if (exitstatus == ERROR_WAIT_NO_CHILDREN)
3120 snprintf(namebuf, MAXPGPATH, "%s: %s", _("worker process"),
3121 rw->rw_worker.bgw_name);
3123 if (!EXIT_STATUS_0(exitstatus))
3125 /* Record timestamp, so we know when to restart the worker. */
3126 rw->rw_crashed_at = GetCurrentTimestamp();
3130 /* Zero exit status means terminate */
3131 rw->rw_crashed_at = 0;
3132 rw->rw_terminate = true;
3136 * Additionally, for shared-memory-connected workers, just like a
3137 * backend, any exit status other than 0 or 1 is considered a crash
3138 * and causes a system-wide restart.
3140 if ((rw->rw_worker.bgw_flags & BGWORKER_SHMEM_ACCESS) != 0)
3142 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3144 HandleChildCrash(pid, exitstatus, namebuf);
3150 * We must release the postmaster child slot whether this worker is
3151 * connected to shared memory or not, but we only treat it as a crash
3152 * if it is in fact connected.
3154 if (!ReleasePostmasterChildSlot(rw->rw_child_slot) &&
3155 (rw->rw_worker.bgw_flags & BGWORKER_SHMEM_ACCESS) != 0)
3157 HandleChildCrash(pid, exitstatus, namebuf);
3161 /* Get it out of the BackendList and clear out remaining data */
3162 dlist_delete(&rw->rw_backend->elem);
3164 ShmemBackendArrayRemove(rw->rw_backend);
3168 * It's possible that this background worker started some OTHER
3169 * background worker and asked to be notified when that worker started
3170 * or stopped. If so, cancel any notifications destined for the
3173 if (rw->rw_backend->bgworker_notify)
3174 BackgroundWorkerStopNotifications(rw->rw_pid);
3175 free(rw->rw_backend);
3176 rw->rw_backend = NULL;
3178 rw->rw_child_slot = 0;
3179 ReportBackgroundWorkerExit(&iter); /* report child death */
3181 LogChildExit(EXIT_STATUS_0(exitstatus) ? DEBUG1 : LOG,
3182 namebuf, pid, exitstatus);
3191 * CleanupBackend -- cleanup after terminated backend.
3193 * Remove all local state associated with backend.
3195 * If you change this, see also CleanupBackgroundWorker.
3198 CleanupBackend(int pid,
3199 int exitstatus) /* child's exit status. */
3201 dlist_mutable_iter iter;
3203 LogChildExit(DEBUG2, _("server process"), pid, exitstatus);
3206 * If a backend dies in an ugly way then we must signal all other backends
3207 * to quickdie. If exit status is zero (normal) or one (FATAL exit), we
3208 * assume everything is all right and proceed to remove the backend from
3209 * the active backend list.
3215 * On win32, also treat ERROR_WAIT_NO_CHILDREN (128) as nonfatal case,
3216 * since that sometimes happens under load when the process fails to start
3217 * properly (long before it starts using shared memory). Microsoft reports
3218 * it is related to mutex failure:
3219 * http://archives.postgresql.org/pgsql-hackers/2010-09/msg00790.php
3221 if (exitstatus == ERROR_WAIT_NO_CHILDREN)
3223 LogChildExit(LOG, _("server process"), pid, exitstatus);
3228 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3230 HandleChildCrash(pid, exitstatus, _("server process"));
3234 dlist_foreach_modify(iter, &BackendList)
3236 Backend *bp = dlist_container(Backend, elem, iter.cur);
3242 if (!ReleasePostmasterChildSlot(bp->child_slot))
3245 * Uh-oh, the child failed to clean itself up. Treat as a
3248 HandleChildCrash(pid, exitstatus, _("server process"));
3252 ShmemBackendArrayRemove(bp);
3255 if (bp->bgworker_notify)
3258 * This backend may have been slated to receive SIGUSR1 when
3259 * some background worker started or stopped. Cancel those
3260 * notifications, as we don't want to signal PIDs that are not
3261 * PostgreSQL backends. This gets skipped in the (probably
3262 * very common) case where the backend has never requested any
3263 * such notifications.
3265 BackgroundWorkerStopNotifications(bp->pid);
3267 dlist_delete(iter.cur);
3275 * HandleChildCrash -- cleanup after failed backend, bgwriter, checkpointer,
3276 * walwriter, autovacuum, or background worker.
3278 * The objectives here are to clean up our local state about the child
3279 * process, and to signal all other remaining children to quickdie.
3282 HandleChildCrash(int pid, int exitstatus, const char *procname)
3284 dlist_mutable_iter iter;
3290 * We only log messages and send signals if this is the first process
3291 * crash and we're not doing an immediate shutdown; otherwise, we're only
3292 * here to update postmaster's idea of live processes. If we have already
3293 * signalled children, nonzero exit status is to be expected, so don't
3296 take_action = !FatalError && Shutdown != ImmediateShutdown;
3300 LogChildExit(LOG, procname, pid, exitstatus);
3302 (errmsg("terminating any other active server processes")));
3305 /* Process background workers. */
3306 slist_foreach(siter, &BackgroundWorkerList)
3308 RegisteredBgWorker *rw;
3310 rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
3311 if (rw->rw_pid == 0)
3312 continue; /* not running */
3313 if (rw->rw_pid == pid)
3316 * Found entry for freshly-dead worker, so remove it.
3318 (void) ReleasePostmasterChildSlot(rw->rw_child_slot);
3319 dlist_delete(&rw->rw_backend->elem);
3321 ShmemBackendArrayRemove(rw->rw_backend);
3323 free(rw->rw_backend);
3324 rw->rw_backend = NULL;
3326 rw->rw_child_slot = 0;
3327 /* don't reset crashed_at */
3328 /* don't report child stop, either */
3329 /* Keep looping so we can signal remaining workers */
3334 * This worker is still alive. Unless we did so already, tell it
3335 * to commit hara-kiri.
3337 * SIGQUIT is the special signal that says exit without proc_exit
3338 * and let the user know what's going on. But if SendStop is set
3339 * (-s on command line), then we send SIGSTOP instead, so that we
3340 * can get core dumps from all backends by hand.
3345 (errmsg_internal("sending %s to process %d",
3346 (SendStop ? "SIGSTOP" : "SIGQUIT"),
3347 (int) rw->rw_pid)));
3348 signal_child(rw->rw_pid, (SendStop ? SIGSTOP : SIGQUIT));
3353 /* Process regular backends */
3354 dlist_foreach_modify(iter, &BackendList)
3356 bp = dlist_container(Backend, elem, iter.cur);
3361 * Found entry for freshly-dead backend, so remove it.
3365 (void) ReleasePostmasterChildSlot(bp->child_slot);
3367 ShmemBackendArrayRemove(bp);
3370 dlist_delete(iter.cur);
3372 /* Keep looping so we can signal remaining backends */
3377 * This backend is still alive. Unless we did so already, tell it
3378 * to commit hara-kiri.
3380 * SIGQUIT is the special signal that says exit without proc_exit
3381 * and let the user know what's going on. But if SendStop is set
3382 * (-s on command line), then we send SIGSTOP instead, so that we
3383 * can get core dumps from all backends by hand.
3385 * We could exclude dead_end children here, but at least in the
3386 * SIGSTOP case it seems better to include them.
3388 * Background workers were already processed above; ignore them
3391 if (bp->bkend_type == BACKEND_TYPE_BGWORKER)
3397 (errmsg_internal("sending %s to process %d",
3398 (SendStop ? "SIGSTOP" : "SIGQUIT"),
3400 signal_child(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
3405 /* Take care of the startup process too */
3406 if (pid == StartupPID)
3409 StartupStatus = STARTUP_CRASHED;
3411 else if (StartupPID != 0 && take_action)
3414 (errmsg_internal("sending %s to process %d",
3415 (SendStop ? "SIGSTOP" : "SIGQUIT"),
3416 (int) StartupPID)));
3417 signal_child(StartupPID, (SendStop ? SIGSTOP : SIGQUIT));
3418 StartupStatus = STARTUP_SIGNALED;
3421 /* Take care of the bgwriter too */
3422 if (pid == BgWriterPID)
3424 else if (BgWriterPID != 0 && take_action)
3427 (errmsg_internal("sending %s to process %d",
3428 (SendStop ? "SIGSTOP" : "SIGQUIT"),
3429 (int) BgWriterPID)));
3430 signal_child(BgWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
3433 /* Take care of the checkpointer too */
3434 if (pid == CheckpointerPID)
3435 CheckpointerPID = 0;
3436 else if (CheckpointerPID != 0 && take_action)
3439 (errmsg_internal("sending %s to process %d",
3440 (SendStop ? "SIGSTOP" : "SIGQUIT"),
3441 (int) CheckpointerPID)));
3442 signal_child(CheckpointerPID, (SendStop ? SIGSTOP : SIGQUIT));
3445 /* Take care of the walwriter too */
3446 if (pid == WalWriterPID)
3448 else if (WalWriterPID != 0 && take_action)
3451 (errmsg_internal("sending %s to process %d",
3452 (SendStop ? "SIGSTOP" : "SIGQUIT"),
3453 (int) WalWriterPID)));
3454 signal_child(WalWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
3457 /* Take care of the walreceiver too */
3458 if (pid == WalReceiverPID)
3460 else if (WalReceiverPID != 0 && take_action)
3463 (errmsg_internal("sending %s to process %d",
3464 (SendStop ? "SIGSTOP" : "SIGQUIT"),
3465 (int) WalReceiverPID)));
3466 signal_child(WalReceiverPID, (SendStop ? SIGSTOP : SIGQUIT));
3469 /* Take care of the autovacuum launcher too */
3470 if (pid == AutoVacPID)
3472 else if (AutoVacPID != 0 && take_action)
3475 (errmsg_internal("sending %s to process %d",
3476 (SendStop ? "SIGSTOP" : "SIGQUIT"),
3477 (int) AutoVacPID)));
3478 signal_child(AutoVacPID, (SendStop ? SIGSTOP : SIGQUIT));
3482 * Force a power-cycle of the pgarch process too. (This isn't absolutely
3483 * necessary, but it seems like a good idea for robustness, and it
3484 * simplifies the state-machine logic in the case where a shutdown request
3485 * arrives during crash processing.)
3487 if (PgArchPID != 0 && take_action)
3490 (errmsg_internal("sending %s to process %d",
3493 signal_child(PgArchPID, SIGQUIT);
3497 * Force a power-cycle of the pgstat process too. (This isn't absolutely
3498 * necessary, but it seems like a good idea for robustness, and it
3499 * simplifies the state-machine logic in the case where a shutdown request
3500 * arrives during crash processing.)
3502 if (PgStatPID != 0 && take_action)
3505 (errmsg_internal("sending %s to process %d",
3508 signal_child(PgStatPID, SIGQUIT);
3509 allow_immediate_pgstat_restart();
3512 /* We do NOT restart the syslogger */
3514 if (Shutdown != ImmediateShutdown)
3517 /* We now transit into a state of waiting for children to die */
3518 if (pmState == PM_RECOVERY ||
3519 pmState == PM_HOT_STANDBY ||
3520 pmState == PM_RUN ||
3521 pmState == PM_WAIT_BACKUP ||
3522 pmState == PM_WAIT_READONLY ||
3523 pmState == PM_SHUTDOWN)
3524 pmState = PM_WAIT_BACKENDS;
3527 * .. and if this doesn't happen quickly enough, now the clock is ticking
3528 * for us to kill them without mercy.
3530 if (AbortStartTime == 0)
3531 AbortStartTime = time(NULL);
3535 * Log the death of a child process.
3538 LogChildExit(int lev, const char *procname, int pid, int exitstatus)
3541 * size of activity_buffer is arbitrary, but set equal to default
3542 * track_activity_query_size
3544 char activity_buffer[1024];
3545 const char *activity = NULL;
3547 if (!EXIT_STATUS_0(exitstatus))
3548 activity = pgstat_get_crashed_backend_activity(pid,
3550 sizeof(activity_buffer));
3552 if (WIFEXITED(exitstatus))
3556 translator: %s is a noun phrase describing a child process, such as
3558 (errmsg("%s (PID %d) exited with exit code %d",
3559 procname, pid, WEXITSTATUS(exitstatus)),
3560 activity ? errdetail("Failed process was running: %s", activity) : 0));
3561 else if (WIFSIGNALED(exitstatus))
3566 translator: %s is a noun phrase describing a child process, such as
3568 (errmsg("%s (PID %d) was terminated by exception 0x%X",
3569 procname, pid, WTERMSIG(exitstatus)),
3570 errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
3571 activity ? errdetail("Failed process was running: %s", activity) : 0));
3572 #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST
3576 translator: %s is a noun phrase describing a child process, such as
3578 (errmsg("%s (PID %d) was terminated by signal %d: %s",
3579 procname, pid, WTERMSIG(exitstatus),
3580 WTERMSIG(exitstatus) < NSIG ?
3581 sys_siglist[WTERMSIG(exitstatus)] : "(unknown)"),
3582 activity ? errdetail("Failed process was running: %s", activity) : 0));
3587 translator: %s is a noun phrase describing a child process, such as
3589 (errmsg("%s (PID %d) was terminated by signal %d",
3590 procname, pid, WTERMSIG(exitstatus)),
3591 activity ? errdetail("Failed process was running: %s", activity) : 0));
3597 translator: %s is a noun phrase describing a child process, such as
3599 (errmsg("%s (PID %d) exited with unrecognized status %d",
3600 procname, pid, exitstatus),
3601 activity ? errdetail("Failed process was running: %s", activity) : 0));
3605 * Advance the postmaster's state machine and take actions as appropriate
3607 * This is common code for pmdie(), reaper() and sigusr1_handler(), which
3608 * receive the signals that might mean we need to change state.
3611 PostmasterStateMachine(void)
3613 if (pmState == PM_WAIT_BACKUP)
3616 * PM_WAIT_BACKUP state ends when online backup mode is not active.
3618 if (!BackupInProgress())
3619 pmState = PM_WAIT_BACKENDS;
3622 if (pmState == PM_WAIT_READONLY)
3625 * PM_WAIT_READONLY state ends when we have no regular backends that
3626 * have been started during recovery. We kill the startup and
3627 * walreceiver processes and transition to PM_WAIT_BACKENDS. Ideally,
3628 * we might like to kill these processes first and then wait for
3629 * backends to die off, but that doesn't work at present because
3630 * killing the startup process doesn't release its locks.
3632 if (CountChildren(BACKEND_TYPE_NORMAL) == 0)
3634 if (StartupPID != 0)
3635 signal_child(StartupPID, SIGTERM);
3636 if (WalReceiverPID != 0)
3637 signal_child(WalReceiverPID, SIGTERM);
3638 pmState = PM_WAIT_BACKENDS;
3643 * If we are in a state-machine state that implies waiting for backends to
3644 * exit, see if they're all gone, and change state if so.
3646 if (pmState == PM_WAIT_BACKENDS)
3649 * PM_WAIT_BACKENDS state ends when we have no regular backends
3650 * (including autovac workers), no bgworkers (including unconnected
3651 * ones), and no walwriter, autovac launcher or bgwriter. If we are
3652 * doing crash recovery or an immediate shutdown then we expect the
3653 * checkpointer to exit as well, otherwise not. The archiver, stats,
3654 * and syslogger processes are disregarded since they are not
3655 * connected to shared memory; we also disregard dead_end children
3656 * here. Walsenders are also disregarded, they will be terminated
3657 * later after writing the checkpoint record, like the archiver
3660 if (CountChildren(BACKEND_TYPE_NORMAL | BACKEND_TYPE_WORKER) == 0 &&
3662 WalReceiverPID == 0 &&
3664 (CheckpointerPID == 0 ||
3665 (!FatalError && Shutdown < ImmediateShutdown)) &&
3666 WalWriterPID == 0 &&
3669 if (Shutdown >= ImmediateShutdown || FatalError)
3672 * Start waiting for dead_end children to die. This state
3673 * change causes ServerLoop to stop creating new ones.
3675 pmState = PM_WAIT_DEAD_END;
3678 * We already SIGQUIT'd the archiver and stats processes, if
3679 * any, when we started immediate shutdown or entered
3686 * If we get here, we are proceeding with normal shutdown. All
3687 * the regular children are gone, and it's time to tell the
3688 * checkpointer to do a shutdown checkpoint.
3690 Assert(Shutdown > NoShutdown);
3691 /* Start the checkpointer if not running */
3692 if (CheckpointerPID == 0)
3693 CheckpointerPID = StartCheckpointer();
3694 /* And tell it to shut down */
3695 if (CheckpointerPID != 0)
3697 signal_child(CheckpointerPID, SIGUSR2);
3698 pmState = PM_SHUTDOWN;
3703 * If we failed to fork a checkpointer, just shut down.
3704 * Any required cleanup will happen at next restart. We
3705 * set FatalError so that an "abnormal shutdown" message
3706 * gets logged when we exit.
3709 pmState = PM_WAIT_DEAD_END;
3711 /* Kill the walsenders, archiver and stats collector too */
3712 SignalChildren(SIGQUIT);
3714 signal_child(PgArchPID, SIGQUIT);
3716 signal_child(PgStatPID, SIGQUIT);
3722 if (pmState == PM_SHUTDOWN_2)
3725 * PM_SHUTDOWN_2 state ends when there's no other children than
3726 * dead_end children left. There shouldn't be any regular backends
3727 * left by now anyway; what we're really waiting for is walsenders and
3730 * Walreceiver should normally be dead by now, but not when a fast
3731 * shutdown is performed during recovery.
3733 if (PgArchPID == 0 && CountChildren(BACKEND_TYPE_ALL) == 0 &&
3734 WalReceiverPID == 0)
3736 pmState = PM_WAIT_DEAD_END;
3740 if (pmState == PM_WAIT_DEAD_END)
3743 * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
3744 * (ie, no dead_end children remain), and the archiver and stats
3745 * collector are gone too.
3747 * The reason we wait for those two is to protect them against a new
3748 * postmaster starting conflicting subprocesses; this isn't an
3749 * ironclad protection, but it at least helps in the
3750 * shutdown-and-immediately-restart scenario. Note that they have
3751 * already been sent appropriate shutdown signals, either during a
3752 * normal state transition leading up to PM_WAIT_DEAD_END, or during
3753 * FatalError processing.
3755 if (dlist_is_empty(&BackendList) &&
3756 PgArchPID == 0 && PgStatPID == 0)
3758 /* These other guys should be dead already */
3759 Assert(StartupPID == 0);
3760 Assert(WalReceiverPID == 0);
3761 Assert(BgWriterPID == 0);
3762 Assert(CheckpointerPID == 0);
3763 Assert(WalWriterPID == 0);
3764 Assert(AutoVacPID == 0);
3765 /* syslogger is not considered here */
3766 pmState = PM_NO_CHILDREN;
3771 * If we've been told to shut down, we exit as soon as there are no
3772 * remaining children. If there was a crash, cleanup will occur at the
3773 * next startup. (Before PostgreSQL 8.3, we tried to recover from the
3774 * crash before exiting, but that seems unwise if we are quitting because
3775 * we got SIGTERM from init --- there may well not be time for recovery
3776 * before init decides to SIGKILL us.)
3778 * Note that the syslogger continues to run. It will exit when it sees
3779 * EOF on its input pipe, which happens when there are no more upstream
3782 if (Shutdown > NoShutdown && pmState == PM_NO_CHILDREN)
3786 ereport(LOG, (errmsg("abnormal database system shutdown")));
3792 * Terminate exclusive backup mode to avoid recovery after a clean
3793 * fast shutdown. Since an exclusive backup can only be taken
3794 * during normal running (and not, for example, while running
3795 * under Hot Standby) it only makes sense to do this if we reached
3796 * normal running. If we're still in recovery, the backup file is
3797 * one we're recovering *from*, and we must keep it around so that
3798 * recovery restarts from the right place.
3800 if (ReachedNormalRunning)
3803 /* Normal exit from the postmaster is here */
3809 * If the startup process failed, or the user does not want an automatic
3810 * restart after backend crashes, wait for all non-syslogger children to
3811 * exit, and then exit postmaster. We don't try to reinitialize when the
3812 * startup process fails, because more than likely it will just fail again
3813 * and we will keep trying forever.
3815 if (pmState == PM_NO_CHILDREN &&
3816 (StartupStatus == STARTUP_CRASHED || !restart_after_crash))
3820 * If we need to recover from a crash, wait for all non-syslogger children
3821 * to exit, then reset shmem and StartupDataBase.
3823 if (FatalError && pmState == PM_NO_CHILDREN)
3826 (errmsg("all server processes terminated; reinitializing")));
3828 /* allow background workers to immediately restart */
3829 ResetBackgroundWorkerCrashTimes();
3833 /* re-read control file into local memory */
3834 LocalProcessControlFile(true);
3836 reset_shared(PostPortNumber);
3838 StartupPID = StartupDataBase();
3839 Assert(StartupPID != 0);
3840 StartupStatus = STARTUP_RUNNING;
3841 pmState = PM_STARTUP;
3842 /* crash recovery started, reset SIGKILL flag */
3849 * Send a signal to a postmaster child process
3851 * On systems that have setsid(), each child process sets itself up as a
3852 * process group leader. For signals that are generally interpreted in the
3853 * appropriate fashion, we signal the entire process group not just the
3854 * direct child process. This allows us to, for example, SIGQUIT a blocked
3855 * archive_recovery script, or SIGINT a script being run by a backend via
3858 * There is a race condition for recently-forked children: they might not
3859 * have executed setsid() yet. So we signal the child directly as well as
3860 * the group. We assume such a child will handle the signal before trying
3861 * to spawn any grandchild processes. We also assume that signaling the
3862 * child twice will not cause any problems.
3865 signal_child(pid_t pid, int signal)
3867 if (kill(pid, signal) < 0)
3868 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
3877 if (kill(-pid, signal) < 0)
3878 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) (-pid), signal);
3887 * Send a signal to the targeted children (but NOT special children;
3888 * dead_end children are never signaled, either).
3891 SignalSomeChildren(int signal, int target)
3894 bool signaled = false;
3896 dlist_foreach(iter, &BackendList)
3898 Backend *bp = dlist_container(Backend, elem, iter.cur);
3904 * Since target == BACKEND_TYPE_ALL is the most common case, we test
3905 * it first and avoid touching shared memory for every child.
3907 if (target != BACKEND_TYPE_ALL)
3910 * Assign bkend_type for any recently announced WAL Sender
3913 if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
3914 IsPostmasterChildWalSender(bp->child_slot))
3915 bp->bkend_type = BACKEND_TYPE_WALSND;
3917 if (!(target & bp->bkend_type))
3922 (errmsg_internal("sending signal %d to process %d",
3923 signal, (int) bp->pid)));
3924 signal_child(bp->pid, signal);
3931 * Send a termination signal to children. This considers all of our children
3932 * processes, except syslogger and dead_end backends.
3935 TerminateChildren(int signal)
3937 SignalChildren(signal);
3938 if (StartupPID != 0)
3940 signal_child(StartupPID, signal);
3941 if (signal == SIGQUIT || signal == SIGKILL)
3942 StartupStatus = STARTUP_SIGNALED;
3944 if (BgWriterPID != 0)
3945 signal_child(BgWriterPID, signal);
3946 if (CheckpointerPID != 0)
3947 signal_child(CheckpointerPID, signal);
3948 if (WalWriterPID != 0)
3949 signal_child(WalWriterPID, signal);
3950 if (WalReceiverPID != 0)
3951 signal_child(WalReceiverPID, signal);
3952 if (AutoVacPID != 0)
3953 signal_child(AutoVacPID, signal);
3955 signal_child(PgArchPID, signal);
3957 signal_child(PgStatPID, signal);
3961 * BackendStartup -- start backend process
3963 * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
3965 * Note: if you change this code, also consider StartAutovacuumWorker.
3968 BackendStartup(Port *port)
3970 Backend *bn; /* for backend cleanup */
3974 * Create backend data structure. Better before the fork() so we can
3975 * handle failure cleanly.
3977 bn = (Backend *) malloc(sizeof(Backend));
3981 (errcode(ERRCODE_OUT_OF_MEMORY),
3982 errmsg("out of memory")));
3983 return STATUS_ERROR;
3987 * Compute the cancel key that will be assigned to this backend. The
3988 * backend will have its own copy in the forked-off process' value of
3989 * MyCancelKey, so that it can transmit the key to the frontend.
3991 if (!RandomCancelKey(&MyCancelKey))
3995 (errcode(ERRCODE_INTERNAL_ERROR),
3996 errmsg("could not generate random cancel key")));
3997 return STATUS_ERROR;
4000 bn->cancel_key = MyCancelKey;
4002 /* Pass down canAcceptConnections state */
4003 port->canAcceptConnections = canAcceptConnections();
4004 bn->dead_end = (port->canAcceptConnections != CAC_OK &&
4005 port->canAcceptConnections != CAC_WAITBACKUP);
4008 * Unless it's a dead_end child, assign it a child slot number
4011 bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
4015 /* Hasn't asked to be notified about any bgworkers yet */
4016 bn->bgworker_notify = false;
4019 pid = backend_forkexec(port);
4020 #else /* !EXEC_BACKEND */
4021 pid = fork_process();
4022 if (pid == 0) /* child */
4026 /* Detangle from postmaster */
4027 InitPostmasterChild();
4029 /* Close the postmaster's sockets */
4030 ClosePostmasterPorts(false);
4032 /* Perform additional initialization and collect startup packet */
4033 BackendInitialize(port);
4035 /* And run the backend */
4038 #endif /* EXEC_BACKEND */
4042 /* in parent, fork failed */
4043 int save_errno = errno;
4046 (void) ReleasePostmasterChildSlot(bn->child_slot);
4050 (errmsg("could not fork new process for connection: %m")));
4051 report_fork_failure_to_client(port, save_errno);
4052 return STATUS_ERROR;
4055 /* in parent, successful fork */
4057 (errmsg_internal("forked new backend, pid=%d socket=%d",
4058 (int) pid, (int) port->sock)));
4061 * Everything's been successful, it's safe to add this backend to our list
4065 bn->bkend_type = BACKEND_TYPE_NORMAL; /* Can change later to WALSND */
4066 dlist_push_head(&BackendList, &bn->elem);
4070 ShmemBackendArrayAdd(bn);
4077 * Try to report backend fork() failure to client before we close the
4078 * connection. Since we do not care to risk blocking the postmaster on
4079 * this connection, we set the connection to non-blocking and try only once.
4081 * This is grungy special-purpose code; we cannot use backend libpq since
4082 * it's not up and running.
4085 report_fork_failure_to_client(Port *port, int errnum)
4090 /* Format the error message packet (always V2 protocol) */
4091 snprintf(buffer, sizeof(buffer), "E%s%s\n",
4092 _("could not fork new process for connection: "),
4095 /* Set port to non-blocking. Don't do send() if this fails */
4096 if (!pg_set_noblock(port->sock))
4099 /* We'll retry after EINTR, but ignore all other failures */
4102 rc = send(port->sock, buffer, strlen(buffer) + 1, 0);
4103 } while (rc < 0 && errno == EINTR);
4108 * BackendInitialize -- initialize an interactive (postmaster-child)
4109 * backend process, and collect the client's startup packet.
4111 * returns: nothing. Will not return at all if there's any failure.
4113 * Note: this code does not depend on having any access to shared memory.
4114 * In the EXEC_BACKEND case, we are physically attached to shared memory
4115 * but have not yet set up most of our local pointers to shmem structures.
4118 BackendInitialize(Port *port)
4122 char remote_host[NI_MAXHOST];
4123 char remote_port[NI_MAXSERV];
4124 char remote_ps_data[NI_MAXHOST];
4126 /* Save port etc. for ps status */
4130 * PreAuthDelay is a debugging aid for investigating problems in the
4131 * authentication cycle: it can be set in postgresql.conf to allow time to
4132 * attach to the newly-forked backend with a debugger. (See also
4133 * PostAuthDelay, which we allow clients to pass through PGOPTIONS, but it
4134 * is not honored until after authentication.)
4136 if (PreAuthDelay > 0)
4137 pg_usleep(PreAuthDelay * 1000000L);
4139 /* This flag will remain set until InitPostgres finishes authentication */
4140 ClientAuthInProgress = true; /* limit visibility of log messages */
4142 /* save process start time */
4143 port->SessionStartTime = GetCurrentTimestamp();
4144 MyStartTime = timestamptz_to_time_t(port->SessionStartTime);
4146 /* set these to empty in case they are needed before we set them up */
4147 port->remote_host = "";
4148 port->remote_port = "";
4151 * Initialize libpq and enable reporting of ereport errors to the client.
4152 * Must do this now because authentication uses libpq to send messages.
4154 pq_init(); /* initialize libpq to talk to client */
4155 whereToSendOutput = DestRemote; /* now safe to ereport to client */
4158 * We arrange for a simple exit(1) if we receive SIGTERM or SIGQUIT or
4159 * timeout while trying to collect the startup packet. Otherwise the
4160 * postmaster cannot shutdown the database FAST or IMMED cleanly if a
4161 * buggy client fails to send the packet promptly. XXX it follows that
4162 * the remainder of this function must tolerate losing control at any
4163 * instant. Likewise, any pg_on_exit_callback registered before or during
4164 * this function must be prepared to execute at any instant between here
4165 * and the end of this function. Furthermore, affected callbacks execute
4166 * partially or not at all when a second exit-inducing signal arrives
4167 * after proc_exit_prepare() decrements on_proc_exit_index. (Thanks to
4168 * that mechanic, callbacks need not anticipate more than one call.) This
4169 * is fragile; it ought to instead follow the norm of handling interrupts
4170 * at selected, safe opportunities.
4172 pqsignal(SIGTERM, startup_die);
4173 pqsignal(SIGQUIT, startup_die);
4174 InitializeTimeouts(); /* establishes SIGALRM handler */
4175 PG_SETMASK(&StartupBlockSig);
4178 * Get the remote host name and port for logging and status display.
4180 remote_host[0] = '\0';
4181 remote_port[0] = '\0';
4182 if ((ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
4183 remote_host, sizeof(remote_host),
4184 remote_port, sizeof(remote_port),
4185 (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV)) != 0)
4187 (errmsg_internal("pg_getnameinfo_all() failed: %s",
4188 gai_strerror(ret))));
4189 if (remote_port[0] == '\0')
4190 snprintf(remote_ps_data, sizeof(remote_ps_data), "%s", remote_host);
4192 snprintf(remote_ps_data, sizeof(remote_ps_data), "%s(%s)", remote_host, remote_port);
4195 * Save remote_host and remote_port in port structure (after this, they
4196 * will appear in log_line_prefix data for log messages).
4198 port->remote_host = strdup(remote_host);
4199 port->remote_port = strdup(remote_port);
4201 /* And now we can issue the Log_connections message, if wanted */
4202 if (Log_connections)
4206 (errmsg("connection received: host=%s port=%s",
4211 (errmsg("connection received: host=%s",
4216 * If we did a reverse lookup to name, we might as well save the results
4217 * rather than possibly repeating the lookup during authentication.
4219 * Note that we don't want to specify NI_NAMEREQD above, because then we'd
4220 * get nothing useful for a client without an rDNS entry. Therefore, we
4221 * must check whether we got a numeric IPv4 or IPv6 address, and not save
4222 * it into remote_hostname if so. (This test is conservative and might
4223 * sometimes classify a hostname as numeric, but an error in that
4224 * direction is safe; it only results in a possible extra lookup.)
4228 strspn(remote_host, "0123456789.") < strlen(remote_host) &&
4229 strspn(remote_host, "0123456789ABCDEFabcdef:") < strlen(remote_host))
4230 port->remote_hostname = strdup(remote_host);
4233 * Ready to begin client interaction. We will give up and exit(1) after a
4234 * time delay, so that a broken client can't hog a connection
4235 * indefinitely. PreAuthDelay and any DNS interactions above don't count
4236 * against the time limit.
4238 * Note: AuthenticationTimeout is applied here while waiting for the
4239 * startup packet, and then again in InitPostgres for the duration of any
4240 * authentication operations. So a hostile client could tie up the
4241 * process for nearly twice AuthenticationTimeout before we kick him off.
4243 * Note: because PostgresMain will call InitializeTimeouts again, the
4244 * registration of STARTUP_PACKET_TIMEOUT will be lost. This is okay
4245 * since we never use it again after this function.
4247 RegisterTimeout(STARTUP_PACKET_TIMEOUT, StartupPacketTimeoutHandler);
4248 enable_timeout_after(STARTUP_PACKET_TIMEOUT, AuthenticationTimeout * 1000);
4251 * Receive the startup packet (which might turn out to be a cancel request
4254 status = ProcessStartupPacket(port, false);
4257 * Stop here if it was bad or a cancel packet. ProcessStartupPacket
4258 * already did any appropriate error reporting.
4260 if (status != STATUS_OK)
4264 * Now that we have the user and database name, we can set the process
4265 * title for ps. It's good to do this as early as possible in startup.
4267 * For a walsender, the ps display is set in the following form:
4269 * postgres: walsender <user> <host> <activity>
4271 * To achieve that, we pass "walsender" as username and username
4272 * as dbname to init_ps_display(). XXX: should add a new variant of
4273 * init_ps_display() to avoid abusing the parameters like this.
4276 init_ps_display(pgstat_get_backend_desc(B_WAL_SENDER), port->user_name, remote_ps_data,
4277 update_process_title ? "authentication" : "");
4279 init_ps_display(port->user_name, port->database_name, remote_ps_data,
4280 update_process_title ? "authentication" : "");
4283 * Disable the timeout, and prevent SIGTERM/SIGQUIT again.
4285 disable_timeout(STARTUP_PACKET_TIMEOUT, false);
4286 PG_SETMASK(&BlockSig);
4291 * BackendRun -- set up the backend's argument list and invoke PostgresMain()
4294 * Shouldn't return at all.
4295 * If PostgresMain() fails, return status.
4298 BackendRun(Port *port)
4308 * Don't want backend to be able to see the postmaster random number
4309 * generator state. We have to clobber the static random_seed *and* start
4310 * a new random sequence in the random() library function.
4312 #ifndef HAVE_STRONG_RANDOM
4314 random_start_time.tv_usec = 0;
4316 /* slightly hacky way to convert timestamptz into integers */
4317 TimestampDifference(0, port->SessionStartTime, &secs, &usecs);
4318 srandom((unsigned int) (MyProcPid ^ (usecs << 12) ^ secs));
4321 * Now, build the argv vector that will be given to PostgresMain.
4323 * The maximum possible number of commandline arguments that could come
4324 * from ExtraOptions is (strlen(ExtraOptions) + 1) / 2; see
4327 maxac = 2; /* for fixed args supplied below */
4328 maxac += (strlen(ExtraOptions) + 1) / 2;
4330 av = (char **) MemoryContextAlloc(TopMemoryContext,
4331 maxac * sizeof(char *));
4334 av[ac++] = "postgres";
4337 * Pass any backend switches specified with -o on the postmaster's own
4338 * command line. We assume these are secure.
4340 pg_split_opts(av, &ac, ExtraOptions);
4347 * Debug: print arguments being passed to backend
4350 (errmsg_internal("%s child[%d]: starting with (",
4351 progname, (int) getpid())));
4352 for (i = 0; i < ac; ++i)
4354 (errmsg_internal("\t%s", av[i])));
4356 (errmsg_internal(")")));
4359 * Make sure we aren't in PostmasterContext anymore. (We can't delete it
4360 * just yet, though, because InitPostgres will need the HBA data.)
4362 MemoryContextSwitchTo(TopMemoryContext);
4364 PostgresMain(ac, av, port->database_name, port->user_name);
4371 * postmaster_forkexec -- fork and exec a postmaster subprocess
4373 * The caller must have set up the argv array already, except for argv[2]
4374 * which will be filled with the name of the temp variable file.
4376 * Returns the child process PID, or -1 on fork failure (a suitable error
4377 * message has been logged on failure).
4379 * All uses of this routine will dispatch to SubPostmasterMain in the
4383 postmaster_forkexec(int argc, char *argv[])
4387 /* This entry point passes dummy values for the Port variables */
4388 memset(&port, 0, sizeof(port));
4389 return internal_forkexec(argc, argv, &port);
4393 * backend_forkexec -- fork/exec off a backend process
4395 * Some operating systems (WIN32) don't have fork() so we have to simulate
4396 * it by storing parameters that need to be passed to the child and
4397 * then create a new child process.
4399 * returns the pid of the fork/exec'd process, or -1 on failure
4402 backend_forkexec(Port *port)
4407 av[ac++] = "postgres";
4408 av[ac++] = "--forkbackend";
4409 av[ac++] = NULL; /* filled in by internal_forkexec */
4412 Assert(ac < lengthof(av));
4414 return internal_forkexec(ac, av, port);
4420 * internal_forkexec non-win32 implementation
4422 * - writes out backend variables to the parameter file
4423 * - fork():s, and then exec():s the child process
4426 internal_forkexec(int argc, char *argv[], Port *port)
4428 static unsigned long tmpBackendFileNum = 0;
4430 char tmpfilename[MAXPGPATH];
4431 BackendParameters param;
4434 if (!save_backend_variables(¶m, port))
4435 return -1; /* log made by save_backend_variables */
4437 /* Calculate name for temp file */
4438 snprintf(tmpfilename, MAXPGPATH, "%s/%s.backend_var.%d.%lu",
4439 PG_TEMP_FILES_DIR, PG_TEMP_FILE_PREFIX,
4440 MyProcPid, ++tmpBackendFileNum);
4443 fp = AllocateFile(tmpfilename, PG_BINARY_W);
4447 * As in OpenTemporaryFileInTablespace, try to make the temp-file
4450 mkdir(PG_TEMP_FILES_DIR, S_IRWXU);
4452 fp = AllocateFile(tmpfilename, PG_BINARY_W);
4456 (errcode_for_file_access(),
4457 errmsg("could not create file \"%s\": %m",
4463 if (fwrite(¶m, sizeof(param), 1, fp) != 1)
4466 (errcode_for_file_access(),
4467 errmsg("could not write to file \"%s\": %m", tmpfilename)));
4476 (errcode_for_file_access(),
4477 errmsg("could not write to file \"%s\": %m", tmpfilename)));
4481 /* Make sure caller set up argv properly */
4483 Assert(argv[argc] == NULL);
4484 Assert(strncmp(argv[1], "--fork", 6) == 0);
4485 Assert(argv[2] == NULL);
4487 /* Insert temp file name after --fork argument */
4488 argv[2] = tmpfilename;
4490 /* Fire off execv in child */
4491 if ((pid = fork_process()) == 0)
4493 if (execv(postgres_exec_path, argv) < 0)
4496 (errmsg("could not execute server process \"%s\": %m",
4497 postgres_exec_path)));
4498 /* We're already in the child process here, can't return */
4503 return pid; /* Parent returns pid, or -1 on fork failure */
4508 * internal_forkexec win32 implementation
4510 * - starts backend using CreateProcess(), in suspended state
4511 * - writes out backend variables to the parameter file
4512 * - during this, duplicates handles and sockets required for
4513 * inheritance into the new process
4514 * - resumes execution of the new process once the backend parameter
4518 internal_forkexec(int argc, char *argv[], Port *port)
4520 int retry_count = 0;
4522 PROCESS_INFORMATION pi;
4525 char cmdLine[MAXPGPATH * 2];
4527 BackendParameters *param;
4528 SECURITY_ATTRIBUTES sa;
4529 char paramHandleStr[32];
4530 win32_deadchild_waitinfo *childinfo;
4532 /* Make sure caller set up argv properly */
4534 Assert(argv[argc] == NULL);
4535 Assert(strncmp(argv[1], "--fork", 6) == 0);
4536 Assert(argv[2] == NULL);
4538 /* Resume here if we need to retry */
4541 /* Set up shared memory for parameter passing */
4542 ZeroMemory(&sa, sizeof(sa));
4543 sa.nLength = sizeof(sa);
4544 sa.bInheritHandle = TRUE;
4545 paramHandle = CreateFileMapping(INVALID_HANDLE_VALUE,
4549 sizeof(BackendParameters),
4551 if (paramHandle == INVALID_HANDLE_VALUE)
4553 elog(LOG, "could not create backend parameter file mapping: error code %lu",
4558 param = MapViewOfFile(paramHandle, FILE_MAP_WRITE, 0, 0, sizeof(BackendParameters));
4561 elog(LOG, "could not map backend parameter memory: error code %lu",
4563 CloseHandle(paramHandle);
4567 /* Insert temp file name after --fork argument */
4569 sprintf(paramHandleStr, "%llu", (LONG_PTR) paramHandle);
4571 sprintf(paramHandleStr, "%lu", (DWORD) paramHandle);
4573 argv[2] = paramHandleStr;
4575 /* Format the cmd line */
4576 cmdLine[sizeof(cmdLine) - 1] = '\0';
4577 cmdLine[sizeof(cmdLine) - 2] = '\0';
4578 snprintf(cmdLine, sizeof(cmdLine) - 1, "\"%s\"", postgres_exec_path);
4580 while (argv[++i] != NULL)
4582 j = strlen(cmdLine);
4583 snprintf(cmdLine + j, sizeof(cmdLine) - 1 - j, " \"%s\"", argv[i]);
4585 if (cmdLine[sizeof(cmdLine) - 2] != '\0')
4587 elog(LOG, "subprocess command line too long");
4591 memset(&pi, 0, sizeof(pi));
4592 memset(&si, 0, sizeof(si));
4596 * Create the subprocess in a suspended state. This will be resumed later,
4597 * once we have written out the parameter file.
4599 if (!CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, CREATE_SUSPENDED,
4600 NULL, NULL, &si, &pi))
4602 elog(LOG, "CreateProcess call failed: %m (error code %lu)",
4607 if (!save_backend_variables(param, port, pi.hProcess, pi.dwProcessId))
4610 * log made by save_backend_variables, but we have to clean up the
4611 * mess with the half-started process
4613 if (!TerminateProcess(pi.hProcess, 255))
4615 (errmsg_internal("could not terminate unstarted process: error code %lu",
4617 CloseHandle(pi.hProcess);
4618 CloseHandle(pi.hThread);
4619 return -1; /* log made by save_backend_variables */
4622 /* Drop the parameter shared memory that is now inherited to the backend */
4623 if (!UnmapViewOfFile(param))
4624 elog(LOG, "could not unmap view of backend parameter file: error code %lu",
4626 if (!CloseHandle(paramHandle))
4627 elog(LOG, "could not close handle to backend parameter file: error code %lu",
4631 * Reserve the memory region used by our main shared memory segment before
4632 * we resume the child process. Normally this should succeed, but if ASLR
4633 * is active then it might sometimes fail due to the stack or heap having
4634 * gotten mapped into that range. In that case, just terminate the
4635 * process and retry.
4637 if (!pgwin32_ReserveSharedMemoryRegion(pi.hProcess))
4639 /* pgwin32_ReserveSharedMemoryRegion already made a log entry */
4640 if (!TerminateProcess(pi.hProcess, 255))
4642 (errmsg_internal("could not terminate process that failed to reserve memory: error code %lu",
4644 CloseHandle(pi.hProcess);
4645 CloseHandle(pi.hThread);
4646 if (++retry_count < 100)
4649 (errmsg("giving up after too many tries to reserve shared memory"),
4650 errhint("This might be caused by ASLR or antivirus software.")));
4655 * Now that the backend variables are written out, we start the child
4656 * thread so it can start initializing while we set up the rest of the
4659 if (ResumeThread(pi.hThread) == -1)
4661 if (!TerminateProcess(pi.hProcess, 255))
4664 (errmsg_internal("could not terminate unstartable process: error code %lu",
4666 CloseHandle(pi.hProcess);
4667 CloseHandle(pi.hThread);
4670 CloseHandle(pi.hProcess);
4671 CloseHandle(pi.hThread);
4673 (errmsg_internal("could not resume thread of unstarted process: error code %lu",
4679 * Queue a waiter for to signal when this child dies. The wait will be
4680 * handled automatically by an operating system thread pool.
4682 * Note: use malloc instead of palloc, since it needs to be thread-safe.
4683 * Struct will be free():d from the callback function that runs on a
4686 childinfo = malloc(sizeof(win32_deadchild_waitinfo));
4689 (errcode(ERRCODE_OUT_OF_MEMORY),
4690 errmsg("out of memory")));
4692 childinfo->procHandle = pi.hProcess;
4693 childinfo->procId = pi.dwProcessId;
4695 if (!RegisterWaitForSingleObject(&childinfo->waitHandle,
4697 pgwin32_deadchild_callback,
4700 WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD))
4702 (errmsg_internal("could not register process for wait: error code %lu",
4705 /* Don't close pi.hProcess here - the wait thread needs access to it */
4707 CloseHandle(pi.hThread);
4709 return pi.dwProcessId;
4715 * SubPostmasterMain -- Get the fork/exec'd process into a state equivalent
4716 * to what it would be if we'd simply forked on Unix, and then
4717 * dispatch to the appropriate place.
4719 * The first two command line arguments are expected to be "--forkFOO"
4720 * (where FOO indicates which postmaster child we are to become), and
4721 * the name of a variables file that we can read to load data that would
4722 * have been inherited by fork() on Unix. Remaining arguments go to the
4723 * subprocess FooMain() routine.
4726 SubPostmasterMain(int argc, char *argv[])
4730 /* In EXEC_BACKEND case we will not have inherited these settings */
4731 IsPostmasterEnvironment = true;
4732 whereToSendOutput = DestNone;
4734 /* Setup as postmaster child */
4735 InitPostmasterChild();
4737 /* Setup essential subsystems (to ensure elog() behaves sanely) */
4738 InitializeGUCOptions();
4740 /* Check we got appropriate args */
4742 elog(FATAL, "invalid subpostmaster invocation");
4744 /* Read in the variables file */
4745 memset(&port, 0, sizeof(Port));
4746 read_backend_variables(argv[2], &port);
4748 /* Close the postmaster's sockets (as soon as we know them) */
4749 ClosePostmasterPorts(strcmp(argv[1], "--forklog") == 0);
4752 * Set reference point for stack-depth checking
4757 * Set up memory area for GSS information. Mirrors the code in ConnCreate
4758 * for the non-exec case.
4760 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
4761 port.gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
4764 (errcode(ERRCODE_OUT_OF_MEMORY),
4765 errmsg("out of memory")));
4769 * If appropriate, physically re-attach to shared memory segment. We want
4770 * to do this before going any further to ensure that we can attach at the
4771 * same address the postmaster used. On the other hand, if we choose not
4772 * to re-attach, we may have other cleanup to do.
4774 * If testing EXEC_BACKEND on Linux, you should run this as root before
4775 * starting the postmaster:
4777 * echo 0 >/proc/sys/kernel/randomize_va_space
4779 * This prevents using randomized stack and code addresses that cause the
4780 * child process's memory map to be different from the parent's, making it
4781 * sometimes impossible to attach to shared memory at the desired address.
4782 * Return the setting to its old value (usually '1' or '2') when finished.
4784 if (strcmp(argv[1], "--forkbackend") == 0 ||
4785 strcmp(argv[1], "--forkavlauncher") == 0 ||
4786 strcmp(argv[1], "--forkavworker") == 0 ||
4787 strcmp(argv[1], "--forkboot") == 0 ||
4788 strncmp(argv[1], "--forkbgworker=", 15) == 0)
4789 PGSharedMemoryReAttach();
4791 PGSharedMemoryNoReAttach();
4793 /* autovacuum needs this set before calling InitProcess */
4794 if (strcmp(argv[1], "--forkavlauncher") == 0)
4795 AutovacuumLauncherIAm();
4796 if (strcmp(argv[1], "--forkavworker") == 0)
4797 AutovacuumWorkerIAm();
4800 * Start our win32 signal implementation. This has to be done after we
4801 * read the backend variables, because we need to pick up the signal pipe
4802 * from the parent process.
4805 pgwin32_signal_initialize();
4808 /* In EXEC_BACKEND case we will not have inherited these settings */
4810 PG_SETMASK(&BlockSig);
4812 /* Read in remaining GUC variables */
4813 read_nondefault_variables();
4816 * (re-)read control file, as it contains config. The postmaster will
4817 * already have read this, but this process doesn't know about that.
4819 LocalProcessControlFile(false);
4822 * Reload any libraries that were preloaded by the postmaster. Since we
4823 * exec'd this process, those libraries didn't come along with us; but we
4824 * should load them into all child processes to be consistent with the
4825 * non-EXEC_BACKEND behavior.
4827 process_shared_preload_libraries();
4829 /* Run backend or appropriate child */
4830 if (strcmp(argv[1], "--forkbackend") == 0)
4832 Assert(argc == 3); /* shouldn't be any more args */
4835 * Need to reinitialize the SSL library in the backend, since the
4836 * context structures contain function pointers and cannot be passed
4837 * through the parameter file.
4839 * If for some reason reload fails (maybe the user installed broken
4840 * key files), soldier on without SSL; that's better than all
4841 * connections becoming impossible.
4843 * XXX should we do this in all child processes? For the moment it's
4844 * enough to do it in backend children.
4849 if (secure_initialize(false) == 0)
4853 (errmsg("SSL configuration could not be loaded in child process")));
4858 * Perform additional initialization and collect startup packet.
4860 * We want to do this before InitProcess() for a couple of reasons: 1.
4861 * so that we aren't eating up a PGPROC slot while waiting on the
4862 * client. 2. so that if InitProcess() fails due to being out of
4863 * PGPROC slots, we have already initialized libpq and are able to
4864 * report the error to the client.
4866 BackendInitialize(&port);
4868 /* Restore basic shared memory pointers */
4869 InitShmemAccess(UsedShmemSegAddr);
4871 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
4874 /* Attach process to shared data structures */
4875 CreateSharedMemoryAndSemaphores(false, 0);
4877 /* And run the backend */
4878 BackendRun(&port); /* does not return */
4880 if (strcmp(argv[1], "--forkboot") == 0)
4882 /* Restore basic shared memory pointers */
4883 InitShmemAccess(UsedShmemSegAddr);
4885 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
4886 InitAuxiliaryProcess();
4888 /* Attach process to shared data structures */
4889 CreateSharedMemoryAndSemaphores(false, 0);
4891 AuxiliaryProcessMain(argc - 2, argv + 2); /* does not return */
4893 if (strcmp(argv[1], "--forkavlauncher") == 0)
4895 /* Restore basic shared memory pointers */
4896 InitShmemAccess(UsedShmemSegAddr);
4898 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
4901 /* Attach process to shared data structures */
4902 CreateSharedMemoryAndSemaphores(false, 0);
4904 AutoVacLauncherMain(argc - 2, argv + 2); /* does not return */
4906 if (strcmp(argv[1], "--forkavworker") == 0)
4908 /* Restore basic shared memory pointers */
4909 InitShmemAccess(UsedShmemSegAddr);
4911 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
4914 /* Attach process to shared data structures */
4915 CreateSharedMemoryAndSemaphores(false, 0);
4917 AutoVacWorkerMain(argc - 2, argv + 2); /* does not return */
4919 if (strncmp(argv[1], "--forkbgworker=", 15) == 0)
4923 /* do this as early as possible; in particular, before InitProcess() */
4924 IsBackgroundWorker = true;
4926 /* Restore basic shared memory pointers */
4927 InitShmemAccess(UsedShmemSegAddr);
4929 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
4932 /* Attach process to shared data structures */
4933 CreateSharedMemoryAndSemaphores(false, 0);
4935 /* Fetch MyBgworkerEntry from shared memory */
4936 shmem_slot = atoi(argv[1] + 15);
4937 MyBgworkerEntry = BackgroundWorkerEntry(shmem_slot);
4939 StartBackgroundWorker();
4941 if (strcmp(argv[1], "--forkarch") == 0)
4943 /* Do not want to attach to shared memory */
4945 PgArchiverMain(argc, argv); /* does not return */
4947 if (strcmp(argv[1], "--forkcol") == 0)
4949 /* Do not want to attach to shared memory */
4951 PgstatCollectorMain(argc, argv); /* does not return */
4953 if (strcmp(argv[1], "--forklog") == 0)
4955 /* Do not want to attach to shared memory */
4957 SysLoggerMain(argc, argv); /* does not return */
4960 abort(); /* shouldn't get here */
4962 #endif /* EXEC_BACKEND */
4966 * ExitPostmaster -- cleanup
4968 * Do NOT call exit() directly --- always go through here!
4971 ExitPostmaster(int status)
4973 #ifdef HAVE_PTHREAD_IS_THREADED_NP
4976 * There is no known cause for a postmaster to become multithreaded after
4977 * startup. Recheck to account for the possibility of unknown causes.
4978 * This message uses LOG level, because an unclean shutdown at this point
4979 * would usually not look much different from a clean shutdown.
4981 if (pthread_is_threaded_np() != 0)
4983 (errcode(ERRCODE_INTERNAL_ERROR),
4984 errmsg_internal("postmaster became multithreaded"),
4985 errdetail("Please report this to <pgsql-bugs@postgresql.org>.")));
4988 /* should cleanup shared memory and kill all backends */
4991 * Not sure of the semantics here. When the Postmaster dies, should the
4992 * backends all be killed? probably not.
4994 * MUST -- vadim 05-10-1999
5001 * sigusr1_handler - handle signal conditions from child processes
5004 sigusr1_handler(SIGNAL_ARGS)
5006 int save_errno = errno;
5008 PG_SETMASK(&BlockSig);
5010 /* Process background worker state change. */
5011 if (CheckPostmasterSignal(PMSIGNAL_BACKGROUND_WORKER_CHANGE))
5013 BackgroundWorkerStateChange();
5014 StartWorkerNeeded = true;
5018 * RECOVERY_STARTED and BEGIN_HOT_STANDBY signals are ignored in
5019 * unexpected states. If the startup process quickly starts up, completes
5020 * recovery, exits, we might process the death of the startup process
5021 * first. We don't want to go back to recovery in that case.
5023 if (CheckPostmasterSignal(PMSIGNAL_RECOVERY_STARTED) &&
5024 pmState == PM_STARTUP && Shutdown == NoShutdown)
5026 /* WAL redo has started. We're out of reinitialization. */
5028 Assert(AbortStartTime == 0);
5031 * Crank up the background tasks. It doesn't matter if this fails,
5032 * we'll just try again later.
5034 Assert(CheckpointerPID == 0);
5035 CheckpointerPID = StartCheckpointer();
5036 Assert(BgWriterPID == 0);
5037 BgWriterPID = StartBackgroundWriter();
5040 * Start the archiver if we're responsible for (re-)archiving received
5043 Assert(PgArchPID == 0);
5044 if (XLogArchivingAlways())
5045 PgArchPID = pgarch_start();
5048 * If we aren't planning to enter hot standby mode later, treat
5049 * RECOVERY_STARTED as meaning we're out of startup, and report status
5052 if (!EnableHotStandby)
5054 AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_STANDBY);
5056 sd_notify(0, "READY=1");
5060 pmState = PM_RECOVERY;
5062 if (CheckPostmasterSignal(PMSIGNAL_BEGIN_HOT_STANDBY) &&
5063 pmState == PM_RECOVERY && Shutdown == NoShutdown)
5066 * Likewise, start other special children as needed.
5068 Assert(PgStatPID == 0);
5069 PgStatPID = pgstat_start();
5072 (errmsg("database system is ready to accept read only connections")));
5075 AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_READY);
5077 sd_notify(0, "READY=1");
5080 pmState = PM_HOT_STANDBY;
5081 /* Some workers may be scheduled to start now */
5082 StartWorkerNeeded = true;
5085 if (StartWorkerNeeded || HaveCrashedWorker)
5086 maybe_start_bgworkers();
5088 if (CheckPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER) &&
5092 * Send SIGUSR1 to archiver process, to wake it up and begin archiving
5095 signal_child(PgArchPID, SIGUSR1);
5098 if (CheckPostmasterSignal(PMSIGNAL_ROTATE_LOGFILE) &&
5101 /* Tell syslogger to rotate logfile */
5102 signal_child(SysLoggerPID, SIGUSR1);
5105 if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER) &&
5106 Shutdown == NoShutdown)
5109 * Start one iteration of the autovacuum daemon, even if autovacuuming
5110 * is nominally not enabled. This is so we can have an active defense
5111 * against transaction ID wraparound. We set a flag for the main loop
5112 * to do it rather than trying to do it here --- this is because the
5113 * autovac process itself may send the signal, and we want to handle
5114 * that by launching another iteration as soon as the current one
5117 start_autovac_launcher = true;
5120 if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER) &&
5121 Shutdown == NoShutdown)
5123 /* The autovacuum launcher wants us to start a worker process. */
5124 StartAutovacuumWorker();
5127 if (CheckPostmasterSignal(PMSIGNAL_START_WALRECEIVER))
5129 /* Startup Process wants us to start the walreceiver process. */
5130 /* Start immediately if possible, else remember request for later. */
5131 WalReceiverRequested = true;
5132 MaybeStartWalReceiver();
5135 if (CheckPostmasterSignal(PMSIGNAL_ADVANCE_STATE_MACHINE) &&
5136 (pmState == PM_WAIT_BACKUP || pmState == PM_WAIT_BACKENDS))
5138 /* Advance postmaster's state machine */
5139 PostmasterStateMachine();
5142 if (CheckPromoteSignal() && StartupPID != 0 &&
5143 (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5144 pmState == PM_HOT_STANDBY || pmState == PM_WAIT_READONLY))
5146 /* Tell startup process to finish recovery */
5147 signal_child(StartupPID, SIGUSR2);
5150 PG_SETMASK(&UnBlockSig);
5156 * SIGTERM or SIGQUIT while processing startup packet.
5157 * Clean up and exit(1).
5159 * XXX: possible future improvement: try to send a message indicating
5160 * why we are disconnecting. Problem is to be sure we don't block while
5161 * doing so, nor mess up SSL initialization. In practice, if the client
5162 * has wedged here, it probably couldn't do anything with the message anyway.
5165 startup_die(SIGNAL_ARGS)
5171 * Dummy signal handler
5173 * We use this for signals that we don't actually use in the postmaster,
5174 * but we do use in backends. If we were to SIG_IGN such signals in the
5175 * postmaster, then a newly started backend might drop a signal that arrives
5176 * before it's able to reconfigure its signal processing. (See notes in
5180 dummy_handler(SIGNAL_ARGS)
5185 * Timeout while processing startup packet.
5186 * As for startup_die(), we clean up and exit(1).
5189 StartupPacketTimeoutHandler(void)
5196 * Generate a random cancel key.
5199 RandomCancelKey(int32 *cancel_key)
5201 #ifdef HAVE_STRONG_RANDOM
5202 return pg_strong_random((char *) cancel_key, sizeof(int32));
5206 * If built with --disable-strong-random, use plain old erand48.
5208 * We cannot use pg_backend_random() in postmaster, because it stores its
5209 * state in shared memory.
5211 static unsigned short seed[3];
5214 * Select a random seed at the time of first receiving a request.
5216 if (random_seed == 0)
5218 struct timeval random_stop_time;
5220 gettimeofday(&random_stop_time, NULL);
5222 seed[0] = (unsigned short) random_start_time.tv_usec;
5223 seed[1] = (unsigned short) (random_stop_time.tv_usec) ^ (random_start_time.tv_usec >> 16);
5224 seed[2] = (unsigned short) (random_stop_time.tv_usec >> 16);
5229 *cancel_key = pg_jrand48(seed);
5236 * Count up number of child processes of specified types (dead_end children
5237 * are always excluded).
5240 CountChildren(int target)
5245 dlist_foreach(iter, &BackendList)
5247 Backend *bp = dlist_container(Backend, elem, iter.cur);
5253 * Since target == BACKEND_TYPE_ALL is the most common case, we test
5254 * it first and avoid touching shared memory for every child.
5256 if (target != BACKEND_TYPE_ALL)
5259 * Assign bkend_type for any recently announced WAL Sender
5262 if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
5263 IsPostmasterChildWalSender(bp->child_slot))
5264 bp->bkend_type = BACKEND_TYPE_WALSND;
5266 if (!(target & bp->bkend_type))
5277 * StartChildProcess -- start an auxiliary process for the postmaster
5279 * "type" determines what kind of child will be started. All child types
5280 * initially go to AuxiliaryProcessMain, which will handle common setup.
5282 * Return value of StartChildProcess is subprocess' PID, or 0 if failed
5283 * to start subprocess.
5286 StartChildProcess(AuxProcType type)
5294 * Set up command-line arguments for subprocess
5296 av[ac++] = "postgres";
5299 av[ac++] = "--forkboot";
5300 av[ac++] = NULL; /* filled in by postmaster_forkexec */
5303 snprintf(typebuf, sizeof(typebuf), "-x%d", type);
5307 Assert(ac < lengthof(av));
5310 pid = postmaster_forkexec(ac, av);
5311 #else /* !EXEC_BACKEND */
5312 pid = fork_process();
5314 if (pid == 0) /* child */
5316 InitPostmasterChild();
5318 /* Close the postmaster's sockets */
5319 ClosePostmasterPorts(false);
5321 /* Release postmaster's working memory context */
5322 MemoryContextSwitchTo(TopMemoryContext);
5323 MemoryContextDelete(PostmasterContext);
5324 PostmasterContext = NULL;
5326 AuxiliaryProcessMain(ac, av);
5329 #endif /* EXEC_BACKEND */
5333 /* in parent, fork failed */
5334 int save_errno = errno;
5339 case StartupProcess:
5341 (errmsg("could not fork startup process: %m")));
5343 case BgWriterProcess:
5345 (errmsg("could not fork background writer process: %m")));
5347 case CheckpointerProcess:
5349 (errmsg("could not fork checkpointer process: %m")));
5351 case WalWriterProcess:
5353 (errmsg("could not fork WAL writer process: %m")));
5355 case WalReceiverProcess:
5357 (errmsg("could not fork WAL receiver process: %m")));
5361 (errmsg("could not fork process: %m")));
5366 * fork failure is fatal during startup, but there's no need to choke
5367 * immediately if starting other child types fails.
5369 if (type == StartupProcess)
5375 * in parent, successful fork
5381 * StartAutovacuumWorker
5382 * Start an autovac worker process.
5384 * This function is here because it enters the resulting PID into the
5385 * postmaster's private backends list.
5387 * NB -- this code very roughly matches BackendStartup.
5390 StartAutovacuumWorker(void)
5395 * If not in condition to run a process, don't try, but handle it like a
5396 * fork failure. This does not normally happen, since the signal is only
5397 * supposed to be sent by autovacuum launcher when it's OK to do it, but
5398 * we have to check to avoid race-condition problems during DB state
5401 if (canAcceptConnections() == CAC_OK)
5404 * Compute the cancel key that will be assigned to this session. We
5405 * probably don't need cancel keys for autovac workers, but we'd
5406 * better have something random in the field to prevent unfriendly
5407 * people from sending cancels to them.
5409 if (!RandomCancelKey(&MyCancelKey))
5412 (errcode(ERRCODE_INTERNAL_ERROR),
5413 errmsg("could not generate random cancel key")));
5417 bn = (Backend *) malloc(sizeof(Backend));
5420 bn->cancel_key = MyCancelKey;
5422 /* Autovac workers are not dead_end and need a child slot */
5423 bn->dead_end = false;
5424 bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
5425 bn->bgworker_notify = false;
5427 bn->pid = StartAutoVacWorker();
5430 bn->bkend_type = BACKEND_TYPE_AUTOVAC;
5431 dlist_push_head(&BackendList, &bn->elem);
5433 ShmemBackendArrayAdd(bn);
5440 * fork failed, fall through to report -- actual error message was
5441 * logged by StartAutoVacWorker
5443 (void) ReleasePostmasterChildSlot(bn->child_slot);
5448 (errcode(ERRCODE_OUT_OF_MEMORY),
5449 errmsg("out of memory")));
5453 * Report the failure to the launcher, if it's running. (If it's not, we
5454 * might not even be connected to shared memory, so don't try to call
5455 * AutoVacWorkerFailed.) Note that we also need to signal it so that it
5456 * responds to the condition, but we don't do that here, instead waiting
5457 * for ServerLoop to do it. This way we avoid a ping-pong signalling in
5458 * quick succession between the autovac launcher and postmaster in case
5461 if (AutoVacPID != 0)
5463 AutoVacWorkerFailed();
5464 avlauncher_needs_signal = true;
5469 * MaybeStartWalReceiver
5470 * Start the WAL receiver process, if not running and our state allows.
5473 MaybeStartWalReceiver(void)
5475 if (WalReceiverPID == 0 &&
5476 (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5477 pmState == PM_HOT_STANDBY || pmState == PM_WAIT_READONLY) &&
5478 Shutdown == NoShutdown)
5480 WalReceiverPID = StartWalReceiver();
5481 WalReceiverRequested = false;
5487 * Create the opts file
5490 CreateOptsFile(int argc, char *argv[], char *fullprogname)
5495 #define OPTS_FILE "postmaster.opts"
5497 if ((fp = fopen(OPTS_FILE, "w")) == NULL)
5499 elog(LOG, "could not create file \"%s\": %m", OPTS_FILE);
5503 fprintf(fp, "%s", fullprogname);
5504 for (i = 1; i < argc; i++)
5505 fprintf(fp, " \"%s\"", argv[i]);
5510 elog(LOG, "could not write file \"%s\": %m", OPTS_FILE);
5519 * MaxLivePostmasterChildren
5521 * This reports the number of entries needed in per-child-process arrays
5522 * (the PMChildFlags array, and if EXEC_BACKEND the ShmemBackendArray).
5523 * These arrays include regular backends, autovac workers, walsenders
5524 * and background workers, but not special children nor dead_end children.
5525 * This allows the arrays to have a fixed maximum size, to wit the same
5526 * too-many-children limit enforced by canAcceptConnections(). The exact value
5527 * isn't too critical as long as it's more than MaxBackends.
5530 MaxLivePostmasterChildren(void)
5532 return 2 * (MaxConnections + autovacuum_max_workers + 1 +
5533 max_worker_processes);
5537 * Connect background worker to a database.
5540 BackgroundWorkerInitializeConnection(char *dbname, char *username)
5542 BackgroundWorker *worker = MyBgworkerEntry;
5544 /* XXX is this the right errcode? */
5545 if (!(worker->bgw_flags & BGWORKER_BACKEND_DATABASE_CONNECTION))
5547 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5548 errmsg("database connection requirement not indicated during registration")));
5550 InitPostgres(dbname, InvalidOid, username, InvalidOid, NULL);
5552 /* it had better not gotten out of "init" mode yet */
5553 if (!IsInitProcessingMode())
5555 (errmsg("invalid processing mode in background worker")));
5556 SetProcessingMode(NormalProcessing);
5560 * Connect background worker to a database using OIDs.
5563 BackgroundWorkerInitializeConnectionByOid(Oid dboid, Oid useroid)
5565 BackgroundWorker *worker = MyBgworkerEntry;
5567 /* XXX is this the right errcode? */
5568 if (!(worker->bgw_flags & BGWORKER_BACKEND_DATABASE_CONNECTION))
5570 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5571 errmsg("database connection requirement not indicated during registration")));
5573 InitPostgres(NULL, dboid, NULL, useroid, NULL);
5575 /* it had better not gotten out of "init" mode yet */
5576 if (!IsInitProcessingMode())
5578 (errmsg("invalid processing mode in background worker")));
5579 SetProcessingMode(NormalProcessing);
5583 * Block/unblock signals in a background worker
5586 BackgroundWorkerBlockSignals(void)
5588 PG_SETMASK(&BlockSig);
5592 BackgroundWorkerUnblockSignals(void)
5594 PG_SETMASK(&UnBlockSig);
5599 bgworker_forkexec(int shmem_slot)
5603 char forkav[MAXPGPATH];
5605 snprintf(forkav, MAXPGPATH, "--forkbgworker=%d", shmem_slot);
5607 av[ac++] = "postgres";
5609 av[ac++] = NULL; /* filled in by postmaster_forkexec */
5612 Assert(ac < lengthof(av));
5614 return postmaster_forkexec(ac, av);
5619 * Start a new bgworker.
5620 * Starting time conditions must have been checked already.
5622 * Returns true on success, false on failure.
5623 * In either case, update the RegisteredBgWorker's state appropriately.
5625 * This code is heavily based on autovacuum.c, q.v.
5628 do_start_bgworker(RegisteredBgWorker *rw)
5632 Assert(rw->rw_pid == 0);
5635 * Allocate and assign the Backend element. Note we must do this before
5636 * forking, so that we can handle out of memory properly.
5638 * Treat failure as though the worker had crashed. That way, the
5639 * postmaster will wait a bit before attempting to start it again; if it
5640 * tried again right away, most likely it'd find itself repeating the
5641 * out-of-memory or fork failure condition.
5643 if (!assign_backendlist_entry(rw))
5645 rw->rw_crashed_at = GetCurrentTimestamp();
5650 (errmsg("starting background worker process \"%s\"",
5651 rw->rw_worker.bgw_name)));
5654 switch ((worker_pid = bgworker_forkexec(rw->rw_shmem_slot)))
5656 switch ((worker_pid = fork_process()))
5660 /* in postmaster, fork failed ... */
5662 (errmsg("could not fork worker process: %m")));
5663 /* undo what assign_backendlist_entry did */
5664 ReleasePostmasterChildSlot(rw->rw_child_slot);
5665 rw->rw_child_slot = 0;
5666 free(rw->rw_backend);
5667 rw->rw_backend = NULL;
5668 /* mark entry as crashed, so we'll try again later */
5669 rw->rw_crashed_at = GetCurrentTimestamp();
5672 #ifndef EXEC_BACKEND
5674 /* in postmaster child ... */
5675 InitPostmasterChild();
5677 /* Close the postmaster's sockets */
5678 ClosePostmasterPorts(false);
5681 * Before blowing away PostmasterContext, save this bgworker's
5682 * data where it can find it.
5684 MyBgworkerEntry = (BackgroundWorker *)
5685 MemoryContextAlloc(TopMemoryContext, sizeof(BackgroundWorker));
5686 memcpy(MyBgworkerEntry, &rw->rw_worker, sizeof(BackgroundWorker));
5688 /* Release postmaster's working memory context */
5689 MemoryContextSwitchTo(TopMemoryContext);
5690 MemoryContextDelete(PostmasterContext);
5691 PostmasterContext = NULL;
5693 StartBackgroundWorker();
5695 exit(1); /* should not get here */
5699 /* in postmaster, fork successful ... */
5700 rw->rw_pid = worker_pid;
5701 rw->rw_backend->pid = rw->rw_pid;
5702 ReportBackgroundWorkerPID(rw);
5703 /* add new worker to lists of backends */
5704 dlist_push_head(&BackendList, &rw->rw_backend->elem);
5706 ShmemBackendArrayAdd(rw->rw_backend);
5715 * Does the current postmaster state require starting a worker with the
5716 * specified start_time?
5719 bgworker_should_start_now(BgWorkerStartTime start_time)
5723 case PM_NO_CHILDREN:
5724 case PM_WAIT_DEAD_END:
5727 case PM_WAIT_BACKENDS:
5728 case PM_WAIT_READONLY:
5729 case PM_WAIT_BACKUP:
5733 if (start_time == BgWorkerStart_RecoveryFinished)
5737 case PM_HOT_STANDBY:
5738 if (start_time == BgWorkerStart_ConsistentState)
5745 if (start_time == BgWorkerStart_PostmasterStart)
5755 * Allocate the Backend struct for a connected background worker, but don't
5756 * add it to the list of backends just yet.
5758 * On failure, return false without changing any worker state.
5760 * Some info from the Backend is copied into the passed rw.
5763 assign_backendlist_entry(RegisteredBgWorker *rw)
5768 * Compute the cancel key that will be assigned to this session. We
5769 * probably don't need cancel keys for background workers, but we'd better
5770 * have something random in the field to prevent unfriendly people from
5771 * sending cancels to them.
5773 if (!RandomCancelKey(&MyCancelKey))
5776 (errcode(ERRCODE_INTERNAL_ERROR),
5777 errmsg("could not generate random cancel key")));
5781 bn = malloc(sizeof(Backend));
5785 (errcode(ERRCODE_OUT_OF_MEMORY),
5786 errmsg("out of memory")));
5790 bn->cancel_key = MyCancelKey;
5791 bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
5792 bn->bkend_type = BACKEND_TYPE_BGWORKER;
5793 bn->dead_end = false;
5794 bn->bgworker_notify = false;
5796 rw->rw_backend = bn;
5797 rw->rw_child_slot = bn->child_slot;
5803 * If the time is right, start background worker(s).
5805 * As a side effect, the bgworker control variables are set or reset
5806 * depending on whether more workers may need to be started.
5808 * We limit the number of workers started per call, to avoid consuming the
5809 * postmaster's attention for too long when many such requests are pending.
5810 * As long as StartWorkerNeeded is true, ServerLoop will not block and will
5811 * call this function again after dealing with any other issues.
5814 maybe_start_bgworkers(void)
5816 #define MAX_BGWORKERS_TO_LAUNCH 100
5817 int num_launched = 0;
5818 TimestampTz now = 0;
5819 slist_mutable_iter iter;
5822 * During crash recovery, we have no need to be called until the state
5823 * transition out of recovery.
5827 StartWorkerNeeded = false;
5828 HaveCrashedWorker = false;
5832 /* Don't need to be called again unless we find a reason for it below */
5833 StartWorkerNeeded = false;
5834 HaveCrashedWorker = false;
5836 slist_foreach_modify(iter, &BackgroundWorkerList)
5838 RegisteredBgWorker *rw;
5840 rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
5842 /* ignore if already running */
5843 if (rw->rw_pid != 0)
5846 /* if marked for death, clean up and remove from list */
5847 if (rw->rw_terminate)
5849 ForgetBackgroundWorker(&iter);
5854 * If this worker has crashed previously, maybe it needs to be
5855 * restarted (unless on registration it specified it doesn't want to
5856 * be restarted at all). Check how long ago did a crash last happen.
5857 * If the last crash is too recent, don't start it right away; let it
5858 * be restarted once enough time has passed.
5860 if (rw->rw_crashed_at != 0)
5862 if (rw->rw_worker.bgw_restart_time == BGW_NEVER_RESTART)
5864 ForgetBackgroundWorker(&iter);
5868 /* read system time only when needed */
5870 now = GetCurrentTimestamp();
5872 if (!TimestampDifferenceExceeds(rw->rw_crashed_at, now,
5873 rw->rw_worker.bgw_restart_time * 1000))
5875 /* Set flag to remember that we have workers to start later */
5876 HaveCrashedWorker = true;
5881 if (bgworker_should_start_now(rw->rw_worker.bgw_start_time))
5883 /* reset crash time before trying to start worker */
5884 rw->rw_crashed_at = 0;
5887 * Try to start the worker.
5889 * On failure, give up processing workers for now, but set
5890 * StartWorkerNeeded so we'll come back here on the next iteration
5891 * of ServerLoop to try again. (We don't want to wait, because
5892 * there might be additional ready-to-run workers.) We could set
5893 * HaveCrashedWorker as well, since this worker is now marked
5894 * crashed, but there's no need because the next run of this
5895 * function will do that.
5897 if (!do_start_bgworker(rw))
5899 StartWorkerNeeded = true;
5904 * If we've launched as many workers as allowed, quit, but have
5905 * ServerLoop call us again to look for additional ready-to-run
5906 * workers. There might not be any, but we'll find out the next
5909 if (++num_launched >= MAX_BGWORKERS_TO_LAUNCH)
5911 StartWorkerNeeded = true;
5919 * When a backend asks to be notified about worker state changes, we
5920 * set a flag in its backend entry. The background worker machinery needs
5921 * to know when such backends exit.
5924 PostmasterMarkPIDForWorkerNotify(int pid)
5929 dlist_foreach(iter, &BackendList)
5931 bp = dlist_container(Backend, elem, iter.cur);
5934 bp->bgworker_notify = true;
5944 * The following need to be available to the save/restore_backend_variables
5945 * functions. They are marked NON_EXEC_STATIC in their home modules.
5947 extern slock_t *ShmemLock;
5948 extern slock_t *ProcStructLock;
5949 extern PGPROC *AuxiliaryProcs;
5950 extern PMSignalData *PMSignalState;
5951 extern pgsocket pgStatSock;
5952 extern pg_time_t first_syslogger_file_time;
5955 #define write_inheritable_socket(dest, src, childpid) ((*(dest) = (src)), true)
5956 #define read_inheritable_socket(dest, src) (*(dest) = *(src))
5958 static bool write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE child);
5959 static bool write_inheritable_socket(InheritableSocket *dest, SOCKET src,
5961 static void read_inheritable_socket(SOCKET *dest, InheritableSocket *src);
5965 /* Save critical backend variables into the BackendParameters struct */
5968 save_backend_variables(BackendParameters *param, Port *port)
5971 save_backend_variables(BackendParameters *param, Port *port,
5972 HANDLE childProcess, pid_t childPid)
5975 memcpy(¶m->port, port, sizeof(Port));
5976 if (!write_inheritable_socket(¶m->portsocket, port->sock, childPid))
5979 strlcpy(param->DataDir, DataDir, MAXPGPATH);
5981 memcpy(¶m->ListenSocket, &ListenSocket, sizeof(ListenSocket));
5983 param->MyCancelKey = MyCancelKey;
5984 param->MyPMChildSlot = MyPMChildSlot;
5986 param->UsedShmemSegID = UsedShmemSegID;
5987 param->UsedShmemSegAddr = UsedShmemSegAddr;
5989 param->ShmemLock = ShmemLock;
5990 param->ShmemVariableCache = ShmemVariableCache;
5991 param->ShmemBackendArray = ShmemBackendArray;
5993 #ifndef HAVE_SPINLOCKS
5994 param->SpinlockSemaArray = SpinlockSemaArray;
5996 param->NamedLWLockTrancheRequests = NamedLWLockTrancheRequests;
5997 param->NamedLWLockTrancheArray = NamedLWLockTrancheArray;
5998 param->MainLWLockArray = MainLWLockArray;
5999 param->ProcStructLock = ProcStructLock;
6000 param->ProcGlobal = ProcGlobal;
6001 param->AuxiliaryProcs = AuxiliaryProcs;
6002 param->PreparedXactProcs = PreparedXactProcs;
6003 param->PMSignalState = PMSignalState;
6004 if (!write_inheritable_socket(¶m->pgStatSock, pgStatSock, childPid))
6007 param->PostmasterPid = PostmasterPid;
6008 param->PgStartTime = PgStartTime;
6009 param->PgReloadTime = PgReloadTime;
6010 param->first_syslogger_file_time = first_syslogger_file_time;
6012 param->redirection_done = redirection_done;
6013 param->IsBinaryUpgrade = IsBinaryUpgrade;
6014 param->max_safe_fds = max_safe_fds;
6016 param->MaxBackends = MaxBackends;
6019 param->PostmasterHandle = PostmasterHandle;
6020 if (!write_duplicated_handle(¶m->initial_signal_pipe,
6021 pgwin32_create_signal_listener(childPid),
6025 memcpy(¶m->postmaster_alive_fds, &postmaster_alive_fds,
6026 sizeof(postmaster_alive_fds));
6029 memcpy(¶m->syslogPipe, &syslogPipe, sizeof(syslogPipe));
6031 strlcpy(param->my_exec_path, my_exec_path, MAXPGPATH);
6033 strlcpy(param->pkglib_path, pkglib_path, MAXPGPATH);
6035 strlcpy(param->ExtraOptions, ExtraOptions, MAXPGPATH);
6043 * Duplicate a handle for usage in a child process, and write the child
6044 * process instance of the handle to the parameter file.
6047 write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE childProcess)
6049 HANDLE hChild = INVALID_HANDLE_VALUE;
6051 if (!DuplicateHandle(GetCurrentProcess(),
6057 DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS))
6060 (errmsg_internal("could not duplicate handle to be written to backend parameter file: error code %lu",
6070 * Duplicate a socket for usage in a child process, and write the resulting
6071 * structure to the parameter file.
6072 * This is required because a number of LSPs (Layered Service Providers) very
6073 * common on Windows (antivirus, firewalls, download managers etc) break
6074 * straight socket inheritance.
6077 write_inheritable_socket(InheritableSocket *dest, SOCKET src, pid_t childpid)
6079 dest->origsocket = src;
6080 if (src != 0 && src != PGINVALID_SOCKET)
6083 if (WSADuplicateSocket(src, childpid, &dest->wsainfo) != 0)
6086 (errmsg("could not duplicate socket %d for use in backend: error code %d",
6087 (int) src, WSAGetLastError())));
6095 * Read a duplicate socket structure back, and get the socket descriptor.
6098 read_inheritable_socket(SOCKET *dest, InheritableSocket *src)
6102 if (src->origsocket == PGINVALID_SOCKET || src->origsocket == 0)
6104 /* Not a real socket! */
6105 *dest = src->origsocket;
6109 /* Actual socket, so create from structure */
6110 s = WSASocket(FROM_PROTOCOL_INFO,
6116 if (s == INVALID_SOCKET)
6118 write_stderr("could not create inherited socket: error code %d\n",
6125 * To make sure we don't get two references to the same socket, close
6126 * the original one. (This would happen when inheritance actually
6129 closesocket(src->origsocket);
6135 read_backend_variables(char *id, Port *port)
6137 BackendParameters param;
6140 /* Non-win32 implementation reads from file */
6144 fp = AllocateFile(id, PG_BINARY_R);
6147 write_stderr("could not open backend variables file \"%s\": %s\n",
6148 id, strerror(errno));
6152 if (fread(¶m, sizeof(param), 1, fp) != 1)
6154 write_stderr("could not read from backend variables file \"%s\": %s\n",
6155 id, strerror(errno));
6161 if (unlink(id) != 0)
6163 write_stderr("could not remove file \"%s\": %s\n",
6164 id, strerror(errno));
6168 /* Win32 version uses mapped file */
6170 BackendParameters *paramp;
6173 paramHandle = (HANDLE) _atoi64(id);
6175 paramHandle = (HANDLE) atol(id);
6177 paramp = MapViewOfFile(paramHandle, FILE_MAP_READ, 0, 0, 0);
6180 write_stderr("could not map view of backend variables: error code %lu\n",
6185 memcpy(¶m, paramp, sizeof(BackendParameters));
6187 if (!UnmapViewOfFile(paramp))
6189 write_stderr("could not unmap view of backend variables: error code %lu\n",
6194 if (!CloseHandle(paramHandle))
6196 write_stderr("could not close handle to backend parameter variables: error code %lu\n",
6202 restore_backend_variables(¶m, port);
6205 /* Restore critical backend variables from the BackendParameters struct */
6207 restore_backend_variables(BackendParameters *param, Port *port)
6209 memcpy(port, ¶m->port, sizeof(Port));
6210 read_inheritable_socket(&port->sock, ¶m->portsocket);
6212 SetDataDir(param->DataDir);
6214 memcpy(&ListenSocket, ¶m->ListenSocket, sizeof(ListenSocket));
6216 MyCancelKey = param->MyCancelKey;
6217 MyPMChildSlot = param->MyPMChildSlot;
6219 UsedShmemSegID = param->UsedShmemSegID;
6220 UsedShmemSegAddr = param->UsedShmemSegAddr;
6222 ShmemLock = param->ShmemLock;
6223 ShmemVariableCache = param->ShmemVariableCache;
6224 ShmemBackendArray = param->ShmemBackendArray;
6226 #ifndef HAVE_SPINLOCKS
6227 SpinlockSemaArray = param->SpinlockSemaArray;
6229 NamedLWLockTrancheRequests = param->NamedLWLockTrancheRequests;
6230 NamedLWLockTrancheArray = param->NamedLWLockTrancheArray;
6231 MainLWLockArray = param->MainLWLockArray;
6232 ProcStructLock = param->ProcStructLock;
6233 ProcGlobal = param->ProcGlobal;
6234 AuxiliaryProcs = param->AuxiliaryProcs;
6235 PreparedXactProcs = param->PreparedXactProcs;
6236 PMSignalState = param->PMSignalState;
6237 read_inheritable_socket(&pgStatSock, ¶m->pgStatSock);
6239 PostmasterPid = param->PostmasterPid;
6240 PgStartTime = param->PgStartTime;
6241 PgReloadTime = param->PgReloadTime;
6242 first_syslogger_file_time = param->first_syslogger_file_time;
6244 redirection_done = param->redirection_done;
6245 IsBinaryUpgrade = param->IsBinaryUpgrade;
6246 max_safe_fds = param->max_safe_fds;
6248 MaxBackends = param->MaxBackends;
6251 PostmasterHandle = param->PostmasterHandle;
6252 pgwin32_initial_signal_pipe = param->initial_signal_pipe;
6254 memcpy(&postmaster_alive_fds, ¶m->postmaster_alive_fds,
6255 sizeof(postmaster_alive_fds));
6258 memcpy(&syslogPipe, ¶m->syslogPipe, sizeof(syslogPipe));
6260 strlcpy(my_exec_path, param->my_exec_path, MAXPGPATH);
6262 strlcpy(pkglib_path, param->pkglib_path, MAXPGPATH);
6264 strlcpy(ExtraOptions, param->ExtraOptions, MAXPGPATH);
6269 ShmemBackendArraySize(void)
6271 return mul_size(MaxLivePostmasterChildren(), sizeof(Backend));
6275 ShmemBackendArrayAllocation(void)
6277 Size size = ShmemBackendArraySize();
6279 ShmemBackendArray = (Backend *) ShmemAlloc(size);
6280 /* Mark all slots as empty */
6281 memset(ShmemBackendArray, 0, size);
6285 ShmemBackendArrayAdd(Backend *bn)
6287 /* The array slot corresponding to my PMChildSlot should be free */
6288 int i = bn->child_slot - 1;
6290 Assert(ShmemBackendArray[i].pid == 0);
6291 ShmemBackendArray[i] = *bn;
6295 ShmemBackendArrayRemove(Backend *bn)
6297 int i = bn->child_slot - 1;
6299 Assert(ShmemBackendArray[i].pid == bn->pid);
6300 /* Mark the slot as empty */
6301 ShmemBackendArray[i].pid = 0;
6303 #endif /* EXEC_BACKEND */
6309 * Subset implementation of waitpid() for Windows. We assume pid is -1
6310 * (that is, check all child processes) and options is WNOHANG (don't wait).
6313 waitpid(pid_t pid, int *exitstatus, int options)
6320 * Check if there are any dead children. If there are, return the pid of
6321 * the first one that died.
6323 if (GetQueuedCompletionStatus(win32ChildQueue, &dwd, &key, &ovl, 0))
6325 *exitstatus = (int) key;
6333 * Note! Code below executes on a thread pool! All operations must
6334 * be thread safe! Note that elog() and friends must *not* be used.
6337 pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
6339 win32_deadchild_waitinfo *childinfo = (win32_deadchild_waitinfo *) lpParameter;
6342 if (TimerOrWaitFired)
6343 return; /* timeout. Should never happen, since we use
6344 * INFINITE as timeout value. */
6347 * Remove handle from wait - required even though it's set to wait only
6350 UnregisterWaitEx(childinfo->waitHandle, NULL);
6352 if (!GetExitCodeProcess(childinfo->procHandle, &exitcode))
6355 * Should never happen. Inform user and set a fixed exitcode.
6357 write_stderr("could not read exit code for process\n");
6361 if (!PostQueuedCompletionStatus(win32ChildQueue, childinfo->procId, (ULONG_PTR) exitcode, NULL))
6362 write_stderr("could not post child completion status\n");
6365 * Handle is per-process, so we close it here instead of in the
6366 * originating thread
6368 CloseHandle(childinfo->procHandle);
6371 * Free struct that was allocated before the call to
6372 * RegisterWaitForSingleObject()
6376 /* Queue SIGCHLD signal */
6377 pg_queue_signal(SIGCHLD);
6382 * Initialize one and only handle for monitoring postmaster death.
6384 * Called once in the postmaster, so that child processes can subsequently
6385 * monitor if their parent is dead.
6388 InitPostmasterDeathWatchHandle(void)
6393 * Create a pipe. Postmaster holds the write end of the pipe open
6394 * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
6395 * the read file descriptor to select() to wake up in case postmaster
6396 * dies, or check for postmaster death with a (read() == 0). Children must
6397 * close the write end as soon as possible after forking, because EOF
6398 * won't be signaled in the read end until all processes have closed the
6399 * write fd. That is taken care of in ClosePostmasterPorts().
6401 Assert(MyProcPid == PostmasterPid);
6402 if (pipe(postmaster_alive_fds) < 0)
6404 (errcode_for_file_access(),
6405 errmsg_internal("could not create pipe to monitor postmaster death: %m")));
6408 * Set O_NONBLOCK to allow testing for the fd's presence with a read()
6411 if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
6413 (errcode_for_socket_access(),
6414 errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
6418 * On Windows, we use a process handle for the same purpose.
6420 if (DuplicateHandle(GetCurrentProcess(),
6421 GetCurrentProcess(),
6422 GetCurrentProcess(),
6426 DUPLICATE_SAME_ACCESS) == 0)
6428 (errmsg_internal("could not duplicate postmaster handle: error code %lu",