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-2009, PostgreSQL Global Development Group
36 * Portions Copyright (c) 1994, Regents of the University of California
40 * $PostgreSQL: pgsql/src/backend/postmaster/postmaster.c,v 1.596 2009/09/08 17:08:36 tgl Exp $
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(). In particular, don't use
62 * write_stderr() for anything that occurs after pmdaemonize.
64 *-------------------------------------------------------------------------
75 #include <sys/socket.h>
77 #include <sys/param.h>
78 #include <netinet/in.h>
79 #include <arpa/inet.h>
83 #ifdef HAVE_SYS_SELECT_H
84 #include <sys/select.h>
95 #include "access/transam.h"
96 #include "access/xlog.h"
97 #include "bootstrap/bootstrap.h"
98 #include "catalog/pg_control.h"
99 #include "lib/dllist.h"
100 #include "libpq/auth.h"
101 #include "libpq/ip.h"
102 #include "libpq/libpq.h"
103 #include "libpq/pqsignal.h"
104 #include "miscadmin.h"
106 #include "postmaster/autovacuum.h"
107 #include "postmaster/fork_process.h"
108 #include "postmaster/pgarch.h"
109 #include "postmaster/postmaster.h"
110 #include "postmaster/syslogger.h"
111 #include "storage/fd.h"
112 #include "storage/ipc.h"
113 #include "storage/pg_shmem.h"
114 #include "storage/pmsignal.h"
115 #include "storage/proc.h"
116 #include "tcop/tcopprot.h"
117 #include "utils/builtins.h"
118 #include "utils/datetime.h"
119 #include "utils/memutils.h"
120 #include "utils/ps_status.h"
123 #include "storage/spin.h"
128 * List of active backends (or child processes anyway; we don't actually
129 * know whether a given child has become a backend or is still in the
130 * authorization phase). This is used mainly to keep track of how many
131 * children we have and send them appropriate signals when necessary.
133 * "Special" children such as the startup, bgwriter and autovacuum launcher
134 * tasks are not in this list. Autovacuum worker processes are in it.
135 * Also, "dead_end" children are in it: these are children launched just
136 * for the purpose of sending a friendly rejection message to a would-be
137 * client. We must track them because they are attached to shared memory,
138 * but we know they will never become live backends. dead_end children are
139 * not assigned a PMChildSlot.
143 pid_t pid; /* process id of backend */
144 long cancel_key; /* cancel key for cancels for this backend */
145 int child_slot; /* PMChildSlot for this backend, if any */
146 bool is_autovacuum; /* is it an autovacuum process? */
147 bool dead_end; /* is it going to send an error and quit? */
148 Dlelem elem; /* list link in BackendList */
151 static Dllist *BackendList;
154 static Backend *ShmemBackendArray;
157 /* The socket number we are listening for connections on */
160 char *ListenAddresses;
163 * ReservedBackends is the number of backends reserved for superuser use.
164 * This number is taken out of the pool size given by MaxBackends so
165 * number of backend slots available to non-superusers is
166 * (MaxBackends - ReservedBackends). Note what this really means is
167 * "if there are <= ReservedBackends connections available, only superusers
168 * can make new connections" --- pre-existing superuser connections don't
169 * count against the limit.
171 int ReservedBackends;
173 /* The socket(s) we're listening to. */
175 static int ListenSocket[MAXLISTEN];
178 * Set by the -o option
180 static char ExtraOptions[MAXPGPATH];
183 * These globals control the behavior of the postmaster in case some
184 * backend dumps core. Normally, it kills all peers of the dead backend
185 * and reinitializes shared memory. By specifying -s or -n, we can have
186 * the postmaster stop (rather than kill) peers and not reinitialize
187 * shared data structures. (Reinit is currently dead code, though.)
189 static bool Reinit = true;
190 static int SendStop = false;
192 /* still more option variables */
193 bool EnableSSL = false;
194 bool SilentMode = false; /* silent_mode */
196 int PreAuthDelay = 0;
197 int AuthenticationTimeout = 60;
199 bool log_hostname; /* for ps display and logging */
200 bool Log_connections = false;
201 bool Db_user_namespace = false;
203 bool enable_bonjour = false;
206 /* PIDs of special child processes; 0 when not running */
207 static pid_t StartupPID = 0,
215 /* Startup/shutdown state */
217 #define SmartShutdown 1
218 #define FastShutdown 2
220 static int Shutdown = NoShutdown;
222 static bool FatalError = false; /* T if recovering from backend crash */
223 static bool RecoveryError = false; /* T if WAL recovery failed */
226 * We use a simple state machine to control startup, shutdown, and
227 * crash recovery (which is rather like shutdown followed by startup).
229 * After doing all the postmaster initialization work, we enter PM_STARTUP
230 * state and the startup process is launched. The startup process begins by
231 * reading the control file and other preliminary initialization steps.
232 * In a normal startup, or after crash recovery, the startup process exits
233 * with exit code 0 and we switch to PM_RUN state. However, archive recovery
234 * is handled specially since it takes much longer and we would like to support
235 * hot standby during archive recovery.
237 * When the startup process is ready to start archive recovery, it signals the
238 * postmaster, and we switch to PM_RECOVERY state. The background writer is
239 * launched, while the startup process continues applying WAL.
240 * After reaching a consistent point in WAL redo, startup process signals
241 * us again, and we switch to PM_RECOVERY_CONSISTENT state. There's currently
242 * no difference between PM_RECOVERY and PM_RECOVERY_CONSISTENT, but we
243 * could start accepting connections to perform read-only queries at this
244 * point, if we had the infrastructure to do that.
245 * When archive recovery is finished, the startup process exits with exit
246 * code 0 and we switch to PM_RUN state.
248 * Normal child backends can only be launched when we are in PM_RUN state.
249 * (We also allow it in PM_WAIT_BACKUP state, but only for superusers.)
250 * In other states we handle connection requests by launching "dead_end"
251 * child processes, which will simply send the client an error message and
252 * quit. (We track these in the BackendList so that we can know when they
253 * are all gone; this is important because they're still connected to shared
254 * memory, and would interfere with an attempt to destroy the shmem segment,
255 * possibly leading to SHMALL failure when we try to make a new one.)
256 * In PM_WAIT_DEAD_END state we are waiting for all the dead_end children
257 * to drain out of the system, and therefore stop accepting connection
258 * requests at all until the last existing child has quit (which hopefully
259 * will not be very long).
261 * Notice that this state variable does not distinguish *why* we entered
262 * states later than PM_RUN --- Shutdown and FatalError must be consulted
263 * to find that out. FatalError is never true in PM_RECOVERY_* or PM_RUN
264 * states, nor in PM_SHUTDOWN states (because we don't enter those states
265 * when trying to recover from a crash). It can be true in PM_STARTUP state,
266 * because we don't clear it until we've successfully started WAL redo.
267 * Similarly, RecoveryError means that we have crashed during recovery, and
268 * should not try to restart.
272 PM_INIT, /* postmaster starting */
273 PM_STARTUP, /* waiting for startup subprocess */
274 PM_RECOVERY, /* in archive recovery mode */
275 PM_RECOVERY_CONSISTENT, /* consistent recovery mode */
276 PM_RUN, /* normal "database is alive" state */
277 PM_WAIT_BACKUP, /* waiting for online backup mode to end */
278 PM_WAIT_BACKENDS, /* waiting for live backends to exit */
279 PM_SHUTDOWN, /* waiting for bgwriter to do shutdown ckpt */
280 PM_SHUTDOWN_2, /* waiting for archiver to finish */
281 PM_WAIT_DEAD_END, /* waiting for dead_end children to exit */
282 PM_NO_CHILDREN /* all important children have exited */
285 static PMState pmState = PM_INIT;
287 bool ClientAuthInProgress = false; /* T during new-client
290 bool redirection_done = false; /* stderr redirected for syslogger? */
292 /* received START_AUTOVAC_LAUNCHER signal */
293 static volatile sig_atomic_t start_autovac_launcher = false;
294 /* the launcher needs to be signalled to communicate some condition */
295 static volatile bool avlauncher_needs_signal = false;
298 * State for assigning random salts and cancel keys.
299 * Also, the global MyCancelKey passes the cancel key assigned to a given
300 * backend from the postmaster to that backend (via fork).
302 static unsigned int random_seed = 0;
303 static struct timeval random_start_time;
309 #ifdef HAVE_INT_OPTRESET
310 extern int optreset; /* might not be declared by system headers */
314 static DNSServiceRef bonjour_sdref = NULL;
318 * postmaster.c - function prototypes
320 static void getInstallationPaths(const char *argv0);
321 static void checkDataDir(void);
322 static void pmdaemonize(void);
323 static Port *ConnCreate(int serverFd);
324 static void ConnFree(Port *port);
325 static void reset_shared(int port);
326 static void SIGHUP_handler(SIGNAL_ARGS);
327 static void pmdie(SIGNAL_ARGS);
328 static void reaper(SIGNAL_ARGS);
329 static void sigusr1_handler(SIGNAL_ARGS);
330 static void startup_die(SIGNAL_ARGS);
331 static void dummy_handler(SIGNAL_ARGS);
332 static void CleanupBackend(int pid, int exitstatus);
333 static void HandleChildCrash(int pid, int exitstatus, const char *procname);
334 static void LogChildExit(int lev, const char *procname,
335 int pid, int exitstatus);
336 static void PostmasterStateMachine(void);
337 static void BackendInitialize(Port *port);
338 static int BackendRun(Port *port);
339 static void ExitPostmaster(int status);
340 static int ServerLoop(void);
341 static int BackendStartup(Port *port);
342 static int ProcessStartupPacket(Port *port, bool SSLdone);
343 static void processCancelRequest(Port *port, void *pkt);
344 static int initMasks(fd_set *rmask);
345 static void report_fork_failure_to_client(Port *port, int errnum);
346 static enum CAC_state canAcceptConnections(void);
347 static long PostmasterRandom(void);
348 static void RandomSalt(char *md5Salt);
349 static void signal_child(pid_t pid, int signal);
350 static void SignalSomeChildren(int signal, bool only_autovac);
352 #define SignalChildren(sig) SignalSomeChildren(sig, false)
353 #define SignalAutovacWorkers(sig) SignalSomeChildren(sig, true)
354 static int CountChildren(void);
355 static bool CreateOptsFile(int argc, char *argv[], char *fullprogname);
356 static pid_t StartChildProcess(AuxProcType type);
357 static void StartAutovacuumWorker(void);
362 static pid_t win32_waitpid(int *exitstatus);
363 static void WINAPI pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired);
365 static HANDLE win32ChildQueue;
372 } win32_deadchild_waitinfo;
374 HANDLE PostmasterHandle;
377 static pid_t backend_forkexec(Port *port);
378 static pid_t internal_forkexec(int argc, char *argv[], Port *port);
380 /* Type for a socket that can be inherited to a client process */
384 SOCKET origsocket; /* Original socket value, or -1 if not a
386 WSAPROTOCOL_INFO wsainfo;
389 typedef int InheritableSocket;
392 typedef struct LWLock LWLock; /* ugly kluge */
395 * Structure contains all variables passed to exec:ed backends
400 InheritableSocket portsocket;
401 char DataDir[MAXPGPATH];
402 int ListenSocket[MAXLISTEN];
405 unsigned long UsedShmemSegID;
406 void *UsedShmemSegAddr;
408 VariableCache ShmemVariableCache;
409 Backend *ShmemBackendArray;
411 slock_t *ProcStructLock;
412 PROC_HDR *ProcGlobal;
413 PGPROC *AuxiliaryProcs;
414 PMSignalData *PMSignalState;
415 InheritableSocket pgStatSock;
417 TimestampTz PgStartTime;
418 TimestampTz PgReloadTime;
419 bool redirection_done;
421 HANDLE PostmasterHandle;
422 HANDLE initial_signal_pipe;
423 HANDLE syslogPipe[2];
427 char my_exec_path[MAXPGPATH];
428 char pkglib_path[MAXPGPATH];
429 char ExtraOptions[MAXPGPATH];
432 static void read_backend_variables(char *id, Port *port);
433 static void restore_backend_variables(BackendParameters *param, Port *port);
436 static bool save_backend_variables(BackendParameters *param, Port *port);
438 static bool save_backend_variables(BackendParameters *param, Port *port,
439 HANDLE childProcess, pid_t childPid);
442 static void ShmemBackendArrayAdd(Backend *bn);
443 static void ShmemBackendArrayRemove(Backend *bn);
444 #endif /* EXEC_BACKEND */
446 #define StartupDataBase() StartChildProcess(StartupProcess)
447 #define StartBackgroundWriter() StartChildProcess(BgWriterProcess)
448 #define StartWalWriter() StartChildProcess(WalWriterProcess)
450 /* Macros to check exit status of a child process */
451 #define EXIT_STATUS_0(st) ((st) == 0)
452 #define EXIT_STATUS_1(st) (WIFEXITED(st) && WEXITSTATUS(st) == 1)
456 * Postmaster main entry point
459 PostmasterMain(int argc, char *argv[])
463 char *userDoption = NULL;
466 MyProcPid = PostmasterPid = getpid();
468 MyStartTime = time(NULL);
470 IsPostmasterEnvironment = true;
473 * for security, no dir or file created can be group or other accessible
475 umask((mode_t) 0077);
478 * Fire up essential subsystems: memory management
483 * By default, palloc() requests in the postmaster will be allocated in
484 * the PostmasterContext, which is space that can be recycled by backends.
485 * Allocated data that needs to be available to backends should be
486 * allocated in TopMemoryContext.
488 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
490 ALLOCSET_DEFAULT_MINSIZE,
491 ALLOCSET_DEFAULT_INITSIZE,
492 ALLOCSET_DEFAULT_MAXSIZE);
493 MemoryContextSwitchTo(PostmasterContext);
495 /* Initialize paths to installation files */
496 getInstallationPaths(argv[0]);
501 InitializeGUCOptions();
506 * Parse command-line options. CAUTION: keep this in sync with
507 * tcop/postgres.c (the option sets should not conflict) and with the
508 * common help() function in main/main.c.
510 while ((opt = getopt(argc, argv, "A:B:c:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:W:-:")) != -1)
515 SetConfigOption("debug_assertions", optarg, PGC_POSTMASTER, PGC_S_ARGV);
519 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
523 userDoption = optarg;
527 set_debug_options(atoi(optarg), PGC_POSTMASTER, PGC_S_ARGV);
531 SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
535 SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
539 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
543 if (!set_plan_disabling_options(optarg, PGC_POSTMASTER, PGC_S_ARGV))
545 write_stderr("%s: invalid argument for option -f: \"%s\"\n",
552 SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
556 SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
560 /* only used by interactive backend */
564 SetConfigOption("unix_socket_directory", optarg, PGC_POSTMASTER, PGC_S_ARGV);
568 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
572 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
576 /* Don't reinit shared mem after abnormal exit */
581 SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
585 /* Other options to pass to the backend on the command line */
586 snprintf(ExtraOptions + strlen(ExtraOptions),
587 sizeof(ExtraOptions) - strlen(ExtraOptions),
592 SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
596 SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
600 /* only used by single-user backend */
604 SetConfigOption("work_mem", optarg, PGC_POSTMASTER, PGC_S_ARGV);
608 SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
614 * In the event that some backend dumps core, send SIGSTOP,
615 * rather than SIGQUIT, to all its peers. This lets the wily
616 * post_hacker collect core dumps from everyone.
623 const char *tmp = get_stats_option_name(optarg);
627 SetConfigOption(tmp, "true", PGC_POSTMASTER, PGC_S_ARGV);
631 write_stderr("%s: invalid argument for option -t: \"%s\"\n",
639 SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
648 ParseLongOption(optarg, &name, &value);
653 (errcode(ERRCODE_SYNTAX_ERROR),
654 errmsg("--%s requires a value",
658 (errcode(ERRCODE_SYNTAX_ERROR),
659 errmsg("-c %s requires a value",
663 SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
671 write_stderr("Try \"%s --help\" for more information.\n",
678 * Postmaster accepts no non-option switch arguments.
682 write_stderr("%s: invalid argument: \"%s\"\n",
683 progname, argv[optind]);
684 write_stderr("Try \"%s --help\" for more information.\n",
690 * Locate the proper configuration files and data directory, and read
691 * postgresql.conf for the first time.
693 if (!SelectConfigFiles(userDoption, progname))
696 /* Verify that DataDir looks reasonable */
699 /* And switch working directory into it */
703 * Check for invalid combinations of GUC settings.
705 if (ReservedBackends >= MaxBackends)
707 write_stderr("%s: superuser_reserved_connections must be less than max_connections\n", progname);
712 * Other one-time internal sanity checks can go here, if they are fast.
713 * (Put any slow processing further down, after postmaster.pid creation.)
715 if (!CheckDateTokenTables())
717 write_stderr("%s: invalid datetoken tables, please fix\n", progname);
722 * Now that we are done processing the postmaster arguments, reset
723 * getopt(3) library so that it will work correctly in subprocesses.
726 #ifdef HAVE_INT_OPTRESET
727 optreset = 1; /* some systems need this too */
730 /* For debugging: display postmaster environment */
732 extern char **environ;
736 (errmsg_internal("%s: PostmasterMain: initial environ dump:",
739 (errmsg_internal("-----------------------------------------")));
740 for (p = environ; *p; ++p)
742 (errmsg_internal("\t%s", *p)));
744 (errmsg_internal("-----------------------------------------")));
748 * Fork away from controlling terminal, if silent_mode specified.
750 * Must do this before we grab any interlock files, else the interlocks
751 * will show the wrong PID.
757 * Create lockfile for data directory.
759 * We want to do this before we try to grab the input sockets, because the
760 * data directory interlock is more reliable than the socket-file
761 * interlock (thanks to whoever decided to put socket files in /tmp :-().
762 * For the same reason, it's best to grab the TCP socket(s) before the
765 CreateDataDirLockFile(true);
768 * If timezone is not set, determine what the OS uses. (In theory this
769 * should be done during GUC initialization, but because it can take as
770 * much as several seconds, we delay it until after we've created the
771 * postmaster.pid file. This prevents problems with boot scripts that
772 * expect the pidfile to appear quickly. Also, we avoid problems with
773 * trying to locate the timezone files too early in initialization.)
775 pg_timezone_initialize();
778 * Likewise, init timezone_abbreviations if not already set.
780 pg_timezone_abbrev_initialize();
783 * Initialize SSL library, if specified.
791 * process any libraries that should be preloaded at postmaster start
793 process_shared_preload_libraries();
796 * Remove old temporary files. At this point there can be no other
797 * Postgres processes running in this directory, so this should be safe.
802 * Establish input sockets.
804 for (i = 0; i < MAXLISTEN; i++)
805 ListenSocket[i] = -1;
814 /* Need a modifiable copy of ListenAddresses */
815 rawstring = pstrdup(ListenAddresses);
817 /* Parse string into list of identifiers */
818 if (!SplitIdentifierString(rawstring, ',', &elemlist))
820 /* syntax error in list */
822 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
823 errmsg("invalid list syntax for \"listen_addresses\"")));
828 char *curhost = (char *) lfirst(l);
830 if (strcmp(curhost, "*") == 0)
831 status = StreamServerPort(AF_UNSPEC, NULL,
832 (unsigned short) PostPortNumber,
834 ListenSocket, MAXLISTEN);
836 status = StreamServerPort(AF_UNSPEC, curhost,
837 (unsigned short) PostPortNumber,
839 ListenSocket, MAXLISTEN);
840 if (status == STATUS_OK)
844 (errmsg("could not create listen socket for \"%s\"",
848 if (!success && list_length(elemlist))
850 (errmsg("could not create any TCP/IP sockets")));
857 /* Register for Bonjour only if we opened TCP socket(s) */
858 if (enable_bonjour && ListenSocket[0] != -1)
860 DNSServiceErrorType err;
863 * We pass 0 for interface_index, which will result in registering on
864 * all "applicable" interfaces. It's not entirely clear from the
865 * DNS-SD docs whether this would be appropriate if we have bound to
866 * just a subset of the available network interfaces.
868 err = DNSServiceRegister(&bonjour_sdref,
875 htons(PostPortNumber),
880 if (err != kDNSServiceErr_NoError)
881 elog(LOG, "DNSServiceRegister() failed: error code %ld",
884 * We don't bother to read the mDNS daemon's reply, and we expect
885 * that it will automatically terminate our registration when the
886 * socket is closed at postmaster termination. So there's nothing
887 * more to be done here. However, the bonjour_sdref is kept around
888 * so that forked children can close their copies of the socket.
893 #ifdef HAVE_UNIX_SOCKETS
894 status = StreamServerPort(AF_UNIX, NULL,
895 (unsigned short) PostPortNumber,
897 ListenSocket, MAXLISTEN);
898 if (status != STATUS_OK)
900 (errmsg("could not create Unix-domain socket")));
904 * check that we have some socket to listen on
906 if (ListenSocket[0] == -1)
908 (errmsg("no socket created for listening")));
911 * Set up shared memory and semaphores.
913 reset_shared(PostPortNumber);
916 * Estimate number of openable files. This must happen after setting up
917 * semaphores, because on some platforms semaphores count as open files.
922 * Initialize the list of active backends.
924 BackendList = DLNewList();
929 * Initialize I/O completion port used to deliver list of dead children.
931 win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
932 if (win32ChildQueue == NULL)
934 (errmsg("could not create I/O completion port for child queue")));
937 * Set up a handle that child processes can use to check whether the
938 * postmaster is still running.
940 if (DuplicateHandle(GetCurrentProcess(),
946 DUPLICATE_SAME_ACCESS) == 0)
948 (errmsg_internal("could not duplicate postmaster handle: error code %d",
949 (int) GetLastError())));
953 * Record postmaster options. We delay this till now to avoid recording
954 * bogus options (eg, NBuffers too high for available memory).
956 if (!CreateOptsFile(argc, argv, my_exec_path))
960 /* Write out nondefault GUC settings for child processes to use */
961 write_nondefault_variables(PGC_POSTMASTER);
965 * Write the external PID file if requested
967 if (external_pid_file)
969 FILE *fpidfile = fopen(external_pid_file, "w");
973 fprintf(fpidfile, "%d\n", MyProcPid);
975 /* Should we remove the pid file on postmaster exit? */
978 write_stderr("%s: could not write external PID file \"%s\": %s\n",
979 progname, external_pid_file, strerror(errno));
983 * Set up signal handlers for the postmaster process.
985 * CAUTION: when changing this list, check for side-effects on the signal
986 * handling setup of child processes. See tcop/postgres.c,
987 * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/walwriter.c,
988 * postmaster/autovacuum.c, postmaster/pgarch.c, postmaster/pgstat.c, and
989 * postmaster/syslogger.c.
992 PG_SETMASK(&BlockSig);
994 pqsignal(SIGHUP, SIGHUP_handler); /* reread config file and have
995 * children do same */
996 pqsignal(SIGINT, pmdie); /* send SIGTERM and shut down */
997 pqsignal(SIGQUIT, pmdie); /* send SIGQUIT and die */
998 pqsignal(SIGTERM, pmdie); /* wait for children and shut down */
999 pqsignal(SIGALRM, SIG_IGN); /* ignored */
1000 pqsignal(SIGPIPE, SIG_IGN); /* ignored */
1001 pqsignal(SIGUSR1, sigusr1_handler); /* message from child process */
1002 pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
1003 pqsignal(SIGCHLD, reaper); /* handle child termination */
1004 pqsignal(SIGTTIN, SIG_IGN); /* ignored */
1005 pqsignal(SIGTTOU, SIG_IGN); /* ignored */
1006 /* ignore SIGXFSZ, so that ulimit violations work like disk full */
1008 pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
1012 * If enabled, start up syslogger collection subprocess
1014 SysLoggerPID = SysLogger_Start();
1017 * Reset whereToSendOutput from DestDebug (its starting state) to
1018 * DestNone. This stops ereport from sending log messages to stderr unless
1019 * Log_destination permits. We don't do this until the postmaster is
1020 * fully launched, since startup failures may as well be reported to
1023 whereToSendOutput = DestNone;
1026 * Initialize stats collection subsystem (this does NOT start the
1027 * collector process!)
1032 * Initialize the autovacuum subsystem (again, no process start yet)
1037 * Load configuration files for client authentication.
1042 * It makes no sense to continue if we fail to load the HBA file,
1043 * since there is no way to connect to the database in this case.
1046 (errmsg("could not load pg_hba.conf")));
1051 * Remember postmaster startup time
1053 PgStartTime = GetCurrentTimestamp();
1054 /* PostmasterRandom wants its own copy */
1055 gettimeofday(&random_start_time, NULL);
1058 * We're ready to rock and roll...
1060 StartupPID = StartupDataBase();
1061 Assert(StartupPID != 0);
1062 pmState = PM_STARTUP;
1064 status = ServerLoop();
1067 * ServerLoop probably shouldn't ever return, but if it does, close down.
1069 ExitPostmaster(status != STATUS_OK);
1071 return 0; /* not reached */
1076 * Compute and check the directory paths to files that are part of the
1077 * installation (as deduced from the postgres executable's own location)
1080 getInstallationPaths(const char *argv0)
1084 /* Locate the postgres executable itself */
1085 if (find_my_exec(argv0, my_exec_path) < 0)
1086 elog(FATAL, "%s: could not locate my own executable path", argv0);
1089 /* Locate executable backend before we change working directory */
1090 if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1091 postgres_exec_path) < 0)
1093 (errmsg("%s: could not locate matching postgres executable",
1098 * Locate the pkglib directory --- this has to be set early in case we try
1099 * to load any modules from it in response to postgresql.conf entries.
1101 get_pkglib_path(my_exec_path, pkglib_path);
1104 * Verify that there's a readable directory there; otherwise the Postgres
1105 * installation is incomplete or corrupt. (A typical cause of this
1106 * failure is that the postgres executable has been moved or hardlinked to
1107 * some directory that's not a sibling of the installation lib/
1110 pdir = AllocateDir(pkglib_path);
1113 (errcode_for_file_access(),
1114 errmsg("could not open directory \"%s\": %m",
1116 errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1121 * XXX is it worth similarly checking the share/ directory? If the lib/
1122 * directory is there, then share/ probably is too.
1128 * Validate the proposed data directory
1133 char path[MAXPGPATH];
1135 struct stat stat_buf;
1139 if (stat(DataDir, &stat_buf) != 0)
1141 if (errno == ENOENT)
1143 (errcode_for_file_access(),
1144 errmsg("data directory \"%s\" does not exist",
1148 (errcode_for_file_access(),
1149 errmsg("could not read permissions of directory \"%s\": %m",
1153 /* eventual chdir would fail anyway, but let's test ... */
1154 if (!S_ISDIR(stat_buf.st_mode))
1156 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1157 errmsg("specified data directory \"%s\" is not a directory",
1161 * Check that the directory belongs to my userid; if not, reject.
1163 * This check is an essential part of the interlock that prevents two
1164 * postmasters from starting in the same directory (see CreateLockFile()).
1165 * Do not remove or weaken it.
1167 * XXX can we safely enable this check on Windows?
1169 #if !defined(WIN32) && !defined(__CYGWIN__)
1170 if (stat_buf.st_uid != geteuid())
1172 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1173 errmsg("data directory \"%s\" has wrong ownership",
1175 errhint("The server must be started by the user that owns the data directory.")));
1179 * Check if the directory has group or world access. If so, reject.
1181 * It would be possible to allow weaker constraints (for example, allow
1182 * group access) but we cannot make a general assumption that that is
1183 * okay; for example there are platforms where nearly all users
1184 * customarily belong to the same group. Perhaps this test should be
1187 * XXX temporarily suppress check when on Windows, because there may not
1188 * be proper support for Unix-y file permissions. Need to think of a
1189 * reasonable check to apply on Windows.
1191 #if !defined(WIN32) && !defined(__CYGWIN__)
1192 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
1194 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1195 errmsg("data directory \"%s\" has group or world access",
1197 errdetail("Permissions should be u=rwx (0700).")));
1200 /* Look for PG_VERSION before looking for pg_control */
1201 ValidatePgVersion(DataDir);
1203 snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1205 fp = AllocateFile(path, PG_BINARY_R);
1208 write_stderr("%s: could not find the database system\n"
1209 "Expected to find it in the directory \"%s\",\n"
1210 "but could not open file \"%s\": %s\n",
1211 progname, DataDir, path, strerror(errno));
1219 * Fork away from the controlling terminal (silent_mode option)
1221 * Since this requires disconnecting from stdin/stdout/stderr (in case they're
1222 * linked to the terminal), we re-point stdin to /dev/null and stdout/stderr
1223 * to "postmaster.log" in the data directory, where we're already chdir'd.
1229 const char *pmlogname = "postmaster.log";
1236 * Make sure we can open the files we're going to redirect to. If this
1237 * fails, we want to complain before disconnecting. Mention the full path
1238 * of the logfile in the error message, even though we address it by
1241 dvnull = open(DEVNULL, O_RDONLY, 0);
1244 write_stderr("%s: could not open file \"%s\": %s\n",
1245 progname, DEVNULL, strerror(errno));
1248 pmlog = open(pmlogname, O_CREAT | O_WRONLY | O_APPEND, 0600);
1251 write_stderr("%s: could not open log file \"%s/%s\": %s\n",
1252 progname, DataDir, pmlogname, strerror(errno));
1259 pid = fork_process();
1260 if (pid == (pid_t) -1)
1262 write_stderr("%s: could not fork background process: %s\n",
1263 progname, strerror(errno));
1268 /* Parent should just exit, without doing any atexit cleanup */
1272 MyProcPid = PostmasterPid = getpid(); /* reset PID vars to child */
1274 MyStartTime = time(NULL);
1277 * Some systems use setsid() to dissociate from the TTY's process group,
1278 * while on others it depends on stdin/stdout/stderr. Do both if possible.
1283 write_stderr("%s: could not dissociate from controlling TTY: %s\n",
1284 progname, strerror(errno));
1290 * Reassociate stdin/stdout/stderr. fork_process() cleared any pending
1291 * output, so this should be safe. The only plausible error is EINTR,
1292 * which just means we should retry.
1295 res = dup2(dvnull, 0);
1296 } while (res < 0 && errno == EINTR);
1299 res = dup2(pmlog, 1);
1300 } while (res < 0 && errno == EINTR);
1302 res = dup2(pmlog, 2);
1303 } while (res < 0 && errno == EINTR);
1307 elog(FATAL, "silent_mode is not supported under Windows");
1313 * Main idle loop of postmaster
1323 last_touch_time = time(NULL);
1325 nSockets = initMasks(&readmask);
1333 * Wait for a connection request to arrive.
1335 * We wait at most one minute, to ensure that the other background
1336 * tasks handled below get done even when no requests are arriving.
1338 * If we are in PM_WAIT_DEAD_END state, then we don't want to accept
1339 * any new connections, so we don't call select() at all; just sleep
1340 * for a little bit with signals unblocked.
1342 memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
1344 PG_SETMASK(&UnBlockSig);
1346 if (pmState == PM_WAIT_DEAD_END)
1348 pg_usleep(100000L); /* 100 msec seems reasonable */
1353 /* must set timeout each time; some OSes change it! */
1354 struct timeval timeout;
1356 timeout.tv_sec = 60;
1357 timeout.tv_usec = 0;
1359 selres = select(nSockets, &rmask, NULL, NULL, &timeout);
1363 * Block all signals until we wait again. (This makes it safe for our
1364 * signal handlers to do nontrivial work.)
1366 PG_SETMASK(&BlockSig);
1368 /* Now check the select() result */
1371 if (errno != EINTR && errno != EWOULDBLOCK)
1374 (errcode_for_socket_access(),
1375 errmsg("select() failed in postmaster: %m")));
1376 return STATUS_ERROR;
1381 * New connection pending on any of our sockets? If so, fork a child
1382 * process to deal with it.
1388 for (i = 0; i < MAXLISTEN; i++)
1390 if (ListenSocket[i] == -1)
1392 if (FD_ISSET(ListenSocket[i], &rmask))
1396 port = ConnCreate(ListenSocket[i]);
1399 BackendStartup(port);
1402 * We no longer need the open socket or port structure
1405 StreamClose(port->sock);
1412 /* If we have lost the log collector, try to start a new one */
1413 if (SysLoggerPID == 0 && Logging_collector)
1414 SysLoggerPID = SysLogger_Start();
1417 * If no background writer process is running, and we are not in a
1418 * state that prevents it, start one. It doesn't matter if this
1419 * fails, we'll just try again later.
1421 if (BgWriterPID == 0 &&
1422 (pmState == PM_RUN || pmState == PM_RECOVERY ||
1423 pmState == PM_RECOVERY_CONSISTENT))
1424 BgWriterPID = StartBackgroundWriter();
1427 * Likewise, if we have lost the walwriter process, try to start a new
1430 if (WalWriterPID == 0 && pmState == PM_RUN)
1431 WalWriterPID = StartWalWriter();
1433 /* If we have lost the autovacuum launcher, try to start a new one */
1434 if (AutoVacPID == 0 &&
1435 (AutoVacuumingActive() || start_autovac_launcher) &&
1438 AutoVacPID = StartAutoVacLauncher();
1439 if (AutoVacPID != 0)
1440 start_autovac_launcher = false; /* signal processed */
1443 /* If we have lost the archiver, try to start a new one */
1444 if (XLogArchivingActive() && PgArchPID == 0 && pmState == PM_RUN)
1445 PgArchPID = pgarch_start();
1447 /* If we have lost the stats collector, try to start a new one */
1448 if (PgStatPID == 0 && pmState == PM_RUN)
1449 PgStatPID = pgstat_start();
1451 /* If we need to signal the autovacuum launcher, do so now */
1452 if (avlauncher_needs_signal)
1454 avlauncher_needs_signal = false;
1455 if (AutoVacPID != 0)
1456 kill(AutoVacPID, SIGUSR2);
1460 * Touch the socket and lock file every 58 minutes, to ensure that
1461 * they are not removed by overzealous /tmp-cleaning tasks. We assume
1462 * no one runs cleaners with cutoff times of less than an hour ...
1465 if (now - last_touch_time >= 58 * SECS_PER_MINUTE)
1468 TouchSocketLockFile();
1469 last_touch_time = now;
1476 * Initialise the masks for select() for the ports we are listening on.
1477 * Return the number of sockets to listen on.
1480 initMasks(fd_set *rmask)
1487 for (i = 0; i < MAXLISTEN; i++)
1489 int fd = ListenSocket[i];
1504 * Read a client's startup packet and do something according to it.
1506 * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
1507 * not return at all.
1509 * (Note that ereport(FATAL) stuff is sent to the client, so only use it
1510 * if that's what you want. Return STATUS_ERROR if you don't want to
1511 * send anything to the client, which would typically be appropriate
1512 * if we detect a communications failure.)
1515 ProcessStartupPacket(Port *port, bool SSLdone)
1519 ProtocolVersion proto;
1520 MemoryContext oldcontext;
1522 if (pq_getbytes((char *) &len, 4) == EOF)
1525 * EOF after SSLdone probably means the client didn't like our
1526 * response to NEGOTIATE_SSL_CODE. That's not an error condition, so
1527 * don't clutter the log with a complaint.
1531 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1532 errmsg("incomplete startup packet")));
1533 return STATUS_ERROR;
1539 if (len < (int32) sizeof(ProtocolVersion) ||
1540 len > MAX_STARTUP_PACKET_LENGTH)
1543 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1544 errmsg("invalid length of startup packet")));
1545 return STATUS_ERROR;
1549 * Allocate at least the size of an old-style startup packet, plus one
1550 * extra byte, and make sure all are zeroes. This ensures we will have
1551 * null termination of all strings, in both fixed- and variable-length
1554 if (len <= (int32) sizeof(StartupPacket))
1555 buf = palloc0(sizeof(StartupPacket) + 1);
1557 buf = palloc0(len + 1);
1559 if (pq_getbytes(buf, len) == EOF)
1562 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1563 errmsg("incomplete startup packet")));
1564 return STATUS_ERROR;
1568 * The first field is either a protocol version number or a special
1571 port->proto = proto = ntohl(*((ProtocolVersion *) buf));
1573 if (proto == CANCEL_REQUEST_CODE)
1575 processCancelRequest(port, buf);
1576 /* Not really an error, but we don't want to proceed further */
1577 return STATUS_ERROR;
1580 if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
1585 /* No SSL when disabled or on Unix sockets */
1586 if (!EnableSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
1589 SSLok = 'S'; /* Support for SSL */
1591 SSLok = 'N'; /* No support for SSL */
1595 if (send(port->sock, &SSLok, 1, 0) != 1)
1598 goto retry1; /* if interrupted, just retry */
1600 (errcode_for_socket_access(),
1601 errmsg("failed to send SSL negotiation response: %m")));
1602 return STATUS_ERROR; /* close the connection */
1606 if (SSLok == 'S' && secure_open_server(port) == -1)
1607 return STATUS_ERROR;
1609 /* regular startup packet, cancel, etc packet should follow... */
1610 /* but not another SSL negotiation request */
1611 return ProcessStartupPacket(port, true);
1614 /* Could add additional special packet types here */
1617 * Set FrontendProtocol now so that ereport() knows what format to send if
1618 * we fail during startup.
1620 FrontendProtocol = proto;
1622 /* Check we can handle the protocol the frontend is using. */
1624 if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
1625 PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
1626 (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
1627 PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
1629 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1630 errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
1631 PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
1632 PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST),
1633 PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST),
1634 PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))));
1637 * Now fetch parameters out of startup packet and save them into the Port
1638 * structure. All data structures attached to the Port struct must be
1639 * allocated in TopMemoryContext so that they will remain available in
1640 * a running backend (even after PostmasterContext is destroyed). We need
1641 * not worry about leaking this storage on failure, since we aren't in the
1642 * postmaster process anymore.
1644 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1646 if (PG_PROTOCOL_MAJOR(proto) >= 3)
1648 int32 offset = sizeof(ProtocolVersion);
1651 * Scan packet body for name/option pairs. We can assume any string
1652 * beginning within the packet body is null-terminated, thanks to
1653 * zeroing extra byte above.
1655 port->guc_options = NIL;
1657 while (offset < len)
1659 char *nameptr = ((char *) buf) + offset;
1663 if (*nameptr == '\0')
1664 break; /* found packet terminator */
1665 valoffset = offset + strlen(nameptr) + 1;
1666 if (valoffset >= len)
1667 break; /* missing value, will complain below */
1668 valptr = ((char *) buf) + valoffset;
1670 if (strcmp(nameptr, "database") == 0)
1671 port->database_name = pstrdup(valptr);
1672 else if (strcmp(nameptr, "user") == 0)
1673 port->user_name = pstrdup(valptr);
1674 else if (strcmp(nameptr, "options") == 0)
1675 port->cmdline_options = pstrdup(valptr);
1678 /* Assume it's a generic GUC option */
1679 port->guc_options = lappend(port->guc_options,
1681 port->guc_options = lappend(port->guc_options,
1684 offset = valoffset + strlen(valptr) + 1;
1688 * If we didn't find a packet terminator exactly at the end of the
1689 * given packet length, complain.
1691 if (offset != len - 1)
1693 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1694 errmsg("invalid startup packet layout: expected terminator as last byte")));
1699 * Get the parameters from the old-style, fixed-width-fields startup
1700 * packet as C strings. The packet destination was cleared first so a
1701 * short packet has zeros silently added. We have to be prepared to
1702 * truncate the pstrdup result for oversize fields, though.
1704 StartupPacket *packet = (StartupPacket *) buf;
1706 port->database_name = pstrdup(packet->database);
1707 if (strlen(port->database_name) > sizeof(packet->database))
1708 port->database_name[sizeof(packet->database)] = '\0';
1709 port->user_name = pstrdup(packet->user);
1710 if (strlen(port->user_name) > sizeof(packet->user))
1711 port->user_name[sizeof(packet->user)] = '\0';
1712 port->cmdline_options = pstrdup(packet->options);
1713 if (strlen(port->cmdline_options) > sizeof(packet->options))
1714 port->cmdline_options[sizeof(packet->options)] = '\0';
1715 port->guc_options = NIL;
1718 /* Check a user name was given. */
1719 if (port->user_name == NULL || port->user_name[0] == '\0')
1721 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1722 errmsg("no PostgreSQL user name specified in startup packet")));
1724 /* The database defaults to the user name. */
1725 if (port->database_name == NULL || port->database_name[0] == '\0')
1726 port->database_name = pstrdup(port->user_name);
1728 if (Db_user_namespace)
1731 * If user@, it is a global user, remove '@'. We only want to do this
1732 * if there is an '@' at the end and no earlier in the user string or
1733 * they may fake as a local user of another database attaching to this
1736 if (strchr(port->user_name, '@') ==
1737 port->user_name + strlen(port->user_name) - 1)
1738 *strchr(port->user_name, '@') = '\0';
1741 /* Append '@' and dbname */
1744 db_user = palloc(strlen(port->user_name) +
1745 strlen(port->database_name) + 2);
1746 sprintf(db_user, "%s@%s", port->user_name, port->database_name);
1747 port->user_name = db_user;
1752 * Truncate given database and user names to length of a Postgres name.
1753 * This avoids lookup failures when overlength names are given.
1755 if (strlen(port->database_name) >= NAMEDATALEN)
1756 port->database_name[NAMEDATALEN - 1] = '\0';
1757 if (strlen(port->user_name) >= NAMEDATALEN)
1758 port->user_name[NAMEDATALEN - 1] = '\0';
1761 * Done putting stuff in TopMemoryContext.
1763 MemoryContextSwitchTo(oldcontext);
1766 * If we're going to reject the connection due to database state, say so
1767 * now instead of wasting cycles on an authentication exchange. (This also
1768 * allows a pg_ping utility to be written.)
1770 switch (port->canAcceptConnections)
1774 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1775 errmsg("the database system is starting up")));
1779 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1780 errmsg("the database system is shutting down")));
1784 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1785 errmsg("the database system is in recovery mode")));
1789 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
1790 errmsg("sorry, too many clients already")));
1792 case CAC_WAITBACKUP:
1793 /* OK for now, will check in InitPostgres */
1804 * The client has sent a cancel request packet, not a normal
1805 * start-a-new-connection packet. Perform the necessary processing.
1806 * Nothing is sent back to the client.
1809 processCancelRequest(Port *port, void *pkt)
1811 CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
1813 long cancelAuthCode;
1816 #ifndef EXEC_BACKEND
1822 backendPID = (int) ntohl(canc->backendPID);
1823 cancelAuthCode = (long) ntohl(canc->cancelAuthCode);
1826 * See if we have a matching backend. In the EXEC_BACKEND case, we can no
1827 * longer access the postmaster's own backend list, and must rely on the
1828 * duplicate array in shared memory.
1830 #ifndef EXEC_BACKEND
1831 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
1833 bp = (Backend *) DLE_VAL(curr);
1835 for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
1837 bp = (Backend *) &ShmemBackendArray[i];
1839 if (bp->pid == backendPID)
1841 if (bp->cancel_key == cancelAuthCode)
1843 /* Found a match; signal that backend to cancel current op */
1845 (errmsg_internal("processing cancel request: sending SIGINT to process %d",
1847 signal_child(bp->pid, SIGINT);
1850 /* Right PID, wrong key: no way, Jose */
1852 (errmsg("wrong key in cancel request for process %d",
1858 /* No matching backend */
1860 (errmsg("PID %d in cancel request did not match any process",
1865 * canAcceptConnections --- check to see if database state allows connections.
1867 static enum CAC_state
1868 canAcceptConnections(void)
1871 * Can't start backends when in startup/shutdown/recovery state.
1873 * In state PM_WAIT_BACKUP only superusers can connect (this must be
1874 * allowed so that a superuser can end online backup mode); we return
1875 * CAC_WAITBACKUP code to indicate that this must be checked later.
1877 if (pmState != PM_RUN)
1879 if (pmState == PM_WAIT_BACKUP)
1880 return CAC_WAITBACKUP; /* allow superusers only */
1881 if (Shutdown > NoShutdown)
1882 return CAC_SHUTDOWN; /* shutdown is pending */
1884 (pmState == PM_STARTUP ||
1885 pmState == PM_RECOVERY ||
1886 pmState == PM_RECOVERY_CONSISTENT))
1887 return CAC_STARTUP; /* normal startup */
1888 return CAC_RECOVERY; /* else must be crash recovery */
1892 * Don't start too many children.
1894 * We allow more connections than we can have backends here because some
1895 * might still be authenticating; they might fail auth, or some existing
1896 * backend might exit before the auth cycle is completed. The exact
1897 * MaxBackends limit is enforced when a new backend tries to join the
1898 * shared-inval backend array.
1900 * The limit here must match the sizes of the per-child-process arrays;
1901 * see comments for MaxLivePostmasterChildren().
1903 if (CountChildren() >= MaxLivePostmasterChildren())
1911 * ConnCreate -- create a local connection data structure
1914 ConnCreate(int serverFd)
1918 if (!(port = (Port *) calloc(1, sizeof(Port))))
1921 (errcode(ERRCODE_OUT_OF_MEMORY),
1922 errmsg("out of memory")));
1926 if (StreamConnection(serverFd, port) != STATUS_OK)
1928 if (port->sock >= 0)
1929 StreamClose(port->sock);
1936 * Precompute password salt values to use for this connection. It's
1937 * slightly annoying to do this long in advance of knowing whether
1938 * we'll need 'em or not, but we must do the random() calls before we
1939 * fork, not after. Else the postmaster's random sequence won't get
1940 * advanced, and all backends would end up using the same salt...
1942 RandomSalt(port->md5Salt);
1946 * Allocate GSSAPI specific state struct
1948 #ifndef EXEC_BACKEND
1949 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
1950 port->gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
1954 (errcode(ERRCODE_OUT_OF_MEMORY),
1955 errmsg("out of memory")));
1966 * ConnFree -- free a local connection data structure
1969 ConnFree(Port *conn)
1981 * ClosePostmasterPorts -- close all the postmaster's open sockets
1983 * This is called during child process startup to release file descriptors
1984 * that are not needed by that child process. The postmaster still has
1985 * them open, of course.
1987 * Note: we pass am_syslogger as a boolean because we don't want to set
1988 * the global variable yet when this is called.
1991 ClosePostmasterPorts(bool am_syslogger)
1995 /* Close the listen sockets */
1996 for (i = 0; i < MAXLISTEN; i++)
1998 if (ListenSocket[i] != -1)
2000 StreamClose(ListenSocket[i]);
2001 ListenSocket[i] = -1;
2005 /* If using syslogger, close the read side of the pipe */
2009 if (syslogPipe[0] >= 0)
2010 close(syslogPipe[0]);
2014 CloseHandle(syslogPipe[0]);
2020 /* If using Bonjour, close the connection to the mDNS daemon */
2022 close(DNSServiceRefSockFD(bonjour_sdref));
2028 * reset_shared -- reset shared memory and semaphores
2031 reset_shared(int port)
2034 * Create or re-create shared memory and semaphores.
2036 * Note: in each "cycle of life" we will normally assign the same IPC keys
2037 * (if using SysV shmem and/or semas), since the port number is used to
2038 * determine IPC keys. This helps ensure that we will clean up dead IPC
2039 * objects if the postmaster crashes and is restarted.
2041 CreateSharedMemoryAndSemaphores(false, port);
2046 * SIGHUP -- reread config files, and tell children to do same
2049 SIGHUP_handler(SIGNAL_ARGS)
2051 int save_errno = errno;
2053 PG_SETMASK(&BlockSig);
2055 if (Shutdown <= SmartShutdown)
2058 (errmsg("received SIGHUP, reloading configuration files")));
2059 ProcessConfigFile(PGC_SIGHUP);
2060 SignalChildren(SIGHUP);
2061 if (StartupPID != 0)
2062 signal_child(StartupPID, SIGHUP);
2063 if (BgWriterPID != 0)
2064 signal_child(BgWriterPID, SIGHUP);
2065 if (WalWriterPID != 0)
2066 signal_child(WalWriterPID, SIGHUP);
2067 if (AutoVacPID != 0)
2068 signal_child(AutoVacPID, SIGHUP);
2070 signal_child(PgArchPID, SIGHUP);
2071 if (SysLoggerPID != 0)
2072 signal_child(SysLoggerPID, SIGHUP);
2074 signal_child(PgStatPID, SIGHUP);
2076 /* Reload authentication config files too */
2079 (errmsg("pg_hba.conf not reloaded")));
2084 /* Update the starting-point file for future children */
2085 write_nondefault_variables(PGC_SIGHUP);
2089 PG_SETMASK(&UnBlockSig);
2096 * pmdie -- signal handler for processing various postmaster signals.
2101 int save_errno = errno;
2103 PG_SETMASK(&BlockSig);
2106 (errmsg_internal("postmaster received signal %d",
2107 postgres_signal_arg)));
2109 switch (postgres_signal_arg)
2116 * Wait for children to end their work, then shut down.
2118 if (Shutdown >= SmartShutdown)
2120 Shutdown = SmartShutdown;
2122 (errmsg("received smart shutdown request")));
2124 if (pmState == PM_RUN || pmState == PM_RECOVERY ||
2125 pmState == PM_RECOVERY_CONSISTENT)
2127 /* autovacuum workers are told to shut down immediately */
2128 SignalAutovacWorkers(SIGTERM);
2129 /* and the autovac launcher too */
2130 if (AutoVacPID != 0)
2131 signal_child(AutoVacPID, SIGTERM);
2132 /* and the walwriter too */
2133 if (WalWriterPID != 0)
2134 signal_child(WalWriterPID, SIGTERM);
2135 pmState = PM_WAIT_BACKUP;
2139 * Now wait for online backup mode to end and backends to exit.
2140 * If that is already the case, PostmasterStateMachine will take
2143 PostmasterStateMachine();
2151 * Abort all children with SIGTERM (rollback active transactions
2152 * and exit) and shut down when they are gone.
2154 if (Shutdown >= FastShutdown)
2156 Shutdown = FastShutdown;
2158 (errmsg("received fast shutdown request")));
2160 if (StartupPID != 0)
2161 signal_child(StartupPID, SIGTERM);
2162 if (pmState == PM_RECOVERY)
2164 /* only bgwriter is active in this state */
2165 pmState = PM_WAIT_BACKENDS;
2167 if (pmState == PM_RUN ||
2168 pmState == PM_WAIT_BACKUP ||
2169 pmState == PM_WAIT_BACKENDS ||
2170 pmState == PM_RECOVERY_CONSISTENT)
2173 (errmsg("aborting any active transactions")));
2174 /* shut down all backends and autovac workers */
2175 SignalChildren(SIGTERM);
2176 /* and the autovac launcher too */
2177 if (AutoVacPID != 0)
2178 signal_child(AutoVacPID, SIGTERM);
2179 /* and the walwriter too */
2180 if (WalWriterPID != 0)
2181 signal_child(WalWriterPID, SIGTERM);
2182 pmState = PM_WAIT_BACKENDS;
2186 * Now wait for backends to exit. If there are none,
2187 * PostmasterStateMachine will take the next step.
2189 PostmasterStateMachine();
2195 * Immediate Shutdown:
2197 * abort all children with SIGQUIT and exit without attempt to
2198 * properly shut down data base system.
2201 (errmsg("received immediate shutdown request")));
2202 SignalChildren(SIGQUIT);
2203 if (StartupPID != 0)
2204 signal_child(StartupPID, SIGQUIT);
2205 if (BgWriterPID != 0)
2206 signal_child(BgWriterPID, SIGQUIT);
2207 if (WalWriterPID != 0)
2208 signal_child(WalWriterPID, SIGQUIT);
2209 if (AutoVacPID != 0)
2210 signal_child(AutoVacPID, SIGQUIT);
2212 signal_child(PgArchPID, SIGQUIT);
2214 signal_child(PgStatPID, SIGQUIT);
2219 PG_SETMASK(&UnBlockSig);
2225 * Reaper -- signal handler to cleanup after a child process dies.
2230 int save_errno = errno;
2231 int pid; /* process id of dead child process */
2232 int exitstatus; /* its exit status */
2234 /* These macros hide platform variations in getting child status */
2236 int status; /* child exit status */
2238 #define LOOPTEST() ((pid = waitpid(-1, &status, WNOHANG)) > 0)
2239 #define LOOPHEADER() (exitstatus = status)
2240 #else /* !HAVE_WAITPID */
2242 union wait status; /* child exit status */
2244 #define LOOPTEST() ((pid = wait3(&status, WNOHANG, NULL)) > 0)
2245 #define LOOPHEADER() (exitstatus = status.w_status)
2247 #define LOOPTEST() ((pid = win32_waitpid(&exitstatus)) > 0)
2248 #define LOOPHEADER()
2250 #endif /* HAVE_WAITPID */
2252 PG_SETMASK(&BlockSig);
2255 (errmsg_internal("reaping dead processes")));
2262 * Check if this child was a startup process.
2264 if (pid == StartupPID)
2269 * Unexpected exit of startup process (including FATAL exit)
2270 * during PM_STARTUP is treated as catastrophic. There are no
2271 * other processes running yet, so we can just exit.
2273 if (pmState == PM_STARTUP && !EXIT_STATUS_0(exitstatus))
2275 LogChildExit(LOG, _("startup process"),
2278 (errmsg("aborting startup due to startup process failure")));
2283 * Startup process exited in response to a shutdown request (or it
2284 * completed normally regardless of the shutdown request).
2286 if (Shutdown > NoShutdown &&
2287 (EXIT_STATUS_0(exitstatus) || EXIT_STATUS_1(exitstatus)))
2289 pmState = PM_WAIT_BACKENDS;
2290 /* PostmasterStateMachine logic does the rest */
2295 * Any unexpected exit (including FATAL exit) of the startup
2296 * process is treated as a crash, except that we don't want to
2299 if (!EXIT_STATUS_0(exitstatus))
2301 RecoveryError = true;
2302 HandleChildCrash(pid, exitstatus,
2303 _("startup process"));
2308 * Startup succeeded, commence normal operations
2314 * Crank up the background writer, if we didn't do that already
2315 * when we entered consistent recovery state. It doesn't matter
2316 * if this fails, we'll just try again later.
2318 if (BgWriterPID == 0)
2319 BgWriterPID = StartBackgroundWriter();
2322 * Likewise, start other special children as needed. In a restart
2323 * situation, some of them may be alive already.
2325 if (WalWriterPID == 0)
2326 WalWriterPID = StartWalWriter();
2327 if (AutoVacuumingActive() && AutoVacPID == 0)
2328 AutoVacPID = StartAutoVacLauncher();
2329 if (XLogArchivingActive() && PgArchPID == 0)
2330 PgArchPID = pgarch_start();
2332 PgStatPID = pgstat_start();
2334 /* at this point we are really open for business */
2336 (errmsg("database system is ready to accept connections")));
2342 * Was it the bgwriter?
2344 if (pid == BgWriterPID)
2347 if (EXIT_STATUS_0(exitstatus) && pmState == PM_SHUTDOWN)
2350 * OK, we saw normal exit of the bgwriter after it's been told
2351 * to shut down. We expect that it wrote a shutdown
2352 * checkpoint. (If for some reason it didn't, recovery will
2353 * occur on next postmaster start.)
2355 * At this point we should have no normal backend children
2356 * left (else we'd not be in PM_SHUTDOWN state) but we might
2357 * have dead_end children to wait for.
2359 * If we have an archiver subprocess, tell it to do a last
2360 * archive cycle and quit; otherwise we can go directly to
2361 * PM_WAIT_DEAD_END state.
2363 Assert(Shutdown > NoShutdown);
2367 /* Waken archiver for the last time */
2368 signal_child(PgArchPID, SIGUSR2);
2369 pmState = PM_SHUTDOWN_2;
2372 pmState = PM_WAIT_DEAD_END;
2375 * We can also shut down the stats collector now; there's
2376 * nothing left for it to do.
2379 signal_child(PgStatPID, SIGQUIT);
2384 * Any unexpected exit of the bgwriter (including FATAL exit)
2385 * is treated as a crash.
2387 HandleChildCrash(pid, exitstatus,
2388 _("background writer process"));
2395 * Was it the wal writer? Normal exit can be ignored; we'll start a
2396 * new one at the next iteration of the postmaster's main loop, if
2397 * necessary. Any other exit condition is treated as a crash.
2399 if (pid == WalWriterPID)
2402 if (!EXIT_STATUS_0(exitstatus))
2403 HandleChildCrash(pid, exitstatus,
2404 _("WAL writer process"));
2409 * Was it the autovacuum launcher? Normal exit can be ignored; we'll
2410 * start a new one at the next iteration of the postmaster's main
2411 * loop, if necessary. Any other exit condition is treated as a
2414 if (pid == AutoVacPID)
2417 if (!EXIT_STATUS_0(exitstatus))
2418 HandleChildCrash(pid, exitstatus,
2419 _("autovacuum launcher process"));
2424 * Was it the archiver? If so, just try to start a new one; no need
2425 * to force reset of the rest of the system. (If fail, we'll try
2426 * again in future cycles of the main loop.) But if we were waiting
2427 * for it to shut down, advance to the next shutdown step.
2429 if (pid == PgArchPID)
2432 if (!EXIT_STATUS_0(exitstatus))
2433 LogChildExit(LOG, _("archiver process"),
2435 if (XLogArchivingActive() && pmState == PM_RUN)
2436 PgArchPID = pgarch_start();
2437 else if (pmState == PM_SHUTDOWN_2)
2438 pmState = PM_WAIT_DEAD_END;
2443 * Was it the statistics collector? If so, just try to start a new
2444 * one; no need to force reset of the rest of the system. (If fail,
2445 * we'll try again in future cycles of the main loop.)
2447 if (pid == PgStatPID)
2450 if (!EXIT_STATUS_0(exitstatus))
2451 LogChildExit(LOG, _("statistics collector process"),
2453 if (pmState == PM_RUN)
2454 PgStatPID = pgstat_start();
2458 /* Was it the system logger? If so, try to start a new one */
2459 if (pid == SysLoggerPID)
2462 /* for safety's sake, launch new logger *first* */
2463 SysLoggerPID = SysLogger_Start();
2464 if (!EXIT_STATUS_0(exitstatus))
2465 LogChildExit(LOG, _("system logger process"),
2471 * Else do standard backend child cleanup.
2473 CleanupBackend(pid, exitstatus);
2474 } /* loop over pending child-death reports */
2477 * After cleaning out the SIGCHLD queue, see if we have any state changes
2478 * or actions to make.
2480 PostmasterStateMachine();
2482 /* Done with signal handler */
2483 PG_SETMASK(&UnBlockSig);
2490 * CleanupBackend -- cleanup after terminated backend.
2492 * Remove all local state associated with backend.
2495 CleanupBackend(int pid,
2496 int exitstatus) /* child's exit status. */
2500 LogChildExit(DEBUG2, _("server process"), pid, exitstatus);
2503 * If a backend dies in an ugly way then we must signal all other backends
2504 * to quickdie. If exit status is zero (normal) or one (FATAL exit), we
2505 * assume everything is all right and proceed to remove the backend from
2506 * the active backend list.
2508 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2510 HandleChildCrash(pid, exitstatus, _("server process"));
2514 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2516 Backend *bp = (Backend *) DLE_VAL(curr);
2522 if (!ReleasePostmasterChildSlot(bp->child_slot))
2525 * Uh-oh, the child failed to clean itself up. Treat as a
2528 HandleChildCrash(pid, exitstatus, _("server process"));
2532 ShmemBackendArrayRemove(bp);
2543 * HandleChildCrash -- cleanup after failed backend, bgwriter, walwriter,
2546 * The objectives here are to clean up our local state about the child
2547 * process, and to signal all other remaining children to quickdie.
2550 HandleChildCrash(int pid, int exitstatus, const char *procname)
2557 * Make log entry unless there was a previous crash (if so, nonzero exit
2558 * status is to be expected in SIGQUIT response; don't clutter log)
2562 LogChildExit(LOG, procname, pid, exitstatus);
2564 (errmsg("terminating any other active server processes")));
2567 /* Process regular backends */
2568 for (curr = DLGetHead(BackendList); curr; curr = next)
2570 next = DLGetSucc(curr);
2571 bp = (Backend *) DLE_VAL(curr);
2575 * Found entry for freshly-dead backend, so remove it.
2579 (void) ReleasePostmasterChildSlot(bp->child_slot);
2581 ShmemBackendArrayRemove(bp);
2586 /* Keep looping so we can signal remaining backends */
2591 * This backend is still alive. Unless we did so already, tell it
2592 * to commit hara-kiri.
2594 * SIGQUIT is the special signal that says exit without proc_exit
2595 * and let the user know what's going on. But if SendStop is set
2596 * (-s on command line), then we send SIGSTOP instead, so that we
2597 * can get core dumps from all backends by hand.
2599 * We could exclude dead_end children here, but at least in the
2600 * SIGSTOP case it seems better to include them.
2605 (errmsg_internal("sending %s to process %d",
2606 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2608 signal_child(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
2613 /* Take care of the startup process too */
2614 if (pid == StartupPID)
2616 else if (StartupPID != 0 && !FatalError)
2619 (errmsg_internal("sending %s to process %d",
2620 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2621 (int) StartupPID)));
2622 signal_child(StartupPID, (SendStop ? SIGSTOP : SIGQUIT));
2625 /* Take care of the bgwriter too */
2626 if (pid == BgWriterPID)
2628 else if (BgWriterPID != 0 && !FatalError)
2631 (errmsg_internal("sending %s to process %d",
2632 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2633 (int) BgWriterPID)));
2634 signal_child(BgWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
2637 /* Take care of the walwriter too */
2638 if (pid == WalWriterPID)
2640 else if (WalWriterPID != 0 && !FatalError)
2643 (errmsg_internal("sending %s to process %d",
2644 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2645 (int) WalWriterPID)));
2646 signal_child(WalWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
2649 /* Take care of the autovacuum launcher too */
2650 if (pid == AutoVacPID)
2652 else if (AutoVacPID != 0 && !FatalError)
2655 (errmsg_internal("sending %s to process %d",
2656 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2657 (int) AutoVacPID)));
2658 signal_child(AutoVacPID, (SendStop ? SIGSTOP : SIGQUIT));
2662 * Force a power-cycle of the pgarch process too. (This isn't absolutely
2663 * necessary, but it seems like a good idea for robustness, and it
2664 * simplifies the state-machine logic in the case where a shutdown request
2665 * arrives during crash processing.)
2667 if (PgArchPID != 0 && !FatalError)
2670 (errmsg_internal("sending %s to process %d",
2673 signal_child(PgArchPID, SIGQUIT);
2677 * Force a power-cycle of the pgstat process too. (This isn't absolutely
2678 * necessary, but it seems like a good idea for robustness, and it
2679 * simplifies the state-machine logic in the case where a shutdown request
2680 * arrives during crash processing.)
2682 if (PgStatPID != 0 && !FatalError)
2685 (errmsg_internal("sending %s to process %d",
2688 signal_child(PgStatPID, SIGQUIT);
2689 allow_immediate_pgstat_restart();
2692 /* We do NOT restart the syslogger */
2695 /* We now transit into a state of waiting for children to die */
2696 if (pmState == PM_RECOVERY ||
2697 pmState == PM_RECOVERY_CONSISTENT ||
2698 pmState == PM_RUN ||
2699 pmState == PM_WAIT_BACKUP ||
2700 pmState == PM_SHUTDOWN)
2701 pmState = PM_WAIT_BACKENDS;
2705 * Log the death of a child process.
2708 LogChildExit(int lev, const char *procname, int pid, int exitstatus)
2710 if (WIFEXITED(exitstatus))
2714 translator: %s is a noun phrase describing a child process, such as
2716 (errmsg("%s (PID %d) exited with exit code %d",
2717 procname, pid, WEXITSTATUS(exitstatus))));
2718 else if (WIFSIGNALED(exitstatus))
2723 translator: %s is a noun phrase describing a child process, such as
2725 (errmsg("%s (PID %d) was terminated by exception 0x%X",
2726 procname, pid, WTERMSIG(exitstatus)),
2727 errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value.")));
2728 #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST
2732 translator: %s is a noun phrase describing a child process, such as
2734 (errmsg("%s (PID %d) was terminated by signal %d: %s",
2735 procname, pid, WTERMSIG(exitstatus),
2736 WTERMSIG(exitstatus) < NSIG ?
2737 sys_siglist[WTERMSIG(exitstatus)] : "(unknown)")));
2742 translator: %s is a noun phrase describing a child process, such as
2744 (errmsg("%s (PID %d) was terminated by signal %d",
2745 procname, pid, WTERMSIG(exitstatus))));
2751 translator: %s is a noun phrase describing a child process, such as
2753 (errmsg("%s (PID %d) exited with unrecognized status %d",
2754 procname, pid, exitstatus)));
2758 * Advance the postmaster's state machine and take actions as appropriate
2760 * This is common code for pmdie() and reaper(), which receive the signals
2761 * that might mean we need to change state.
2764 PostmasterStateMachine(void)
2766 if (pmState == PM_WAIT_BACKUP)
2769 * PM_WAIT_BACKUP state ends when online backup mode is not active.
2771 if (!BackupInProgress())
2772 pmState = PM_WAIT_BACKENDS;
2776 * If we are in a state-machine state that implies waiting for backends to
2777 * exit, see if they're all gone, and change state if so.
2779 if (pmState == PM_WAIT_BACKENDS)
2782 * PM_WAIT_BACKENDS state ends when we have no regular backends
2783 * (including autovac workers) and no walwriter or autovac launcher.
2784 * If we are doing crash recovery then we expect the bgwriter to exit
2785 * too, otherwise not. The archiver, stats, and syslogger processes
2786 * are disregarded since they are not connected to shared memory; we
2787 * also disregard dead_end children here.
2789 if (CountChildren() == 0 &&
2791 (BgWriterPID == 0 || !FatalError) &&
2792 WalWriterPID == 0 &&
2798 * Start waiting for dead_end children to die. This state
2799 * change causes ServerLoop to stop creating new ones.
2801 pmState = PM_WAIT_DEAD_END;
2804 * We already SIGQUIT'd the archiver and stats processes, if
2805 * any, when we entered FatalError state.
2811 * If we get here, we are proceeding with normal shutdown. All
2812 * the regular children are gone, and it's time to tell the
2813 * bgwriter to do a shutdown checkpoint.
2815 Assert(Shutdown > NoShutdown);
2816 /* Start the bgwriter if not running */
2817 if (BgWriterPID == 0)
2818 BgWriterPID = StartBackgroundWriter();
2819 /* And tell it to shut down */
2820 if (BgWriterPID != 0)
2822 signal_child(BgWriterPID, SIGUSR2);
2823 pmState = PM_SHUTDOWN;
2828 * If we failed to fork a bgwriter, just shut down. Any
2829 * required cleanup will happen at next restart. We set
2830 * FatalError so that an "abnormal shutdown" message gets
2831 * logged when we exit.
2834 pmState = PM_WAIT_DEAD_END;
2836 /* Kill the archiver and stats collector too */
2838 signal_child(PgArchPID, SIGQUIT);
2840 signal_child(PgStatPID, SIGQUIT);
2846 if (pmState == PM_WAIT_DEAD_END)
2849 * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
2850 * (ie, no dead_end children remain), and the archiver and stats
2851 * collector are gone too.
2853 * The reason we wait for those two is to protect them against a new
2854 * postmaster starting conflicting subprocesses; this isn't an
2855 * ironclad protection, but it at least helps in the
2856 * shutdown-and-immediately-restart scenario. Note that they have
2857 * already been sent appropriate shutdown signals, either during a
2858 * normal state transition leading up to PM_WAIT_DEAD_END, or during
2859 * FatalError processing.
2861 if (DLGetHead(BackendList) == NULL &&
2862 PgArchPID == 0 && PgStatPID == 0)
2864 /* These other guys should be dead already */
2865 Assert(StartupPID == 0);
2866 Assert(BgWriterPID == 0);
2867 Assert(WalWriterPID == 0);
2868 Assert(AutoVacPID == 0);
2869 /* syslogger is not considered here */
2870 pmState = PM_NO_CHILDREN;
2875 * If we've been told to shut down, we exit as soon as there are no
2876 * remaining children. If there was a crash, cleanup will occur at the
2877 * next startup. (Before PostgreSQL 8.3, we tried to recover from the
2878 * crash before exiting, but that seems unwise if we are quitting because
2879 * we got SIGTERM from init --- there may well not be time for recovery
2880 * before init decides to SIGKILL us.)
2882 * Note that the syslogger continues to run. It will exit when it sees
2883 * EOF on its input pipe, which happens when there are no more upstream
2886 if (Shutdown > NoShutdown && pmState == PM_NO_CHILDREN)
2890 ereport(LOG, (errmsg("abnormal database system shutdown")));
2896 * Terminate backup mode to avoid recovery after a clean fast
2901 /* Normal exit from the postmaster is here */
2907 * If recovery failed, wait for all non-syslogger children to exit, and
2908 * then exit postmaster. We don't try to reinitialize when recovery fails,
2909 * because more than likely it will just fail again and we will keep
2912 if (RecoveryError && pmState == PM_NO_CHILDREN)
2916 * If we need to recover from a crash, wait for all non-syslogger children
2917 * to exit, then reset shmem and StartupDataBase.
2919 if (FatalError && pmState == PM_NO_CHILDREN)
2922 (errmsg("all server processes terminated; reinitializing")));
2925 reset_shared(PostPortNumber);
2927 StartupPID = StartupDataBase();
2928 Assert(StartupPID != 0);
2929 pmState = PM_STARTUP;
2935 * Send a signal to a postmaster child process
2937 * On systems that have setsid(), each child process sets itself up as a
2938 * process group leader. For signals that are generally interpreted in the
2939 * appropriate fashion, we signal the entire process group not just the
2940 * direct child process. This allows us to, for example, SIGQUIT a blocked
2941 * archive_recovery script, or SIGINT a script being run by a backend via
2944 * There is a race condition for recently-forked children: they might not
2945 * have executed setsid() yet. So we signal the child directly as well as
2946 * the group. We assume such a child will handle the signal before trying
2947 * to spawn any grandchild processes. We also assume that signaling the
2948 * child twice will not cause any problems.
2951 signal_child(pid_t pid, int signal)
2953 if (kill(pid, signal) < 0)
2954 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
2962 if (kill(-pid, signal) < 0)
2963 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) (-pid), signal);
2972 * Send a signal to all backend children, including autovacuum workers
2973 * (but NOT special children; dead_end children are never signaled, either).
2974 * If only_autovac is TRUE, only the autovacuum worker processes are signalled.
2977 SignalSomeChildren(int signal, bool only_autovac)
2981 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2983 Backend *bp = (Backend *) DLE_VAL(curr);
2987 if (only_autovac && !bp->is_autovacuum)
2991 (errmsg_internal("sending signal %d to process %d",
2992 signal, (int) bp->pid)));
2993 signal_child(bp->pid, signal);
2998 * BackendStartup -- start backend process
3000 * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
3002 * Note: if you change this code, also consider StartAutovacuumWorker.
3005 BackendStartup(Port *port)
3007 Backend *bn; /* for backend cleanup */
3011 * Create backend data structure. Better before the fork() so we can
3012 * handle failure cleanly.
3014 bn = (Backend *) malloc(sizeof(Backend));
3018 (errcode(ERRCODE_OUT_OF_MEMORY),
3019 errmsg("out of memory")));
3020 return STATUS_ERROR;
3024 * Compute the cancel key that will be assigned to this backend. The
3025 * backend will have its own copy in the forked-off process' value of
3026 * MyCancelKey, so that it can transmit the key to the frontend.
3028 MyCancelKey = PostmasterRandom();
3029 bn->cancel_key = MyCancelKey;
3031 /* Pass down canAcceptConnections state */
3032 port->canAcceptConnections = canAcceptConnections();
3033 bn->dead_end = (port->canAcceptConnections != CAC_OK &&
3034 port->canAcceptConnections != CAC_WAITBACKUP);
3037 * Unless it's a dead_end child, assign it a child slot number
3040 bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
3045 pid = backend_forkexec(port);
3046 #else /* !EXEC_BACKEND */
3047 pid = fork_process();
3048 if (pid == 0) /* child */
3053 * Let's clean up ourselves as the postmaster child, and close the
3054 * postmaster's listen sockets. (In EXEC_BACKEND case this is all
3055 * done in SubPostmasterMain.)
3057 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
3059 MyProcPid = getpid(); /* reset MyProcPid */
3061 MyStartTime = time(NULL);
3063 /* We don't want the postmaster's proc_exit() handlers */
3066 /* Close the postmaster's sockets */
3067 ClosePostmasterPorts(false);
3069 /* Perform additional initialization and collect startup packet */
3070 BackendInitialize(port);
3072 /* And run the backend */
3073 proc_exit(BackendRun(port));
3075 #endif /* EXEC_BACKEND */
3079 /* in parent, fork failed */
3080 int save_errno = errno;
3083 (void) ReleasePostmasterChildSlot(bn->child_slot);
3087 (errmsg("could not fork new process for connection: %m")));
3088 report_fork_failure_to_client(port, save_errno);
3089 return STATUS_ERROR;
3092 /* in parent, successful fork */
3094 (errmsg_internal("forked new backend, pid=%d socket=%d",
3095 (int) pid, port->sock)));
3098 * Everything's been successful, it's safe to add this backend to our list
3102 bn->is_autovacuum = false;
3103 DLInitElem(&bn->elem, bn);
3104 DLAddHead(BackendList, &bn->elem);
3107 ShmemBackendArrayAdd(bn);
3114 * Try to report backend fork() failure to client before we close the
3115 * connection. Since we do not care to risk blocking the postmaster on
3116 * this connection, we set the connection to non-blocking and try only once.
3118 * This is grungy special-purpose code; we cannot use backend libpq since
3119 * it's not up and running.
3122 report_fork_failure_to_client(Port *port, int errnum)
3127 /* Format the error message packet (always V2 protocol) */
3128 snprintf(buffer, sizeof(buffer), "E%s%s\n",
3129 _("could not fork new process for connection: "),
3132 /* Set port to non-blocking. Don't do send() if this fails */
3133 if (!pg_set_noblock(port->sock))
3136 /* We'll retry after EINTR, but ignore all other failures */
3139 rc = send(port->sock, buffer, strlen(buffer) + 1, 0);
3140 } while (rc < 0 && errno == EINTR);
3145 * BackendInitialize -- initialize an interactive (postmaster-child)
3146 * backend process, and collect the client's startup packet.
3148 * returns: nothing. Will not return at all if there's any failure.
3150 * Note: this code does not depend on having any access to shared memory.
3151 * In the EXEC_BACKEND case, we are physically attached to shared memory
3152 * but have not yet set up most of our local pointers to shmem structures.
3155 BackendInitialize(Port *port)
3158 char remote_host[NI_MAXHOST];
3159 char remote_port[NI_MAXSERV];
3160 char remote_ps_data[NI_MAXHOST];
3162 /* Save port etc. for ps status */
3166 * PreAuthDelay is a debugging aid for investigating problems in the
3167 * authentication cycle: it can be set in postgresql.conf to allow time to
3168 * attach to the newly-forked backend with a debugger. (See also
3169 * PostAuthDelay, which we allow clients to pass through PGOPTIONS, but
3170 * it is not honored until after authentication.)
3172 if (PreAuthDelay > 0)
3173 pg_usleep(PreAuthDelay * 1000000L);
3175 /* This flag will remain set until InitPostgres finishes authentication */
3176 ClientAuthInProgress = true; /* limit visibility of log messages */
3178 /* save process start time */
3179 port->SessionStartTime = GetCurrentTimestamp();
3180 MyStartTime = timestamptz_to_time_t(port->SessionStartTime);
3182 /* set these to empty in case they are needed before we set them up */
3183 port->remote_host = "";
3184 port->remote_port = "";
3187 * Initialize libpq and enable reporting of ereport errors to the client.
3188 * Must do this now because authentication uses libpq to send messages.
3190 pq_init(); /* initialize libpq to talk to client */
3191 whereToSendOutput = DestRemote; /* now safe to ereport to client */
3194 * If possible, make this process a group leader, so that the postmaster
3195 * can signal any child processes too. (We do this now on the off chance
3196 * that something might spawn a child process during authentication.)
3200 elog(FATAL, "setsid() failed: %m");
3204 * We arrange for a simple exit(1) if we receive SIGTERM or SIGQUIT
3205 * or timeout while trying to collect the startup packet. Otherwise the
3206 * postmaster cannot shutdown the database FAST or IMMED cleanly if a
3207 * buggy client fails to send the packet promptly.
3209 pqsignal(SIGTERM, startup_die);
3210 pqsignal(SIGQUIT, startup_die);
3211 pqsignal(SIGALRM, startup_die);
3212 PG_SETMASK(&StartupBlockSig);
3215 * Get the remote host name and port for logging and status display.
3217 remote_host[0] = '\0';
3218 remote_port[0] = '\0';
3219 if (pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
3220 remote_host, sizeof(remote_host),
3221 remote_port, sizeof(remote_port),
3222 (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV))
3224 int ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
3225 remote_host, sizeof(remote_host),
3226 remote_port, sizeof(remote_port),
3227 NI_NUMERICHOST | NI_NUMERICSERV);
3231 (errmsg_internal("pg_getnameinfo_all() failed: %s",
3232 gai_strerror(ret))));
3234 snprintf(remote_ps_data, sizeof(remote_ps_data),
3235 remote_port[0] == '\0' ? "%s" : "%s(%s)",
3236 remote_host, remote_port);
3238 if (Log_connections)
3240 (errmsg("connection received: host=%s%s%s",
3241 remote_host, remote_port[0] ? " port=" : "",
3245 * save remote_host and remote_port in port structure
3247 port->remote_host = strdup(remote_host);
3248 port->remote_port = strdup(remote_port);
3251 * Ready to begin client interaction. We will give up and exit(1) after a
3252 * time delay, so that a broken client can't hog a connection
3253 * indefinitely. PreAuthDelay and any DNS interactions above don't count
3254 * against the time limit.
3256 if (!enable_sig_alarm(AuthenticationTimeout * 1000, false))
3257 elog(FATAL, "could not set timer for startup packet timeout");
3260 * Receive the startup packet (which might turn out to be a cancel request
3263 status = ProcessStartupPacket(port, false);
3266 * Stop here if it was bad or a cancel packet. ProcessStartupPacket
3267 * already did any appropriate error reporting.
3269 if (status != STATUS_OK)
3273 * Now that we have the user and database name, we can set the process
3274 * title for ps. It's good to do this as early as possible in startup.
3276 init_ps_display(port->user_name, port->database_name, remote_ps_data,
3277 update_process_title ? "authentication" : "");
3280 * Disable the timeout, and prevent SIGTERM/SIGQUIT again.
3282 if (!disable_sig_alarm(false))
3283 elog(FATAL, "could not disable timer for startup packet timeout");
3284 PG_SETMASK(&BlockSig);
3289 * BackendRun -- set up the backend's argument list and invoke PostgresMain()
3292 * Shouldn't return at all.
3293 * If PostgresMain() fails, return status.
3296 BackendRun(Port *port)
3306 * Don't want backend to be able to see the postmaster random number
3307 * generator state. We have to clobber the static random_seed *and* start
3308 * a new random sequence in the random() library function.
3311 random_start_time.tv_usec = 0;
3312 /* slightly hacky way to get integer microseconds part of timestamptz */
3313 TimestampDifference(0, port->SessionStartTime, &secs, &usecs);
3314 srandom((unsigned int) (MyProcPid ^ usecs));
3317 * Now, build the argv vector that will be given to PostgresMain.
3319 * The maximum possible number of commandline arguments that could come
3320 * from ExtraOptions is (strlen(ExtraOptions) + 1) / 2; see
3323 maxac = 5; /* for fixed args supplied below */
3324 maxac += (strlen(ExtraOptions) + 1) / 2;
3326 av = (char **) MemoryContextAlloc(TopMemoryContext,
3327 maxac * sizeof(char *));
3330 av[ac++] = "postgres";
3333 * Pass any backend switches specified with -o on the postmaster's own
3334 * command line. We assume these are secure. (It's OK to mangle
3335 * ExtraOptions now, since we're safely inside a subprocess.)
3337 pg_split_opts(av, &ac, ExtraOptions);
3340 * Tell the backend which database to use.
3342 av[ac++] = port->database_name;
3349 * Debug: print arguments being passed to backend
3352 (errmsg_internal("%s child[%d]: starting with (",
3353 progname, (int) getpid())));
3354 for (i = 0; i < ac; ++i)
3356 (errmsg_internal("\t%s", av[i])));
3358 (errmsg_internal(")")));
3361 * Make sure we aren't in PostmasterContext anymore. (We can't delete it
3362 * just yet, though, because InitPostgres will need the HBA data.)
3364 MemoryContextSwitchTo(TopMemoryContext);
3366 return (PostgresMain(ac, av, port->user_name));
3373 * postmaster_forkexec -- fork and exec a postmaster subprocess
3375 * The caller must have set up the argv array already, except for argv[2]
3376 * which will be filled with the name of the temp variable file.
3378 * Returns the child process PID, or -1 on fork failure (a suitable error
3379 * message has been logged on failure).
3381 * All uses of this routine will dispatch to SubPostmasterMain in the
3385 postmaster_forkexec(int argc, char *argv[])
3389 /* This entry point passes dummy values for the Port variables */
3390 memset(&port, 0, sizeof(port));
3391 return internal_forkexec(argc, argv, &port);
3395 * backend_forkexec -- fork/exec off a backend process
3397 * Some operating systems (WIN32) don't have fork() so we have to simulate
3398 * it by storing parameters that need to be passed to the child and
3399 * then create a new child process.
3401 * returns the pid of the fork/exec'd process, or -1 on failure
3404 backend_forkexec(Port *port)
3409 av[ac++] = "postgres";
3410 av[ac++] = "--forkbackend";
3411 av[ac++] = NULL; /* filled in by internal_forkexec */
3414 Assert(ac < lengthof(av));
3416 return internal_forkexec(ac, av, port);
3422 * internal_forkexec non-win32 implementation
3424 * - writes out backend variables to the parameter file
3425 * - fork():s, and then exec():s the child process
3428 internal_forkexec(int argc, char *argv[], Port *port)
3430 static unsigned long tmpBackendFileNum = 0;
3432 char tmpfilename[MAXPGPATH];
3433 BackendParameters param;
3436 if (!save_backend_variables(¶m, port))
3437 return -1; /* log made by save_backend_variables */
3439 /* Calculate name for temp file */
3440 snprintf(tmpfilename, MAXPGPATH, "%s/%s.backend_var.%d.%lu",
3441 PG_TEMP_FILES_DIR, PG_TEMP_FILE_PREFIX,
3442 MyProcPid, ++tmpBackendFileNum);
3445 fp = AllocateFile(tmpfilename, PG_BINARY_W);
3448 /* As in OpenTemporaryFile, try to make the temp-file directory */
3449 mkdir(PG_TEMP_FILES_DIR, S_IRWXU);
3451 fp = AllocateFile(tmpfilename, PG_BINARY_W);
3455 (errcode_for_file_access(),
3456 errmsg("could not create file \"%s\": %m",
3462 if (fwrite(¶m, sizeof(param), 1, fp) != 1)
3465 (errcode_for_file_access(),
3466 errmsg("could not write to file \"%s\": %m", tmpfilename)));
3475 (errcode_for_file_access(),
3476 errmsg("could not write to file \"%s\": %m", tmpfilename)));
3480 /* Make sure caller set up argv properly */
3482 Assert(argv[argc] == NULL);
3483 Assert(strncmp(argv[1], "--fork", 6) == 0);
3484 Assert(argv[2] == NULL);
3486 /* Insert temp file name after --fork argument */
3487 argv[2] = tmpfilename;
3489 /* Fire off execv in child */
3490 if ((pid = fork_process()) == 0)
3492 if (execv(postgres_exec_path, argv) < 0)
3495 (errmsg("could not execute server process \"%s\": %m",
3496 postgres_exec_path)));
3497 /* We're already in the child process here, can't return */
3502 return pid; /* Parent returns pid, or -1 on fork failure */
3507 * internal_forkexec win32 implementation
3509 * - starts backend using CreateProcess(), in suspended state
3510 * - writes out backend variables to the parameter file
3511 * - during this, duplicates handles and sockets required for
3512 * inheritance into the new process
3513 * - resumes execution of the new process once the backend parameter
3517 internal_forkexec(int argc, char *argv[], Port *port)
3520 PROCESS_INFORMATION pi;
3523 char cmdLine[MAXPGPATH * 2];
3525 BackendParameters *param;
3526 SECURITY_ATTRIBUTES sa;
3527 char paramHandleStr[32];
3528 win32_deadchild_waitinfo *childinfo;
3530 /* Make sure caller set up argv properly */
3532 Assert(argv[argc] == NULL);
3533 Assert(strncmp(argv[1], "--fork", 6) == 0);
3534 Assert(argv[2] == NULL);
3536 /* Set up shared memory for parameter passing */
3537 ZeroMemory(&sa, sizeof(sa));
3538 sa.nLength = sizeof(sa);
3539 sa.bInheritHandle = TRUE;
3540 paramHandle = CreateFileMapping(INVALID_HANDLE_VALUE,
3544 sizeof(BackendParameters),
3546 if (paramHandle == INVALID_HANDLE_VALUE)
3548 elog(LOG, "could not create backend parameter file mapping: error code %d",
3549 (int) GetLastError());
3553 param = MapViewOfFile(paramHandle, FILE_MAP_WRITE, 0, 0, sizeof(BackendParameters));
3556 elog(LOG, "could not map backend parameter memory: error code %d",
3557 (int) GetLastError());
3558 CloseHandle(paramHandle);
3562 /* Insert temp file name after --fork argument */
3563 sprintf(paramHandleStr, "%lu", (DWORD) paramHandle);
3564 argv[2] = paramHandleStr;
3566 /* Format the cmd line */
3567 cmdLine[sizeof(cmdLine) - 1] = '\0';
3568 cmdLine[sizeof(cmdLine) - 2] = '\0';
3569 snprintf(cmdLine, sizeof(cmdLine) - 1, "\"%s\"", postgres_exec_path);
3571 while (argv[++i] != NULL)
3573 j = strlen(cmdLine);
3574 snprintf(cmdLine + j, sizeof(cmdLine) - 1 - j, " \"%s\"", argv[i]);
3576 if (cmdLine[sizeof(cmdLine) - 2] != '\0')
3578 elog(LOG, "subprocess command line too long");
3582 memset(&pi, 0, sizeof(pi));
3583 memset(&si, 0, sizeof(si));
3587 * Create the subprocess in a suspended state. This will be resumed later,
3588 * once we have written out the parameter file.
3590 if (!CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, CREATE_SUSPENDED,
3591 NULL, NULL, &si, &pi))
3593 elog(LOG, "CreateProcess call failed: %m (error code %d)",
3594 (int) GetLastError());
3598 if (!save_backend_variables(param, port, pi.hProcess, pi.dwProcessId))
3601 * log made by save_backend_variables, but we have to clean up the
3602 * mess with the half-started process
3604 if (!TerminateProcess(pi.hProcess, 255))
3606 (errmsg_internal("could not terminate unstarted process: error code %d",
3607 (int) GetLastError())));
3608 CloseHandle(pi.hProcess);
3609 CloseHandle(pi.hThread);
3610 return -1; /* log made by save_backend_variables */
3613 /* Drop the parameter shared memory that is now inherited to the backend */
3614 if (!UnmapViewOfFile(param))
3615 elog(LOG, "could not unmap view of backend parameter file: error code %d",
3616 (int) GetLastError());
3617 if (!CloseHandle(paramHandle))
3618 elog(LOG, "could not close handle to backend parameter file: error code %d",
3619 (int) GetLastError());
3622 * Reserve the memory region used by our main shared memory segment before we
3623 * resume the child process.
3625 if (!pgwin32_ReserveSharedMemoryRegion(pi.hProcess))
3628 * Failed to reserve the memory, so terminate the newly created
3629 * process and give up.
3631 if (!TerminateProcess(pi.hProcess, 255))
3633 (errmsg_internal("could not terminate process that failed to reserve memory: error code %d",
3634 (int) GetLastError())));
3635 CloseHandle(pi.hProcess);
3636 CloseHandle(pi.hThread);
3637 return -1; /* logging done made by pgwin32_ReserveSharedMemoryRegion() */
3641 * Now that the backend variables are written out, we start the child
3642 * thread so it can start initializing while we set up the rest of the
3645 if (ResumeThread(pi.hThread) == -1)
3647 if (!TerminateProcess(pi.hProcess, 255))
3650 (errmsg_internal("could not terminate unstartable process: error code %d",
3651 (int) GetLastError())));
3652 CloseHandle(pi.hProcess);
3653 CloseHandle(pi.hThread);
3656 CloseHandle(pi.hProcess);
3657 CloseHandle(pi.hThread);
3659 (errmsg_internal("could not resume thread of unstarted process: error code %d",
3660 (int) GetLastError())));
3665 * Queue a waiter for to signal when this child dies. The wait will be
3666 * handled automatically by an operating system thread pool.
3668 * Note: use malloc instead of palloc, since it needs to be thread-safe.
3669 * Struct will be free():d from the callback function that runs on a
3672 childinfo = malloc(sizeof(win32_deadchild_waitinfo));
3675 (errcode(ERRCODE_OUT_OF_MEMORY),
3676 errmsg("out of memory")));
3678 childinfo->procHandle = pi.hProcess;
3679 childinfo->procId = pi.dwProcessId;
3681 if (!RegisterWaitForSingleObject(&childinfo->waitHandle,
3683 pgwin32_deadchild_callback,
3686 WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD))
3688 (errmsg_internal("could not register process for wait: error code %d",
3689 (int) GetLastError())));
3691 /* Don't close pi.hProcess here - the wait thread needs access to it */
3693 CloseHandle(pi.hThread);
3695 return pi.dwProcessId;
3701 * SubPostmasterMain -- Get the fork/exec'd process into a state equivalent
3702 * to what it would be if we'd simply forked on Unix, and then
3703 * dispatch to the appropriate place.
3705 * The first two command line arguments are expected to be "--forkFOO"
3706 * (where FOO indicates which postmaster child we are to become), and
3707 * the name of a variables file that we can read to load data that would
3708 * have been inherited by fork() on Unix. Remaining arguments go to the
3709 * subprocess FooMain() routine.
3712 SubPostmasterMain(int argc, char *argv[])
3716 /* Do this sooner rather than later... */
3717 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
3719 MyProcPid = getpid(); /* reset MyProcPid */
3721 MyStartTime = time(NULL);
3724 * make sure stderr is in binary mode before anything can possibly be
3725 * written to it, in case it's actually the syslogger pipe, so the pipe
3726 * chunking protocol isn't disturbed. Non-logpipe data gets translated on
3727 * redirection (e.g. via pg_ctl -l) anyway.
3730 _setmode(fileno(stderr), _O_BINARY);
3733 /* Lose the postmaster's on-exit routines (really a no-op) */
3736 /* In EXEC_BACKEND case we will not have inherited these settings */
3737 IsPostmasterEnvironment = true;
3738 whereToSendOutput = DestNone;
3740 /* Setup essential subsystems (to ensure elog() behaves sanely) */
3741 MemoryContextInit();
3742 InitializeGUCOptions();
3744 /* Read in the variables file */
3745 memset(&port, 0, sizeof(Port));
3746 read_backend_variables(argv[2], &port);
3749 * Set up memory area for GSS information. Mirrors the code in ConnCreate
3750 * for the non-exec case.
3752 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
3753 port.gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
3756 (errcode(ERRCODE_OUT_OF_MEMORY),
3757 errmsg("out of memory")));
3760 /* Check we got appropriate args */
3762 elog(FATAL, "invalid subpostmaster invocation");
3765 * If appropriate, physically re-attach to shared memory segment. We want
3766 * to do this before going any further to ensure that we can attach at the
3767 * same address the postmaster used.
3769 if (strcmp(argv[1], "--forkbackend") == 0 ||
3770 strcmp(argv[1], "--forkavlauncher") == 0 ||
3771 strcmp(argv[1], "--forkavworker") == 0 ||
3772 strcmp(argv[1], "--forkboot") == 0)
3773 PGSharedMemoryReAttach();
3775 /* autovacuum needs this set before calling InitProcess */
3776 if (strcmp(argv[1], "--forkavlauncher") == 0)
3777 AutovacuumLauncherIAm();
3778 if (strcmp(argv[1], "--forkavworker") == 0)
3779 AutovacuumWorkerIAm();
3782 * Start our win32 signal implementation. This has to be done after we
3783 * read the backend variables, because we need to pick up the signal pipe
3784 * from the parent process.
3787 pgwin32_signal_initialize();
3790 /* In EXEC_BACKEND case we will not have inherited these settings */
3792 PG_SETMASK(&BlockSig);
3794 /* Read in remaining GUC variables */
3795 read_nondefault_variables();
3798 * Reload any libraries that were preloaded by the postmaster. Since we
3799 * exec'd this process, those libraries didn't come along with us; but we
3800 * should load them into all child processes to be consistent with the
3801 * non-EXEC_BACKEND behavior.
3803 process_shared_preload_libraries();
3805 /* Run backend or appropriate child */
3806 if (strcmp(argv[1], "--forkbackend") == 0)
3808 Assert(argc == 3); /* shouldn't be any more args */
3810 /* Close the postmaster's sockets */
3811 ClosePostmasterPorts(false);
3814 * Need to reinitialize the SSL library in the backend, since the
3815 * context structures contain function pointers and cannot be passed
3816 * through the parameter file.
3818 * XXX should we do this in all child processes? For the moment it's
3819 * enough to do it in backend children.
3823 secure_initialize();
3827 * Perform additional initialization and collect startup packet.
3829 * We want to do this before InitProcess() for a couple of reasons: 1.
3830 * so that we aren't eating up a PGPROC slot while waiting on the
3831 * client. 2. so that if InitProcess() fails due to being out of
3832 * PGPROC slots, we have already initialized libpq and are able to
3833 * report the error to the client.
3835 BackendInitialize(&port);
3837 /* Restore basic shared memory pointers */
3838 InitShmemAccess(UsedShmemSegAddr);
3840 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3844 * Attach process to shared data structures. If testing EXEC_BACKEND
3845 * on Linux, you must run this as root before starting the postmaster:
3847 * echo 0 >/proc/sys/kernel/randomize_va_space
3849 * This prevents a randomized stack base address that causes child
3850 * shared memory to be at a different address than the parent, making
3851 * it impossible to attached to shared memory. Return the value to
3852 * '1' when finished.
3854 CreateSharedMemoryAndSemaphores(false, 0);
3856 /* And run the backend */
3857 proc_exit(BackendRun(&port));
3859 if (strcmp(argv[1], "--forkboot") == 0)
3861 /* Close the postmaster's sockets */
3862 ClosePostmasterPorts(false);
3864 /* Restore basic shared memory pointers */
3865 InitShmemAccess(UsedShmemSegAddr);
3867 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3868 InitAuxiliaryProcess();
3870 /* Attach process to shared data structures */
3871 CreateSharedMemoryAndSemaphores(false, 0);
3873 AuxiliaryProcessMain(argc - 2, argv + 2);
3876 if (strcmp(argv[1], "--forkavlauncher") == 0)
3878 /* Close the postmaster's sockets */
3879 ClosePostmasterPorts(false);
3881 /* Restore basic shared memory pointers */
3882 InitShmemAccess(UsedShmemSegAddr);
3884 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3887 /* Attach process to shared data structures */
3888 CreateSharedMemoryAndSemaphores(false, 0);
3890 AutoVacLauncherMain(argc - 2, argv + 2);
3893 if (strcmp(argv[1], "--forkavworker") == 0)
3895 /* Close the postmaster's sockets */
3896 ClosePostmasterPorts(false);
3898 /* Restore basic shared memory pointers */
3899 InitShmemAccess(UsedShmemSegAddr);
3901 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3904 /* Attach process to shared data structures */
3905 CreateSharedMemoryAndSemaphores(false, 0);
3907 AutoVacWorkerMain(argc - 2, argv + 2);
3910 if (strcmp(argv[1], "--forkarch") == 0)
3912 /* Close the postmaster's sockets */
3913 ClosePostmasterPorts(false);
3915 /* Do not want to attach to shared memory */
3917 PgArchiverMain(argc, argv);
3920 if (strcmp(argv[1], "--forkcol") == 0)
3922 /* Close the postmaster's sockets */
3923 ClosePostmasterPorts(false);
3925 /* Do not want to attach to shared memory */
3927 PgstatCollectorMain(argc, argv);
3930 if (strcmp(argv[1], "--forklog") == 0)
3932 /* Close the postmaster's sockets */
3933 ClosePostmasterPorts(true);
3935 /* Do not want to attach to shared memory */
3937 SysLoggerMain(argc, argv);
3941 return 1; /* shouldn't get here */
3943 #endif /* EXEC_BACKEND */
3947 * ExitPostmaster -- cleanup
3949 * Do NOT call exit() directly --- always go through here!
3952 ExitPostmaster(int status)
3954 /* should cleanup shared memory and kill all backends */
3957 * Not sure of the semantics here. When the Postmaster dies, should the
3958 * backends all be killed? probably not.
3960 * MUST -- vadim 05-10-1999
3967 * sigusr1_handler - handle signal conditions from child processes
3970 sigusr1_handler(SIGNAL_ARGS)
3972 int save_errno = errno;
3974 PG_SETMASK(&BlockSig);
3977 * RECOVERY_STARTED and RECOVERY_CONSISTENT signals are ignored in
3978 * unexpected states. If the startup process quickly starts up, completes
3979 * recovery, exits, we might process the death of the startup process
3980 * first. We don't want to go back to recovery in that case.
3982 if (CheckPostmasterSignal(PMSIGNAL_RECOVERY_STARTED) &&
3983 pmState == PM_STARTUP)
3985 /* WAL redo has started. We're out of reinitialization. */
3989 * Crank up the background writer. It doesn't matter if this fails,
3990 * we'll just try again later.
3992 Assert(BgWriterPID == 0);
3993 BgWriterPID = StartBackgroundWriter();
3995 pmState = PM_RECOVERY;
3997 if (CheckPostmasterSignal(PMSIGNAL_RECOVERY_CONSISTENT) &&
3998 pmState == PM_RECOVERY)
4001 * Likewise, start other special children as needed.
4003 Assert(PgStatPID == 0);
4004 PgStatPID = pgstat_start();
4006 /* XXX at this point we could accept read-only connections */
4008 (errmsg("database system is in consistent recovery mode")));
4010 pmState = PM_RECOVERY_CONSISTENT;
4013 if (CheckPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER) &&
4017 * Send SIGUSR1 to archiver process, to wake it up and begin archiving
4018 * next transaction log file.
4020 signal_child(PgArchPID, SIGUSR1);
4023 if (CheckPostmasterSignal(PMSIGNAL_ROTATE_LOGFILE) &&
4026 /* Tell syslogger to rotate logfile */
4027 signal_child(SysLoggerPID, SIGUSR1);
4030 if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER))
4033 * Start one iteration of the autovacuum daemon, even if autovacuuming
4034 * is nominally not enabled. This is so we can have an active defense
4035 * against transaction ID wraparound. We set a flag for the main loop
4036 * to do it rather than trying to do it here --- this is because the
4037 * autovac process itself may send the signal, and we want to handle
4038 * that by launching another iteration as soon as the current one
4041 start_autovac_launcher = true;
4044 if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER))
4046 /* The autovacuum launcher wants us to start a worker process. */
4047 StartAutovacuumWorker();
4050 PG_SETMASK(&UnBlockSig);
4056 * Timeout or shutdown signal from postmaster while processing startup packet.
4057 * Cleanup and exit(1).
4059 * XXX: possible future improvement: try to send a message indicating
4060 * why we are disconnecting. Problem is to be sure we don't block while
4061 * doing so, nor mess up SSL initialization. In practice, if the client
4062 * has wedged here, it probably couldn't do anything with the message anyway.
4065 startup_die(SIGNAL_ARGS)
4071 * Dummy signal handler
4073 * We use this for signals that we don't actually use in the postmaster,
4074 * but we do use in backends. If we were to SIG_IGN such signals in the
4075 * postmaster, then a newly started backend might drop a signal that arrives
4076 * before it's able to reconfigure its signal processing. (See notes in
4080 dummy_handler(SIGNAL_ARGS)
4088 RandomSalt(char *md5Salt)
4093 * We use % 255, sacrificing one possible byte value, so as to ensure that
4094 * all bits of the random() value participate in the result. While at it,
4095 * add one to avoid generating any null bytes.
4097 rand = PostmasterRandom();
4098 md5Salt[0] = (rand % 255) + 1;
4099 rand = PostmasterRandom();
4100 md5Salt[1] = (rand % 255) + 1;
4101 rand = PostmasterRandom();
4102 md5Salt[2] = (rand % 255) + 1;
4103 rand = PostmasterRandom();
4104 md5Salt[3] = (rand % 255) + 1;
4111 PostmasterRandom(void)
4114 * Select a random seed at the time of first receiving a request.
4116 if (random_seed == 0)
4120 struct timeval random_stop_time;
4122 gettimeofday(&random_stop_time, NULL);
4125 * We are not sure how much precision is in tv_usec, so we swap
4126 * the high and low 16 bits of 'random_stop_time' and XOR them
4127 * with 'random_start_time'. On the off chance that the result is
4128 * 0, we loop until it isn't.
4130 random_seed = random_start_time.tv_usec ^
4131 ((random_stop_time.tv_usec << 16) |
4132 ((random_stop_time.tv_usec >> 16) & 0xffff));
4134 while (random_seed == 0);
4136 srandom(random_seed);
4143 * Count up number of child processes (excluding special children and
4144 * dead_end children)
4152 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
4154 Backend *bp = (Backend *) DLE_VAL(curr);
4164 * StartChildProcess -- start an auxiliary process for the postmaster
4166 * xlop determines what kind of child will be started. All child types
4167 * initially go to AuxiliaryProcessMain, which will handle common setup.
4169 * Return value of StartChildProcess is subprocess' PID, or 0 if failed
4170 * to start subprocess.
4173 StartChildProcess(AuxProcType type)
4181 * Set up command-line arguments for subprocess
4183 av[ac++] = "postgres";
4186 av[ac++] = "--forkboot";
4187 av[ac++] = NULL; /* filled in by postmaster_forkexec */
4190 snprintf(typebuf, sizeof(typebuf), "-x%d", type);
4194 Assert(ac < lengthof(av));
4197 pid = postmaster_forkexec(ac, av);
4198 #else /* !EXEC_BACKEND */
4199 pid = fork_process();
4201 if (pid == 0) /* child */
4203 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
4205 /* Close the postmaster's sockets */
4206 ClosePostmasterPorts(false);
4208 /* Lose the postmaster's on-exit routines and port connections */
4211 /* Release postmaster's working memory context */
4212 MemoryContextSwitchTo(TopMemoryContext);
4213 MemoryContextDelete(PostmasterContext);
4214 PostmasterContext = NULL;
4216 AuxiliaryProcessMain(ac, av);
4219 #endif /* EXEC_BACKEND */
4223 /* in parent, fork failed */
4224 int save_errno = errno;
4229 case StartupProcess:
4231 (errmsg("could not fork startup process: %m")));
4233 case BgWriterProcess:
4235 (errmsg("could not fork background writer process: %m")));
4237 case WalWriterProcess:
4239 (errmsg("could not fork WAL writer process: %m")));
4243 (errmsg("could not fork process: %m")));
4248 * fork failure is fatal during startup, but there's no need to choke
4249 * immediately if starting other child types fails.
4251 if (type == StartupProcess)
4257 * in parent, successful fork
4263 * StartAutovacuumWorker
4264 * Start an autovac worker process.
4266 * This function is here because it enters the resulting PID into the
4267 * postmaster's private backends list.
4269 * NB -- this code very roughly matches BackendStartup.
4272 StartAutovacuumWorker(void)
4277 * If not in condition to run a process, don't try, but handle it like a
4278 * fork failure. This does not normally happen, since the signal is only
4279 * supposed to be sent by autovacuum launcher when it's OK to do it, but
4280 * we have to check to avoid race-condition problems during DB state
4283 if (canAcceptConnections() == CAC_OK)
4285 bn = (Backend *) malloc(sizeof(Backend));
4289 * Compute the cancel key that will be assigned to this session.
4290 * We probably don't need cancel keys for autovac workers, but
4291 * we'd better have something random in the field to prevent
4292 * unfriendly people from sending cancels to them.
4294 MyCancelKey = PostmasterRandom();
4295 bn->cancel_key = MyCancelKey;
4297 /* Autovac workers are not dead_end and need a child slot */
4298 bn->dead_end = false;
4299 bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
4301 bn->pid = StartAutoVacWorker();
4304 bn->is_autovacuum = true;
4305 DLInitElem(&bn->elem, bn);
4306 DLAddHead(BackendList, &bn->elem);
4308 ShmemBackendArrayAdd(bn);
4315 * fork failed, fall through to report -- actual error message was
4316 * logged by StartAutoVacWorker
4318 (void) ReleasePostmasterChildSlot(bn->child_slot);
4323 (errcode(ERRCODE_OUT_OF_MEMORY),
4324 errmsg("out of memory")));
4328 * Report the failure to the launcher, if it's running. (If it's not, we
4329 * might not even be connected to shared memory, so don't try to call
4330 * AutoVacWorkerFailed.) Note that we also need to signal it so that it
4331 * responds to the condition, but we don't do that here, instead waiting
4332 * for ServerLoop to do it. This way we avoid a ping-pong signalling in
4333 * quick succession between the autovac launcher and postmaster in case
4336 if (AutoVacPID != 0)
4338 AutoVacWorkerFailed();
4339 avlauncher_needs_signal = true;
4344 * Create the opts file
4347 CreateOptsFile(int argc, char *argv[], char *fullprogname)
4352 #define OPTS_FILE "postmaster.opts"
4354 if ((fp = fopen(OPTS_FILE, "w")) == NULL)
4356 elog(LOG, "could not create file \"%s\": %m", OPTS_FILE);
4360 fprintf(fp, "%s", fullprogname);
4361 for (i = 1; i < argc; i++)
4362 fprintf(fp, " \"%s\"", argv[i]);
4367 elog(LOG, "could not write file \"%s\": %m", OPTS_FILE);
4376 * MaxLivePostmasterChildren
4378 * This reports the number of entries needed in per-child-process arrays
4379 * (the PMChildFlags array, and if EXEC_BACKEND the ShmemBackendArray).
4380 * These arrays include regular backends and autovac workers, but not special
4381 * children nor dead_end children. This allows the arrays to have a fixed
4382 * maximum size, to wit the same too-many-children limit enforced by
4383 * canAcceptConnections(). The exact value isn't too critical as long as
4384 * it's more than MaxBackends.
4387 MaxLivePostmasterChildren(void)
4389 return 2 * MaxBackends;
4396 * The following need to be available to the save/restore_backend_variables
4399 extern slock_t *ShmemLock;
4400 extern LWLock *LWLockArray;
4401 extern slock_t *ProcStructLock;
4402 extern PROC_HDR *ProcGlobal;
4403 extern PGPROC *AuxiliaryProcs;
4404 extern PMSignalData *PMSignalState;
4405 extern int pgStatSock;
4408 #define write_inheritable_socket(dest, src, childpid) ((*(dest) = (src)), true)
4409 #define read_inheritable_socket(dest, src) (*(dest) = *(src))
4411 static bool write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE child);
4412 static bool write_inheritable_socket(InheritableSocket *dest, SOCKET src,
4414 static void read_inheritable_socket(SOCKET *dest, InheritableSocket *src);
4418 /* Save critical backend variables into the BackendParameters struct */
4421 save_backend_variables(BackendParameters *param, Port *port)
4424 save_backend_variables(BackendParameters *param, Port *port,
4425 HANDLE childProcess, pid_t childPid)
4428 memcpy(¶m->port, port, sizeof(Port));
4429 if (!write_inheritable_socket(¶m->portsocket, port->sock, childPid))
4432 strlcpy(param->DataDir, DataDir, MAXPGPATH);
4434 memcpy(¶m->ListenSocket, &ListenSocket, sizeof(ListenSocket));
4436 param->MyCancelKey = MyCancelKey;
4437 param->MyPMChildSlot = MyPMChildSlot;
4439 param->UsedShmemSegID = UsedShmemSegID;
4440 param->UsedShmemSegAddr = UsedShmemSegAddr;
4442 param->ShmemLock = ShmemLock;
4443 param->ShmemVariableCache = ShmemVariableCache;
4444 param->ShmemBackendArray = ShmemBackendArray;
4446 param->LWLockArray = LWLockArray;
4447 param->ProcStructLock = ProcStructLock;
4448 param->ProcGlobal = ProcGlobal;
4449 param->AuxiliaryProcs = AuxiliaryProcs;
4450 param->PMSignalState = PMSignalState;
4451 if (!write_inheritable_socket(¶m->pgStatSock, pgStatSock, childPid))
4454 param->PostmasterPid = PostmasterPid;
4455 param->PgStartTime = PgStartTime;
4456 param->PgReloadTime = PgReloadTime;
4458 param->redirection_done = redirection_done;
4461 param->PostmasterHandle = PostmasterHandle;
4462 if (!write_duplicated_handle(¶m->initial_signal_pipe,
4463 pgwin32_create_signal_listener(childPid),
4468 memcpy(¶m->syslogPipe, &syslogPipe, sizeof(syslogPipe));
4470 strlcpy(param->my_exec_path, my_exec_path, MAXPGPATH);
4472 strlcpy(param->pkglib_path, pkglib_path, MAXPGPATH);
4474 strlcpy(param->ExtraOptions, ExtraOptions, MAXPGPATH);
4482 * Duplicate a handle for usage in a child process, and write the child
4483 * process instance of the handle to the parameter file.
4486 write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE childProcess)
4488 HANDLE hChild = INVALID_HANDLE_VALUE;
4490 if (!DuplicateHandle(GetCurrentProcess(),
4496 DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS))
4499 (errmsg_internal("could not duplicate handle to be written to backend parameter file: error code %d",
4500 (int) GetLastError())));
4509 * Duplicate a socket for usage in a child process, and write the resulting
4510 * structure to the parameter file.
4511 * This is required because a number of LSPs (Layered Service Providers) very
4512 * common on Windows (antivirus, firewalls, download managers etc) break
4513 * straight socket inheritance.
4516 write_inheritable_socket(InheritableSocket *dest, SOCKET src, pid_t childpid)
4518 dest->origsocket = src;
4519 if (src != 0 && src != -1)
4522 if (WSADuplicateSocket(src, childpid, &dest->wsainfo) != 0)
4525 (errmsg("could not duplicate socket %d for use in backend: error code %d",
4526 src, WSAGetLastError())));
4534 * Read a duplicate socket structure back, and get the socket descriptor.
4537 read_inheritable_socket(SOCKET *dest, InheritableSocket *src)
4541 if (src->origsocket == -1 || src->origsocket == 0)
4543 /* Not a real socket! */
4544 *dest = src->origsocket;
4548 /* Actual socket, so create from structure */
4549 s = WSASocket(FROM_PROTOCOL_INFO,
4555 if (s == INVALID_SOCKET)
4557 write_stderr("could not create inherited socket: error code %d\n",
4564 * To make sure we don't get two references to the same socket, close
4565 * the original one. (This would happen when inheritance actually
4568 closesocket(src->origsocket);
4574 read_backend_variables(char *id, Port *port)
4576 BackendParameters param;
4579 /* Non-win32 implementation reads from file */
4583 fp = AllocateFile(id, PG_BINARY_R);
4586 write_stderr("could not read from backend variables file \"%s\": %s\n",
4587 id, strerror(errno));
4591 if (fread(¶m, sizeof(param), 1, fp) != 1)
4593 write_stderr("could not read from backend variables file \"%s\": %s\n",
4594 id, strerror(errno));
4600 if (unlink(id) != 0)
4602 write_stderr("could not remove file \"%s\": %s\n",
4603 id, strerror(errno));
4607 /* Win32 version uses mapped file */
4609 BackendParameters *paramp;
4611 paramHandle = (HANDLE) atol(id);
4612 paramp = MapViewOfFile(paramHandle, FILE_MAP_READ, 0, 0, 0);
4615 write_stderr("could not map view of backend variables: error code %d\n",
4616 (int) GetLastError());
4620 memcpy(¶m, paramp, sizeof(BackendParameters));
4622 if (!UnmapViewOfFile(paramp))
4624 write_stderr("could not unmap view of backend variables: error code %d\n",
4625 (int) GetLastError());
4629 if (!CloseHandle(paramHandle))
4631 write_stderr("could not close handle to backend parameter variables: error code %d\n",
4632 (int) GetLastError());
4637 restore_backend_variables(¶m, port);
4640 /* Restore critical backend variables from the BackendParameters struct */
4642 restore_backend_variables(BackendParameters *param, Port *port)
4644 memcpy(port, ¶m->port, sizeof(Port));
4645 read_inheritable_socket(&port->sock, ¶m->portsocket);
4647 SetDataDir(param->DataDir);
4649 memcpy(&ListenSocket, ¶m->ListenSocket, sizeof(ListenSocket));
4651 MyCancelKey = param->MyCancelKey;
4652 MyPMChildSlot = param->MyPMChildSlot;
4654 UsedShmemSegID = param->UsedShmemSegID;
4655 UsedShmemSegAddr = param->UsedShmemSegAddr;
4657 ShmemLock = param->ShmemLock;
4658 ShmemVariableCache = param->ShmemVariableCache;
4659 ShmemBackendArray = param->ShmemBackendArray;
4661 LWLockArray = param->LWLockArray;
4662 ProcStructLock = param->ProcStructLock;
4663 ProcGlobal = param->ProcGlobal;
4664 AuxiliaryProcs = param->AuxiliaryProcs;
4665 PMSignalState = param->PMSignalState;
4666 read_inheritable_socket(&pgStatSock, ¶m->pgStatSock);
4668 PostmasterPid = param->PostmasterPid;
4669 PgStartTime = param->PgStartTime;
4670 PgReloadTime = param->PgReloadTime;
4672 redirection_done = param->redirection_done;
4675 PostmasterHandle = param->PostmasterHandle;
4676 pgwin32_initial_signal_pipe = param->initial_signal_pipe;
4679 memcpy(&syslogPipe, ¶m->syslogPipe, sizeof(syslogPipe));
4681 strlcpy(my_exec_path, param->my_exec_path, MAXPGPATH);
4683 strlcpy(pkglib_path, param->pkglib_path, MAXPGPATH);
4685 strlcpy(ExtraOptions, param->ExtraOptions, MAXPGPATH);
4690 ShmemBackendArraySize(void)
4692 return mul_size(MaxLivePostmasterChildren(), sizeof(Backend));
4696 ShmemBackendArrayAllocation(void)
4698 Size size = ShmemBackendArraySize();
4700 ShmemBackendArray = (Backend *) ShmemAlloc(size);
4701 /* Mark all slots as empty */
4702 memset(ShmemBackendArray, 0, size);
4706 ShmemBackendArrayAdd(Backend *bn)
4708 /* The array slot corresponding to my PMChildSlot should be free */
4709 int i = bn->child_slot - 1;
4711 Assert(ShmemBackendArray[i].pid == 0);
4712 ShmemBackendArray[i] = *bn;
4716 ShmemBackendArrayRemove(Backend *bn)
4718 int i = bn->child_slot - 1;
4720 Assert(ShmemBackendArray[i].pid == bn->pid);
4721 /* Mark the slot as empty */
4722 ShmemBackendArray[i].pid = 0;
4724 #endif /* EXEC_BACKEND */
4730 win32_waitpid(int *exitstatus)
4737 * Check if there are any dead children. If there are, return the pid of
4738 * the first one that died.
4740 if (GetQueuedCompletionStatus(win32ChildQueue, &dwd, &key, &ovl, 0))
4742 *exitstatus = (int) key;
4750 * Note! Code below executes on a thread pool! All operations must
4751 * be thread safe! Note that elog() and friends must *not* be used.
4754 pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
4756 win32_deadchild_waitinfo *childinfo = (win32_deadchild_waitinfo *) lpParameter;
4759 if (TimerOrWaitFired)
4760 return; /* timeout. Should never happen, since we use
4761 * INFINITE as timeout value. */
4764 * Remove handle from wait - required even though it's set to wait only
4767 UnregisterWaitEx(childinfo->waitHandle, NULL);
4769 if (!GetExitCodeProcess(childinfo->procHandle, &exitcode))
4772 * Should never happen. Inform user and set a fixed exitcode.
4774 write_stderr("could not read exit code for process\n");
4778 if (!PostQueuedCompletionStatus(win32ChildQueue, childinfo->procId, (ULONG_PTR) exitcode, NULL))
4779 write_stderr("could not post child completion status\n");
4782 * Handle is per-process, so we close it here instead of in the
4783 * originating thread
4785 CloseHandle(childinfo->procHandle);
4788 * Free struct that was allocated before the call to
4789 * RegisterWaitForSingleObject()
4793 /* Queue SIGCHLD signal */
4794 pg_queue_signal(SIGCHLD);