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.590 2009/08/24 20:08:32 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>
92 #include <DNSServiceDiscovery/DNSServiceDiscovery.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;
205 /* PIDs of special child processes; 0 when not running */
206 static pid_t StartupPID = 0,
214 /* Startup/shutdown state */
216 #define SmartShutdown 1
217 #define FastShutdown 2
219 static int Shutdown = NoShutdown;
221 static bool FatalError = false; /* T if recovering from backend crash */
222 static bool RecoveryError = false; /* T if WAL recovery failed */
225 * We use a simple state machine to control startup, shutdown, and
226 * crash recovery (which is rather like shutdown followed by startup).
228 * After doing all the postmaster initialization work, we enter PM_STARTUP
229 * state and the startup process is launched. The startup process begins by
230 * reading the control file and other preliminary initialization steps.
231 * In a normal startup, or after crash recovery, the startup process exits
232 * with exit code 0 and we switch to PM_RUN state. However, archive recovery
233 * is handled specially since it takes much longer and we would like to support
234 * hot standby during archive recovery.
236 * When the startup process is ready to start archive recovery, it signals the
237 * postmaster, and we switch to PM_RECOVERY state. The background writer is
238 * launched, while the startup process continues applying WAL.
239 * After reaching a consistent point in WAL redo, startup process signals
240 * us again, and we switch to PM_RECOVERY_CONSISTENT state. There's currently
241 * no difference between PM_RECOVERY and PM_RECOVERY_CONSISTENT, but we
242 * could start accepting connections to perform read-only queries at this
243 * point, if we had the infrastructure to do that.
244 * When archive recovery is finished, the startup process exits with exit
245 * code 0 and we switch to PM_RUN state.
247 * Normal child backends can only be launched when we are in PM_RUN state.
248 * (We also allow it in PM_WAIT_BACKUP state, but only for superusers.)
249 * In other states we handle connection requests by launching "dead_end"
250 * child processes, which will simply send the client an error message and
251 * quit. (We track these in the BackendList so that we can know when they
252 * are all gone; this is important because they're still connected to shared
253 * memory, and would interfere with an attempt to destroy the shmem segment,
254 * possibly leading to SHMALL failure when we try to make a new one.)
255 * In PM_WAIT_DEAD_END state we are waiting for all the dead_end children
256 * to drain out of the system, and therefore stop accepting connection
257 * requests at all until the last existing child has quit (which hopefully
258 * will not be very long).
260 * Notice that this state variable does not distinguish *why* we entered
261 * states later than PM_RUN --- Shutdown and FatalError must be consulted
262 * to find that out. FatalError is never true in PM_RECOVERY_* or PM_RUN
263 * states, nor in PM_SHUTDOWN states (because we don't enter those states
264 * when trying to recover from a crash). It can be true in PM_STARTUP state,
265 * because we don't clear it until we've successfully started WAL redo.
266 * Similarly, RecoveryError means that we have crashed during recovery, and
267 * should not try to restart.
271 PM_INIT, /* postmaster starting */
272 PM_STARTUP, /* waiting for startup subprocess */
273 PM_RECOVERY, /* in archive recovery mode */
274 PM_RECOVERY_CONSISTENT, /* consistent recovery mode */
275 PM_RUN, /* normal "database is alive" state */
276 PM_WAIT_BACKUP, /* waiting for online backup mode to end */
277 PM_WAIT_BACKENDS, /* waiting for live backends to exit */
278 PM_SHUTDOWN, /* waiting for bgwriter to do shutdown ckpt */
279 PM_SHUTDOWN_2, /* waiting for archiver to finish */
280 PM_WAIT_DEAD_END, /* waiting for dead_end children to exit */
281 PM_NO_CHILDREN /* all important children have exited */
284 static PMState pmState = PM_INIT;
286 bool ClientAuthInProgress = false; /* T during new-client
289 bool redirection_done = false; /* stderr redirected for syslogger? */
291 /* received START_AUTOVAC_LAUNCHER signal */
292 static volatile sig_atomic_t start_autovac_launcher = false;
293 /* the launcher needs to be signalled to communicate some condition */
294 static volatile bool avlauncher_needs_signal = false;
297 * State for assigning random salts and cancel keys.
298 * Also, the global MyCancelKey passes the cancel key assigned to a given
299 * backend from the postmaster to that backend (via fork).
301 static unsigned int random_seed = 0;
302 static struct timeval random_start_time;
308 #ifdef HAVE_INT_OPTRESET
309 extern int optreset; /* might not be declared by system headers */
313 * postmaster.c - function prototypes
315 static void getInstallationPaths(const char *argv0);
316 static void checkDataDir(void);
319 static void reg_reply(DNSServiceRegistrationReplyErrorType errorCode,
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 dummy_handler(SIGNAL_ARGS);
331 static void CleanupBackend(int pid, int exitstatus);
332 static void HandleChildCrash(int pid, int exitstatus, const char *procname);
333 static void LogChildExit(int lev, const char *procname,
334 int pid, int exitstatus);
335 static void PostmasterStateMachine(void);
336 static void BackendInitialize(Port *port);
337 static int BackendRun(Port *port);
338 static void ExitPostmaster(int status);
339 static int ServerLoop(void);
340 static int BackendStartup(Port *port);
341 static int ProcessStartupPacket(Port *port, bool SSLdone);
342 static void processCancelRequest(Port *port, void *pkt);
343 static int initMasks(fd_set *rmask);
344 static void report_fork_failure_to_client(Port *port, int errnum);
345 static enum CAC_state canAcceptConnections(void);
346 static long PostmasterRandom(void);
347 static void RandomSalt(char *md5Salt);
348 static void signal_child(pid_t pid, int signal);
349 static void SignalSomeChildren(int signal, bool only_autovac);
351 #define SignalChildren(sig) SignalSomeChildren(sig, false)
352 #define SignalAutovacWorkers(sig) SignalSomeChildren(sig, true)
353 static int CountChildren(void);
354 static bool CreateOptsFile(int argc, char *argv[], char *fullprogname);
355 static pid_t StartChildProcess(AuxProcType type);
356 static void StartAutovacuumWorker(void);
361 static pid_t win32_waitpid(int *exitstatus);
362 static void WINAPI pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired);
364 static HANDLE win32ChildQueue;
371 } win32_deadchild_waitinfo;
373 HANDLE PostmasterHandle;
376 static pid_t backend_forkexec(Port *port);
377 static pid_t internal_forkexec(int argc, char *argv[], Port *port);
379 /* Type for a socket that can be inherited to a client process */
383 SOCKET origsocket; /* Original socket value, or -1 if not a
385 WSAPROTOCOL_INFO wsainfo;
388 typedef int InheritableSocket;
391 typedef struct LWLock LWLock; /* ugly kluge */
394 * Structure contains all variables passed to exec:ed backends
399 InheritableSocket portsocket;
400 char DataDir[MAXPGPATH];
401 int ListenSocket[MAXLISTEN];
404 unsigned long UsedShmemSegID;
405 void *UsedShmemSegAddr;
407 VariableCache ShmemVariableCache;
408 Backend *ShmemBackendArray;
410 slock_t *ProcStructLock;
411 PROC_HDR *ProcGlobal;
412 PGPROC *AuxiliaryProcs;
413 PMSignalData *PMSignalState;
414 InheritableSocket pgStatSock;
416 TimestampTz PgStartTime;
417 TimestampTz PgReloadTime;
418 bool redirection_done;
420 HANDLE PostmasterHandle;
421 HANDLE initial_signal_pipe;
422 HANDLE syslogPipe[2];
426 char my_exec_path[MAXPGPATH];
427 char pkglib_path[MAXPGPATH];
428 char ExtraOptions[MAXPGPATH];
431 static void read_backend_variables(char *id, Port *port);
432 static void restore_backend_variables(BackendParameters *param, Port *port);
435 static bool save_backend_variables(BackendParameters *param, Port *port);
437 static bool save_backend_variables(BackendParameters *param, Port *port,
438 HANDLE childProcess, pid_t childPid);
441 static void ShmemBackendArrayAdd(Backend *bn);
442 static void ShmemBackendArrayRemove(Backend *bn);
443 #endif /* EXEC_BACKEND */
445 #define StartupDataBase() StartChildProcess(StartupProcess)
446 #define StartBackgroundWriter() StartChildProcess(BgWriterProcess)
447 #define StartWalWriter() StartChildProcess(WalWriterProcess)
449 /* Macros to check exit status of a child process */
450 #define EXIT_STATUS_0(st) ((st) == 0)
451 #define EXIT_STATUS_1(st) (WIFEXITED(st) && WEXITSTATUS(st) == 1)
455 * Postmaster main entry point
458 PostmasterMain(int argc, char *argv[])
462 char *userDoption = NULL;
465 MyProcPid = PostmasterPid = getpid();
467 MyStartTime = time(NULL);
469 IsPostmasterEnvironment = true;
472 * for security, no dir or file created can be group or other accessible
474 umask((mode_t) 0077);
477 * Fire up essential subsystems: memory management
482 * By default, palloc() requests in the postmaster will be allocated in
483 * the PostmasterContext, which is space that can be recycled by backends.
484 * Allocated data that needs to be available to backends should be
485 * allocated in TopMemoryContext.
487 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
489 ALLOCSET_DEFAULT_MINSIZE,
490 ALLOCSET_DEFAULT_INITSIZE,
491 ALLOCSET_DEFAULT_MAXSIZE);
492 MemoryContextSwitchTo(PostmasterContext);
494 /* Initialize paths to installation files */
495 getInstallationPaths(argv[0]);
500 InitializeGUCOptions();
505 * Parse command-line options. CAUTION: keep this in sync with
506 * tcop/postgres.c (the option sets should not conflict) and with the
507 * common help() function in main/main.c.
509 while ((opt = getopt(argc, argv, "A:B:c:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:W:-:")) != -1)
514 SetConfigOption("debug_assertions", optarg, PGC_POSTMASTER, PGC_S_ARGV);
518 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
522 userDoption = optarg;
526 set_debug_options(atoi(optarg), PGC_POSTMASTER, PGC_S_ARGV);
530 SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
534 SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
538 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
542 if (!set_plan_disabling_options(optarg, PGC_POSTMASTER, PGC_S_ARGV))
544 write_stderr("%s: invalid argument for option -f: \"%s\"\n",
551 SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
555 SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
559 /* only used by interactive backend */
563 SetConfigOption("unix_socket_directory", optarg, PGC_POSTMASTER, PGC_S_ARGV);
567 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
571 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
575 /* Don't reinit shared mem after abnormal exit */
580 SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
584 /* Other options to pass to the backend on the command line */
585 snprintf(ExtraOptions + strlen(ExtraOptions),
586 sizeof(ExtraOptions) - strlen(ExtraOptions),
591 SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
595 SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
599 /* only used by single-user backend */
603 SetConfigOption("work_mem", optarg, PGC_POSTMASTER, PGC_S_ARGV);
607 SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
613 * In the event that some backend dumps core, send SIGSTOP,
614 * rather than SIGQUIT, to all its peers. This lets the wily
615 * post_hacker collect core dumps from everyone.
622 const char *tmp = get_stats_option_name(optarg);
626 SetConfigOption(tmp, "true", PGC_POSTMASTER, PGC_S_ARGV);
630 write_stderr("%s: invalid argument for option -t: \"%s\"\n",
638 SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
647 ParseLongOption(optarg, &name, &value);
652 (errcode(ERRCODE_SYNTAX_ERROR),
653 errmsg("--%s requires a value",
657 (errcode(ERRCODE_SYNTAX_ERROR),
658 errmsg("-c %s requires a value",
662 SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
670 write_stderr("Try \"%s --help\" for more information.\n",
677 * Postmaster accepts no non-option switch arguments.
681 write_stderr("%s: invalid argument: \"%s\"\n",
682 progname, argv[optind]);
683 write_stderr("Try \"%s --help\" for more information.\n",
689 * Locate the proper configuration files and data directory, and read
690 * postgresql.conf for the first time.
692 if (!SelectConfigFiles(userDoption, progname))
695 /* Verify that DataDir looks reasonable */
698 /* And switch working directory into it */
702 * Check for invalid combinations of GUC settings.
704 if (ReservedBackends >= MaxBackends)
706 write_stderr("%s: superuser_reserved_connections must be less than max_connections\n", progname);
711 * Other one-time internal sanity checks can go here, if they are fast.
712 * (Put any slow processing further down, after postmaster.pid creation.)
714 if (!CheckDateTokenTables())
716 write_stderr("%s: invalid datetoken tables, please fix\n", progname);
721 * Now that we are done processing the postmaster arguments, reset
722 * getopt(3) library so that it will work correctly in subprocesses.
725 #ifdef HAVE_INT_OPTRESET
726 optreset = 1; /* some systems need this too */
729 /* For debugging: display postmaster environment */
731 extern char **environ;
735 (errmsg_internal("%s: PostmasterMain: initial environ dump:",
738 (errmsg_internal("-----------------------------------------")));
739 for (p = environ; *p; ++p)
741 (errmsg_internal("\t%s", *p)));
743 (errmsg_internal("-----------------------------------------")));
747 * Fork away from controlling terminal, if silent_mode specified.
749 * Must do this before we grab any interlock files, else the interlocks
750 * will show the wrong PID.
756 * Create lockfile for data directory.
758 * We want to do this before we try to grab the input sockets, because the
759 * data directory interlock is more reliable than the socket-file
760 * interlock (thanks to whoever decided to put socket files in /tmp :-().
761 * For the same reason, it's best to grab the TCP socket(s) before the
764 CreateDataDirLockFile(true);
767 * If timezone is not set, determine what the OS uses. (In theory this
768 * should be done during GUC initialization, but because it can take as
769 * much as several seconds, we delay it until after we've created the
770 * postmaster.pid file. This prevents problems with boot scripts that
771 * expect the pidfile to appear quickly. Also, we avoid problems with
772 * trying to locate the timezone files too early in initialization.)
774 pg_timezone_initialize();
777 * Likewise, init timezone_abbreviations if not already set.
779 pg_timezone_abbrev_initialize();
782 * Initialize SSL library, if specified.
790 * process any libraries that should be preloaded at postmaster start
792 process_shared_preload_libraries();
795 * Remove old temporary files. At this point there can be no other
796 * Postgres processes running in this directory, so this should be safe.
801 * Establish input sockets.
803 for (i = 0; i < MAXLISTEN; i++)
804 ListenSocket[i] = -1;
813 /* Need a modifiable copy of ListenAddresses */
814 rawstring = pstrdup(ListenAddresses);
816 /* Parse string into list of identifiers */
817 if (!SplitIdentifierString(rawstring, ',', &elemlist))
819 /* syntax error in list */
821 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
822 errmsg("invalid list syntax for \"listen_addresses\"")));
827 char *curhost = (char *) lfirst(l);
829 if (strcmp(curhost, "*") == 0)
830 status = StreamServerPort(AF_UNSPEC, NULL,
831 (unsigned short) PostPortNumber,
833 ListenSocket, MAXLISTEN);
835 status = StreamServerPort(AF_UNSPEC, curhost,
836 (unsigned short) PostPortNumber,
838 ListenSocket, MAXLISTEN);
839 if (status == STATUS_OK)
843 (errmsg("could not create listen socket for \"%s\"",
847 if (!success && list_length(elemlist))
849 (errmsg("could not create any TCP/IP sockets")));
856 /* Register for Bonjour only if we opened TCP socket(s) */
857 if (ListenSocket[0] != -1 && bonjour_name != NULL)
859 DNSServiceRegistrationCreate(bonjour_name,
862 htons(PostPortNumber),
864 (DNSServiceRegistrationReply) reg_reply,
869 #ifdef HAVE_UNIX_SOCKETS
870 status = StreamServerPort(AF_UNIX, NULL,
871 (unsigned short) PostPortNumber,
873 ListenSocket, MAXLISTEN);
874 if (status != STATUS_OK)
876 (errmsg("could not create Unix-domain socket")));
880 * check that we have some socket to listen on
882 if (ListenSocket[0] == -1)
884 (errmsg("no socket created for listening")));
887 * Set up shared memory and semaphores.
889 reset_shared(PostPortNumber);
892 * Estimate number of openable files. This must happen after setting up
893 * semaphores, because on some platforms semaphores count as open files.
898 * Initialize the list of active backends.
900 BackendList = DLNewList();
905 * Initialize I/O completion port used to deliver list of dead children.
907 win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
908 if (win32ChildQueue == NULL)
910 (errmsg("could not create I/O completion port for child queue")));
913 * Set up a handle that child processes can use to check whether the
914 * postmaster is still running.
916 if (DuplicateHandle(GetCurrentProcess(),
922 DUPLICATE_SAME_ACCESS) == 0)
924 (errmsg_internal("could not duplicate postmaster handle: error code %d",
925 (int) GetLastError())));
929 * Record postmaster options. We delay this till now to avoid recording
930 * bogus options (eg, NBuffers too high for available memory).
932 if (!CreateOptsFile(argc, argv, my_exec_path))
936 /* Write out nondefault GUC settings for child processes to use */
937 write_nondefault_variables(PGC_POSTMASTER);
941 * Write the external PID file if requested
943 if (external_pid_file)
945 FILE *fpidfile = fopen(external_pid_file, "w");
949 fprintf(fpidfile, "%d\n", MyProcPid);
951 /* Should we remove the pid file on postmaster exit? */
954 write_stderr("%s: could not write external PID file \"%s\": %s\n",
955 progname, external_pid_file, strerror(errno));
959 * Set up signal handlers for the postmaster process.
961 * CAUTION: when changing this list, check for side-effects on the signal
962 * handling setup of child processes. See tcop/postgres.c,
963 * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/walwriter.c,
964 * postmaster/autovacuum.c, postmaster/pgarch.c, postmaster/pgstat.c, and
965 * postmaster/syslogger.c.
968 PG_SETMASK(&BlockSig);
970 pqsignal(SIGHUP, SIGHUP_handler); /* reread config file and have
971 * children do same */
972 pqsignal(SIGINT, pmdie); /* send SIGTERM and shut down */
973 pqsignal(SIGQUIT, pmdie); /* send SIGQUIT and die */
974 pqsignal(SIGTERM, pmdie); /* wait for children and shut down */
975 pqsignal(SIGALRM, SIG_IGN); /* ignored */
976 pqsignal(SIGPIPE, SIG_IGN); /* ignored */
977 pqsignal(SIGUSR1, sigusr1_handler); /* message from child process */
978 pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
979 pqsignal(SIGCHLD, reaper); /* handle child termination */
980 pqsignal(SIGTTIN, SIG_IGN); /* ignored */
981 pqsignal(SIGTTOU, SIG_IGN); /* ignored */
982 /* ignore SIGXFSZ, so that ulimit violations work like disk full */
984 pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
988 * If enabled, start up syslogger collection subprocess
990 SysLoggerPID = SysLogger_Start();
993 * Reset whereToSendOutput from DestDebug (its starting state) to
994 * DestNone. This stops ereport from sending log messages to stderr unless
995 * Log_destination permits. We don't do this until the postmaster is
996 * fully launched, since startup failures may as well be reported to
999 whereToSendOutput = DestNone;
1002 * Initialize stats collection subsystem (this does NOT start the
1003 * collector process!)
1008 * Initialize the autovacuum subsystem (again, no process start yet)
1013 * Load configuration files for client authentication.
1018 * It makes no sense to continue if we fail to load the HBA file,
1019 * since there is no way to connect to the database in this case.
1022 (errmsg("could not load pg_hba.conf")));
1027 * Remember postmaster startup time
1029 PgStartTime = GetCurrentTimestamp();
1030 /* PostmasterRandom wants its own copy */
1031 gettimeofday(&random_start_time, NULL);
1034 * We're ready to rock and roll...
1036 StartupPID = StartupDataBase();
1037 Assert(StartupPID != 0);
1038 pmState = PM_STARTUP;
1040 status = ServerLoop();
1043 * ServerLoop probably shouldn't ever return, but if it does, close down.
1045 ExitPostmaster(status != STATUS_OK);
1047 return 0; /* not reached */
1052 * Compute and check the directory paths to files that are part of the
1053 * installation (as deduced from the postgres executable's own location)
1056 getInstallationPaths(const char *argv0)
1060 /* Locate the postgres executable itself */
1061 if (find_my_exec(argv0, my_exec_path) < 0)
1062 elog(FATAL, "%s: could not locate my own executable path", argv0);
1065 /* Locate executable backend before we change working directory */
1066 if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1067 postgres_exec_path) < 0)
1069 (errmsg("%s: could not locate matching postgres executable",
1074 * Locate the pkglib directory --- this has to be set early in case we try
1075 * to load any modules from it in response to postgresql.conf entries.
1077 get_pkglib_path(my_exec_path, pkglib_path);
1080 * Verify that there's a readable directory there; otherwise the Postgres
1081 * installation is incomplete or corrupt. (A typical cause of this
1082 * failure is that the postgres executable has been moved or hardlinked to
1083 * some directory that's not a sibling of the installation lib/
1086 pdir = AllocateDir(pkglib_path);
1089 (errcode_for_file_access(),
1090 errmsg("could not open directory \"%s\": %m",
1092 errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1097 * XXX is it worth similarly checking the share/ directory? If the lib/
1098 * directory is there, then share/ probably is too.
1104 * Validate the proposed data directory
1109 char path[MAXPGPATH];
1111 struct stat stat_buf;
1115 if (stat(DataDir, &stat_buf) != 0)
1117 if (errno == ENOENT)
1119 (errcode_for_file_access(),
1120 errmsg("data directory \"%s\" does not exist",
1124 (errcode_for_file_access(),
1125 errmsg("could not read permissions of directory \"%s\": %m",
1129 /* eventual chdir would fail anyway, but let's test ... */
1130 if (!S_ISDIR(stat_buf.st_mode))
1132 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1133 errmsg("specified data directory \"%s\" is not a directory",
1137 * Check that the directory belongs to my userid; if not, reject.
1139 * This check is an essential part of the interlock that prevents two
1140 * postmasters from starting in the same directory (see CreateLockFile()).
1141 * Do not remove or weaken it.
1143 * XXX can we safely enable this check on Windows?
1145 #if !defined(WIN32) && !defined(__CYGWIN__)
1146 if (stat_buf.st_uid != geteuid())
1148 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1149 errmsg("data directory \"%s\" has wrong ownership",
1151 errhint("The server must be started by the user that owns the data directory.")));
1155 * Check if the directory has group or world access. If so, reject.
1157 * It would be possible to allow weaker constraints (for example, allow
1158 * group access) but we cannot make a general assumption that that is
1159 * okay; for example there are platforms where nearly all users
1160 * customarily belong to the same group. Perhaps this test should be
1163 * XXX temporarily suppress check when on Windows, because there may not
1164 * be proper support for Unix-y file permissions. Need to think of a
1165 * reasonable check to apply on Windows.
1167 #if !defined(WIN32) && !defined(__CYGWIN__)
1168 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
1170 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1171 errmsg("data directory \"%s\" has group or world access",
1173 errdetail("Permissions should be u=rwx (0700).")));
1176 /* Look for PG_VERSION before looking for pg_control */
1177 ValidatePgVersion(DataDir);
1179 snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1181 fp = AllocateFile(path, PG_BINARY_R);
1184 write_stderr("%s: could not find the database system\n"
1185 "Expected to find it in the directory \"%s\",\n"
1186 "but could not open file \"%s\": %s\n",
1187 progname, DataDir, path, strerror(errno));
1197 * empty callback function for DNSServiceRegistrationCreate()
1200 reg_reply(DNSServiceRegistrationReplyErrorType errorCode, void *context)
1203 #endif /* USE_BONJOUR */
1207 * Fork away from the controlling terminal (silent_mode option)
1209 * Since this requires disconnecting from stdin/stdout/stderr (in case they're
1210 * linked to the terminal), we re-point stdin to /dev/null and stdout/stderr
1211 * to "postmaster.log" in the data directory, where we're already chdir'd.
1217 const char *pmlogname = "postmaster.log";
1224 * Make sure we can open the files we're going to redirect to. If this
1225 * fails, we want to complain before disconnecting. Mention the full path
1226 * of the logfile in the error message, even though we address it by
1229 dvnull = open(DEVNULL, O_RDONLY, 0);
1232 write_stderr("%s: could not open file \"%s\": %s\n",
1233 progname, DEVNULL, strerror(errno));
1236 pmlog = open(pmlogname, O_CREAT | O_WRONLY | O_APPEND, 0600);
1239 write_stderr("%s: could not open log file \"%s/%s\": %s\n",
1240 progname, DataDir, pmlogname, strerror(errno));
1247 pid = fork_process();
1248 if (pid == (pid_t) -1)
1250 write_stderr("%s: could not fork background process: %s\n",
1251 progname, strerror(errno));
1256 /* Parent should just exit, without doing any atexit cleanup */
1260 MyProcPid = PostmasterPid = getpid(); /* reset PID vars to child */
1262 MyStartTime = time(NULL);
1265 * Some systems use setsid() to dissociate from the TTY's process group,
1266 * while on others it depends on stdin/stdout/stderr. Do both if possible.
1271 write_stderr("%s: could not dissociate from controlling TTY: %s\n",
1272 progname, strerror(errno));
1278 * Reassociate stdin/stdout/stderr. fork_process() cleared any pending
1279 * output, so this should be safe. The only plausible error is EINTR,
1280 * which just means we should retry.
1283 res = dup2(dvnull, 0);
1284 } while (res < 0 && errno == EINTR);
1287 res = dup2(pmlog, 1);
1288 } while (res < 0 && errno == EINTR);
1290 res = dup2(pmlog, 2);
1291 } while (res < 0 && errno == EINTR);
1295 elog(FATAL, "silent_mode is not supported under Windows");
1301 * Main idle loop of postmaster
1311 last_touch_time = time(NULL);
1313 nSockets = initMasks(&readmask);
1321 * Wait for a connection request to arrive.
1323 * We wait at most one minute, to ensure that the other background
1324 * tasks handled below get done even when no requests are arriving.
1326 * If we are in PM_WAIT_DEAD_END state, then we don't want to accept
1327 * any new connections, so we don't call select() at all; just sleep
1328 * for a little bit with signals unblocked.
1330 memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
1332 PG_SETMASK(&UnBlockSig);
1334 if (pmState == PM_WAIT_DEAD_END)
1336 pg_usleep(100000L); /* 100 msec seems reasonable */
1341 /* must set timeout each time; some OSes change it! */
1342 struct timeval timeout;
1344 timeout.tv_sec = 60;
1345 timeout.tv_usec = 0;
1347 selres = select(nSockets, &rmask, NULL, NULL, &timeout);
1351 * Block all signals until we wait again. (This makes it safe for our
1352 * signal handlers to do nontrivial work.)
1354 PG_SETMASK(&BlockSig);
1356 /* Now check the select() result */
1359 if (errno != EINTR && errno != EWOULDBLOCK)
1362 (errcode_for_socket_access(),
1363 errmsg("select() failed in postmaster: %m")));
1364 return STATUS_ERROR;
1369 * New connection pending on any of our sockets? If so, fork a child
1370 * process to deal with it.
1376 for (i = 0; i < MAXLISTEN; i++)
1378 if (ListenSocket[i] == -1)
1380 if (FD_ISSET(ListenSocket[i], &rmask))
1384 port = ConnCreate(ListenSocket[i]);
1387 BackendStartup(port);
1390 * We no longer need the open socket or port structure
1393 StreamClose(port->sock);
1400 /* If we have lost the log collector, try to start a new one */
1401 if (SysLoggerPID == 0 && Logging_collector)
1402 SysLoggerPID = SysLogger_Start();
1405 * If no background writer process is running, and we are not in a
1406 * state that prevents it, start one. It doesn't matter if this
1407 * fails, we'll just try again later.
1409 if (BgWriterPID == 0 &&
1410 (pmState == PM_RUN || pmState == PM_RECOVERY ||
1411 pmState == PM_RECOVERY_CONSISTENT))
1412 BgWriterPID = StartBackgroundWriter();
1415 * Likewise, if we have lost the walwriter process, try to start a new
1418 if (WalWriterPID == 0 && pmState == PM_RUN)
1419 WalWriterPID = StartWalWriter();
1421 /* If we have lost the autovacuum launcher, try to start a new one */
1422 if (AutoVacPID == 0 &&
1423 (AutoVacuumingActive() || start_autovac_launcher) &&
1426 AutoVacPID = StartAutoVacLauncher();
1427 if (AutoVacPID != 0)
1428 start_autovac_launcher = false; /* signal processed */
1431 /* If we have lost the archiver, try to start a new one */
1432 if (XLogArchivingActive() && PgArchPID == 0 && pmState == PM_RUN)
1433 PgArchPID = pgarch_start();
1435 /* If we have lost the stats collector, try to start a new one */
1436 if (PgStatPID == 0 && pmState == PM_RUN)
1437 PgStatPID = pgstat_start();
1439 /* If we need to signal the autovacuum launcher, do so now */
1440 if (avlauncher_needs_signal)
1442 avlauncher_needs_signal = false;
1443 if (AutoVacPID != 0)
1444 kill(AutoVacPID, SIGUSR1);
1448 * Touch the socket and lock file every 58 minutes, to ensure that
1449 * they are not removed by overzealous /tmp-cleaning tasks. We assume
1450 * no one runs cleaners with cutoff times of less than an hour ...
1453 if (now - last_touch_time >= 58 * SECS_PER_MINUTE)
1456 TouchSocketLockFile();
1457 last_touch_time = now;
1464 * Initialise the masks for select() for the ports we are listening on.
1465 * Return the number of sockets to listen on.
1468 initMasks(fd_set *rmask)
1475 for (i = 0; i < MAXLISTEN; i++)
1477 int fd = ListenSocket[i];
1492 * Read a client's startup packet and do something according to it.
1494 * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
1495 * not return at all.
1497 * (Note that ereport(FATAL) stuff is sent to the client, so only use it
1498 * if that's what you want. Return STATUS_ERROR if you don't want to
1499 * send anything to the client, which would typically be appropriate
1500 * if we detect a communications failure.)
1503 ProcessStartupPacket(Port *port, bool SSLdone)
1507 ProtocolVersion proto;
1508 MemoryContext oldcontext;
1510 if (pq_getbytes((char *) &len, 4) == EOF)
1513 * EOF after SSLdone probably means the client didn't like our
1514 * response to NEGOTIATE_SSL_CODE. That's not an error condition, so
1515 * don't clutter the log with a complaint.
1519 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1520 errmsg("incomplete startup packet")));
1521 return STATUS_ERROR;
1527 if (len < (int32) sizeof(ProtocolVersion) ||
1528 len > MAX_STARTUP_PACKET_LENGTH)
1531 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1532 errmsg("invalid length of startup packet")));
1533 return STATUS_ERROR;
1537 * Allocate at least the size of an old-style startup packet, plus one
1538 * extra byte, and make sure all are zeroes. This ensures we will have
1539 * null termination of all strings, in both fixed- and variable-length
1542 if (len <= (int32) sizeof(StartupPacket))
1543 buf = palloc0(sizeof(StartupPacket) + 1);
1545 buf = palloc0(len + 1);
1547 if (pq_getbytes(buf, len) == EOF)
1550 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1551 errmsg("incomplete startup packet")));
1552 return STATUS_ERROR;
1556 * The first field is either a protocol version number or a special
1559 port->proto = proto = ntohl(*((ProtocolVersion *) buf));
1561 if (proto == CANCEL_REQUEST_CODE)
1563 processCancelRequest(port, buf);
1564 return 127; /* XXX */
1567 if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
1572 /* No SSL when disabled or on Unix sockets */
1573 if (!EnableSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
1576 SSLok = 'S'; /* Support for SSL */
1578 SSLok = 'N'; /* No support for SSL */
1582 if (send(port->sock, &SSLok, 1, 0) != 1)
1585 goto retry1; /* if interrupted, just retry */
1587 (errcode_for_socket_access(),
1588 errmsg("failed to send SSL negotiation response: %m")));
1589 return STATUS_ERROR; /* close the connection */
1593 if (SSLok == 'S' && secure_open_server(port) == -1)
1594 return STATUS_ERROR;
1596 /* regular startup packet, cancel, etc packet should follow... */
1597 /* but not another SSL negotiation request */
1598 return ProcessStartupPacket(port, true);
1601 /* Could add additional special packet types here */
1604 * Set FrontendProtocol now so that ereport() knows what format to send if
1605 * we fail during startup.
1607 FrontendProtocol = proto;
1609 /* Check we can handle the protocol the frontend is using. */
1611 if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
1612 PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
1613 (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
1614 PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
1616 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1617 errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
1618 PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
1619 PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST),
1620 PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST),
1621 PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))));
1624 * Now fetch parameters out of startup packet and save them into the Port
1625 * structure. All data structures attached to the Port struct must be
1626 * allocated in TopMemoryContext so that they won't disappear when we pass
1627 * them to PostgresMain (see BackendRun). We need not worry about leaking
1628 * this storage on failure, since we aren't in the postmaster process
1631 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1633 if (PG_PROTOCOL_MAJOR(proto) >= 3)
1635 int32 offset = sizeof(ProtocolVersion);
1638 * Scan packet body for name/option pairs. We can assume any string
1639 * beginning within the packet body is null-terminated, thanks to
1640 * zeroing extra byte above.
1642 port->guc_options = NIL;
1644 while (offset < len)
1646 char *nameptr = ((char *) buf) + offset;
1650 if (*nameptr == '\0')
1651 break; /* found packet terminator */
1652 valoffset = offset + strlen(nameptr) + 1;
1653 if (valoffset >= len)
1654 break; /* missing value, will complain below */
1655 valptr = ((char *) buf) + valoffset;
1657 if (strcmp(nameptr, "database") == 0)
1658 port->database_name = pstrdup(valptr);
1659 else if (strcmp(nameptr, "user") == 0)
1660 port->user_name = pstrdup(valptr);
1661 else if (strcmp(nameptr, "options") == 0)
1662 port->cmdline_options = pstrdup(valptr);
1665 /* Assume it's a generic GUC option */
1666 port->guc_options = lappend(port->guc_options,
1668 port->guc_options = lappend(port->guc_options,
1671 offset = valoffset + strlen(valptr) + 1;
1675 * If we didn't find a packet terminator exactly at the end of the
1676 * given packet length, complain.
1678 if (offset != len - 1)
1680 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1681 errmsg("invalid startup packet layout: expected terminator as last byte")));
1686 * Get the parameters from the old-style, fixed-width-fields startup
1687 * packet as C strings. The packet destination was cleared first so a
1688 * short packet has zeros silently added. We have to be prepared to
1689 * truncate the pstrdup result for oversize fields, though.
1691 StartupPacket *packet = (StartupPacket *) buf;
1693 port->database_name = pstrdup(packet->database);
1694 if (strlen(port->database_name) > sizeof(packet->database))
1695 port->database_name[sizeof(packet->database)] = '\0';
1696 port->user_name = pstrdup(packet->user);
1697 if (strlen(port->user_name) > sizeof(packet->user))
1698 port->user_name[sizeof(packet->user)] = '\0';
1699 port->cmdline_options = pstrdup(packet->options);
1700 if (strlen(port->cmdline_options) > sizeof(packet->options))
1701 port->cmdline_options[sizeof(packet->options)] = '\0';
1702 port->guc_options = NIL;
1705 /* Check a user name was given. */
1706 if (port->user_name == NULL || port->user_name[0] == '\0')
1708 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1709 errmsg("no PostgreSQL user name specified in startup packet")));
1711 /* The database defaults to the user name. */
1712 if (port->database_name == NULL || port->database_name[0] == '\0')
1713 port->database_name = pstrdup(port->user_name);
1715 if (Db_user_namespace)
1718 * If user@, it is a global user, remove '@'. We only want to do this
1719 * if there is an '@' at the end and no earlier in the user string or
1720 * they may fake as a local user of another database attaching to this
1723 if (strchr(port->user_name, '@') ==
1724 port->user_name + strlen(port->user_name) - 1)
1725 *strchr(port->user_name, '@') = '\0';
1728 /* Append '@' and dbname */
1731 db_user = palloc(strlen(port->user_name) +
1732 strlen(port->database_name) + 2);
1733 sprintf(db_user, "%s@%s", port->user_name, port->database_name);
1734 port->user_name = db_user;
1739 * Truncate given database and user names to length of a Postgres name.
1740 * This avoids lookup failures when overlength names are given.
1742 if (strlen(port->database_name) >= NAMEDATALEN)
1743 port->database_name[NAMEDATALEN - 1] = '\0';
1744 if (strlen(port->user_name) >= NAMEDATALEN)
1745 port->user_name[NAMEDATALEN - 1] = '\0';
1748 * Done putting stuff in TopMemoryContext.
1750 MemoryContextSwitchTo(oldcontext);
1753 * If we're going to reject the connection due to database state, say so
1754 * now instead of wasting cycles on an authentication exchange. (This also
1755 * allows a pg_ping utility to be written.)
1757 switch (port->canAcceptConnections)
1761 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1762 errmsg("the database system is starting up")));
1766 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1767 errmsg("the database system is shutting down")));
1771 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1772 errmsg("the database system is in recovery mode")));
1776 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
1777 errmsg("sorry, too many clients already")));
1779 case CAC_WAITBACKUP:
1780 /* OK for now, will check in InitPostgres */
1791 * The client has sent a cancel request packet, not a normal
1792 * start-a-new-connection packet. Perform the necessary processing.
1793 * Nothing is sent back to the client.
1796 processCancelRequest(Port *port, void *pkt)
1798 CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
1800 long cancelAuthCode;
1803 #ifndef EXEC_BACKEND
1809 backendPID = (int) ntohl(canc->backendPID);
1810 cancelAuthCode = (long) ntohl(canc->cancelAuthCode);
1813 * See if we have a matching backend. In the EXEC_BACKEND case, we can no
1814 * longer access the postmaster's own backend list, and must rely on the
1815 * duplicate array in shared memory.
1817 #ifndef EXEC_BACKEND
1818 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
1820 bp = (Backend *) DLE_VAL(curr);
1822 for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
1824 bp = (Backend *) &ShmemBackendArray[i];
1826 if (bp->pid == backendPID)
1828 if (bp->cancel_key == cancelAuthCode)
1830 /* Found a match; signal that backend to cancel current op */
1832 (errmsg_internal("processing cancel request: sending SIGINT to process %d",
1834 signal_child(bp->pid, SIGINT);
1837 /* Right PID, wrong key: no way, Jose */
1839 (errmsg("wrong key in cancel request for process %d",
1845 /* No matching backend */
1847 (errmsg("PID %d in cancel request did not match any process",
1852 * canAcceptConnections --- check to see if database state allows connections.
1854 static enum CAC_state
1855 canAcceptConnections(void)
1858 * Can't start backends when in startup/shutdown/recovery state.
1860 * In state PM_WAIT_BACKUP only superusers can connect (this must be
1861 * allowed so that a superuser can end online backup mode); we return
1862 * CAC_WAITBACKUP code to indicate that this must be checked later.
1864 if (pmState != PM_RUN)
1866 if (pmState == PM_WAIT_BACKUP)
1867 return CAC_WAITBACKUP; /* allow superusers only */
1868 if (Shutdown > NoShutdown)
1869 return CAC_SHUTDOWN; /* shutdown is pending */
1871 (pmState == PM_STARTUP ||
1872 pmState == PM_RECOVERY ||
1873 pmState == PM_RECOVERY_CONSISTENT))
1874 return CAC_STARTUP; /* normal startup */
1875 return CAC_RECOVERY; /* else must be crash recovery */
1879 * Don't start too many children.
1881 * We allow more connections than we can have backends here because some
1882 * might still be authenticating; they might fail auth, or some existing
1883 * backend might exit before the auth cycle is completed. The exact
1884 * MaxBackends limit is enforced when a new backend tries to join the
1885 * shared-inval backend array.
1887 * The limit here must match the sizes of the per-child-process arrays;
1888 * see comments for MaxLivePostmasterChildren().
1890 if (CountChildren() >= MaxLivePostmasterChildren())
1898 * ConnCreate -- create a local connection data structure
1901 ConnCreate(int serverFd)
1905 if (!(port = (Port *) calloc(1, sizeof(Port))))
1908 (errcode(ERRCODE_OUT_OF_MEMORY),
1909 errmsg("out of memory")));
1913 if (StreamConnection(serverFd, port) != STATUS_OK)
1915 if (port->sock >= 0)
1916 StreamClose(port->sock);
1923 * Precompute password salt values to use for this connection. It's
1924 * slightly annoying to do this long in advance of knowing whether
1925 * we'll need 'em or not, but we must do the random() calls before we
1926 * fork, not after. Else the postmaster's random sequence won't get
1927 * advanced, and all backends would end up using the same salt...
1929 RandomSalt(port->md5Salt);
1933 * Allocate GSSAPI specific state struct
1935 #ifndef EXEC_BACKEND
1936 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
1937 port->gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
1941 (errcode(ERRCODE_OUT_OF_MEMORY),
1942 errmsg("out of memory")));
1953 * ConnFree -- free a local connection data structure
1956 ConnFree(Port *conn)
1968 * ClosePostmasterPorts -- close all the postmaster's open sockets
1970 * This is called during child process startup to release file descriptors
1971 * that are not needed by that child process. The postmaster still has
1972 * them open, of course.
1974 * Note: we pass am_syslogger as a boolean because we don't want to set
1975 * the global variable yet when this is called.
1978 ClosePostmasterPorts(bool am_syslogger)
1982 /* Close the listen sockets */
1983 for (i = 0; i < MAXLISTEN; i++)
1985 if (ListenSocket[i] != -1)
1987 StreamClose(ListenSocket[i]);
1988 ListenSocket[i] = -1;
1992 /* If using syslogger, close the read side of the pipe */
1996 if (syslogPipe[0] >= 0)
1997 close(syslogPipe[0]);
2001 CloseHandle(syslogPipe[0]);
2009 * reset_shared -- reset shared memory and semaphores
2012 reset_shared(int port)
2015 * Create or re-create shared memory and semaphores.
2017 * Note: in each "cycle of life" we will normally assign the same IPC keys
2018 * (if using SysV shmem and/or semas), since the port number is used to
2019 * determine IPC keys. This helps ensure that we will clean up dead IPC
2020 * objects if the postmaster crashes and is restarted.
2022 CreateSharedMemoryAndSemaphores(false, port);
2027 * SIGHUP -- reread config files, and tell children to do same
2030 SIGHUP_handler(SIGNAL_ARGS)
2032 int save_errno = errno;
2034 PG_SETMASK(&BlockSig);
2036 if (Shutdown <= SmartShutdown)
2039 (errmsg("received SIGHUP, reloading configuration files")));
2040 ProcessConfigFile(PGC_SIGHUP);
2041 SignalChildren(SIGHUP);
2042 if (StartupPID != 0)
2043 signal_child(StartupPID, SIGHUP);
2044 if (BgWriterPID != 0)
2045 signal_child(BgWriterPID, SIGHUP);
2046 if (WalWriterPID != 0)
2047 signal_child(WalWriterPID, SIGHUP);
2048 if (AutoVacPID != 0)
2049 signal_child(AutoVacPID, SIGHUP);
2051 signal_child(PgArchPID, SIGHUP);
2052 if (SysLoggerPID != 0)
2053 signal_child(SysLoggerPID, SIGHUP);
2055 signal_child(PgStatPID, SIGHUP);
2057 /* Reload authentication config files too */
2060 (errmsg("pg_hba.conf not reloaded")));
2065 /* Update the starting-point file for future children */
2066 write_nondefault_variables(PGC_SIGHUP);
2070 PG_SETMASK(&UnBlockSig);
2077 * pmdie -- signal handler for processing various postmaster signals.
2082 int save_errno = errno;
2084 PG_SETMASK(&BlockSig);
2087 (errmsg_internal("postmaster received signal %d",
2088 postgres_signal_arg)));
2090 switch (postgres_signal_arg)
2097 * Wait for children to end their work, then shut down.
2099 if (Shutdown >= SmartShutdown)
2101 Shutdown = SmartShutdown;
2103 (errmsg("received smart shutdown request")));
2105 if (pmState == PM_RUN || pmState == PM_RECOVERY ||
2106 pmState == PM_RECOVERY_CONSISTENT)
2108 /* autovacuum workers are told to shut down immediately */
2109 SignalAutovacWorkers(SIGTERM);
2110 /* and the autovac launcher too */
2111 if (AutoVacPID != 0)
2112 signal_child(AutoVacPID, SIGTERM);
2113 /* and the walwriter too */
2114 if (WalWriterPID != 0)
2115 signal_child(WalWriterPID, SIGTERM);
2116 pmState = PM_WAIT_BACKUP;
2120 * Now wait for online backup mode to end and backends to exit.
2121 * If that is already the case, PostmasterStateMachine will take
2124 PostmasterStateMachine();
2132 * Abort all children with SIGTERM (rollback active transactions
2133 * and exit) and shut down when they are gone.
2135 if (Shutdown >= FastShutdown)
2137 Shutdown = FastShutdown;
2139 (errmsg("received fast shutdown request")));
2141 if (StartupPID != 0)
2142 signal_child(StartupPID, SIGTERM);
2143 if (pmState == PM_RECOVERY)
2145 /* only bgwriter is active in this state */
2146 pmState = PM_WAIT_BACKENDS;
2148 if (pmState == PM_RUN ||
2149 pmState == PM_WAIT_BACKUP ||
2150 pmState == PM_WAIT_BACKENDS ||
2151 pmState == PM_RECOVERY_CONSISTENT)
2154 (errmsg("aborting any active transactions")));
2155 /* shut down all backends and autovac workers */
2156 SignalChildren(SIGTERM);
2157 /* and the autovac launcher too */
2158 if (AutoVacPID != 0)
2159 signal_child(AutoVacPID, SIGTERM);
2160 /* and the walwriter too */
2161 if (WalWriterPID != 0)
2162 signal_child(WalWriterPID, SIGTERM);
2163 pmState = PM_WAIT_BACKENDS;
2167 * Now wait for backends to exit. If there are none,
2168 * PostmasterStateMachine will take the next step.
2170 PostmasterStateMachine();
2176 * Immediate Shutdown:
2178 * abort all children with SIGQUIT and exit without attempt to
2179 * properly shut down data base system.
2182 (errmsg("received immediate shutdown request")));
2183 SignalChildren(SIGQUIT);
2184 if (StartupPID != 0)
2185 signal_child(StartupPID, SIGQUIT);
2186 if (BgWriterPID != 0)
2187 signal_child(BgWriterPID, SIGQUIT);
2188 if (WalWriterPID != 0)
2189 signal_child(WalWriterPID, SIGQUIT);
2190 if (AutoVacPID != 0)
2191 signal_child(AutoVacPID, SIGQUIT);
2193 signal_child(PgArchPID, SIGQUIT);
2195 signal_child(PgStatPID, SIGQUIT);
2200 PG_SETMASK(&UnBlockSig);
2206 * Reaper -- signal handler to cleanup after a child process dies.
2211 int save_errno = errno;
2212 int pid; /* process id of dead child process */
2213 int exitstatus; /* its exit status */
2215 /* These macros hide platform variations in getting child status */
2217 int status; /* child exit status */
2219 #define LOOPTEST() ((pid = waitpid(-1, &status, WNOHANG)) > 0)
2220 #define LOOPHEADER() (exitstatus = status)
2221 #else /* !HAVE_WAITPID */
2223 union wait status; /* child exit status */
2225 #define LOOPTEST() ((pid = wait3(&status, WNOHANG, NULL)) > 0)
2226 #define LOOPHEADER() (exitstatus = status.w_status)
2228 #define LOOPTEST() ((pid = win32_waitpid(&exitstatus)) > 0)
2229 #define LOOPHEADER()
2231 #endif /* HAVE_WAITPID */
2233 PG_SETMASK(&BlockSig);
2236 (errmsg_internal("reaping dead processes")));
2243 * Check if this child was a startup process.
2245 if (pid == StartupPID)
2250 * Unexpected exit of startup process (including FATAL exit)
2251 * during PM_STARTUP is treated as catastrophic. There are no
2252 * other processes running yet, so we can just exit.
2254 if (pmState == PM_STARTUP && !EXIT_STATUS_0(exitstatus))
2256 LogChildExit(LOG, _("startup process"),
2259 (errmsg("aborting startup due to startup process failure")));
2264 * Startup process exited in response to a shutdown request (or it
2265 * completed normally regardless of the shutdown request).
2267 if (Shutdown > NoShutdown &&
2268 (EXIT_STATUS_0(exitstatus) || EXIT_STATUS_1(exitstatus)))
2270 pmState = PM_WAIT_BACKENDS;
2271 /* PostmasterStateMachine logic does the rest */
2276 * Any unexpected exit (including FATAL exit) of the startup
2277 * process is treated as a crash, except that we don't want to
2280 if (!EXIT_STATUS_0(exitstatus))
2282 RecoveryError = true;
2283 HandleChildCrash(pid, exitstatus,
2284 _("startup process"));
2289 * Startup succeeded, commence normal operations
2295 * Load the flat authorization file into postmaster's cache. The
2296 * startup process has recomputed this from the database contents,
2297 * so we wait till it finishes before loading it.
2302 * Crank up the background writer, if we didn't do that already
2303 * when we entered consistent recovery state. It doesn't matter
2304 * if this fails, we'll just try again later.
2306 if (BgWriterPID == 0)
2307 BgWriterPID = StartBackgroundWriter();
2310 * Likewise, start other special children as needed. In a restart
2311 * situation, some of them may be alive already.
2313 if (WalWriterPID == 0)
2314 WalWriterPID = StartWalWriter();
2315 if (AutoVacuumingActive() && AutoVacPID == 0)
2316 AutoVacPID = StartAutoVacLauncher();
2317 if (XLogArchivingActive() && PgArchPID == 0)
2318 PgArchPID = pgarch_start();
2320 PgStatPID = pgstat_start();
2322 /* at this point we are really open for business */
2324 (errmsg("database system is ready to accept connections")));
2330 * Was it the bgwriter?
2332 if (pid == BgWriterPID)
2335 if (EXIT_STATUS_0(exitstatus) && pmState == PM_SHUTDOWN)
2338 * OK, we saw normal exit of the bgwriter after it's been told
2339 * to shut down. We expect that it wrote a shutdown
2340 * checkpoint. (If for some reason it didn't, recovery will
2341 * occur on next postmaster start.)
2343 * At this point we should have no normal backend children
2344 * left (else we'd not be in PM_SHUTDOWN state) but we might
2345 * have dead_end children to wait for.
2347 * If we have an archiver subprocess, tell it to do a last
2348 * archive cycle and quit; otherwise we can go directly to
2349 * PM_WAIT_DEAD_END state.
2351 Assert(Shutdown > NoShutdown);
2355 /* Waken archiver for the last time */
2356 signal_child(PgArchPID, SIGUSR2);
2357 pmState = PM_SHUTDOWN_2;
2360 pmState = PM_WAIT_DEAD_END;
2363 * We can also shut down the stats collector now; there's
2364 * nothing left for it to do.
2367 signal_child(PgStatPID, SIGQUIT);
2372 * Any unexpected exit of the bgwriter (including FATAL exit)
2373 * is treated as a crash.
2375 HandleChildCrash(pid, exitstatus,
2376 _("background writer process"));
2383 * Was it the wal writer? Normal exit can be ignored; we'll start a
2384 * new one at the next iteration of the postmaster's main loop, if
2385 * necessary. Any other exit condition is treated as a crash.
2387 if (pid == WalWriterPID)
2390 if (!EXIT_STATUS_0(exitstatus))
2391 HandleChildCrash(pid, exitstatus,
2392 _("WAL writer process"));
2397 * Was it the autovacuum launcher? Normal exit can be ignored; we'll
2398 * start a new one at the next iteration of the postmaster's main
2399 * loop, if necessary. Any other exit condition is treated as a
2402 if (pid == AutoVacPID)
2405 if (!EXIT_STATUS_0(exitstatus))
2406 HandleChildCrash(pid, exitstatus,
2407 _("autovacuum launcher process"));
2412 * Was it the archiver? If so, just try to start a new one; no need
2413 * to force reset of the rest of the system. (If fail, we'll try
2414 * again in future cycles of the main loop.) But if we were waiting
2415 * for it to shut down, advance to the next shutdown step.
2417 if (pid == PgArchPID)
2420 if (!EXIT_STATUS_0(exitstatus))
2421 LogChildExit(LOG, _("archiver process"),
2423 if (XLogArchivingActive() && pmState == PM_RUN)
2424 PgArchPID = pgarch_start();
2425 else if (pmState == PM_SHUTDOWN_2)
2426 pmState = PM_WAIT_DEAD_END;
2431 * Was it the statistics collector? If so, just try to start a new
2432 * one; no need to force reset of the rest of the system. (If fail,
2433 * we'll try again in future cycles of the main loop.)
2435 if (pid == PgStatPID)
2438 if (!EXIT_STATUS_0(exitstatus))
2439 LogChildExit(LOG, _("statistics collector process"),
2441 if (pmState == PM_RUN)
2442 PgStatPID = pgstat_start();
2446 /* Was it the system logger? If so, try to start a new one */
2447 if (pid == SysLoggerPID)
2450 /* for safety's sake, launch new logger *first* */
2451 SysLoggerPID = SysLogger_Start();
2452 if (!EXIT_STATUS_0(exitstatus))
2453 LogChildExit(LOG, _("system logger process"),
2459 * Else do standard backend child cleanup.
2461 CleanupBackend(pid, exitstatus);
2462 } /* loop over pending child-death reports */
2465 * After cleaning out the SIGCHLD queue, see if we have any state changes
2466 * or actions to make.
2468 PostmasterStateMachine();
2470 /* Done with signal handler */
2471 PG_SETMASK(&UnBlockSig);
2478 * CleanupBackend -- cleanup after terminated backend.
2480 * Remove all local state associated with backend.
2483 CleanupBackend(int pid,
2484 int exitstatus) /* child's exit status. */
2488 LogChildExit(DEBUG2, _("server process"), pid, exitstatus);
2491 * If a backend dies in an ugly way then we must signal all other backends
2492 * to quickdie. If exit status is zero (normal) or one (FATAL exit), we
2493 * assume everything is all right and proceed to remove the backend from
2494 * the active backend list.
2496 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2498 HandleChildCrash(pid, exitstatus, _("server process"));
2502 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2504 Backend *bp = (Backend *) DLE_VAL(curr);
2510 if (!ReleasePostmasterChildSlot(bp->child_slot))
2513 * Uh-oh, the child failed to clean itself up. Treat as a
2516 HandleChildCrash(pid, exitstatus, _("server process"));
2520 ShmemBackendArrayRemove(bp);
2531 * HandleChildCrash -- cleanup after failed backend, bgwriter, walwriter,
2534 * The objectives here are to clean up our local state about the child
2535 * process, and to signal all other remaining children to quickdie.
2538 HandleChildCrash(int pid, int exitstatus, const char *procname)
2545 * Make log entry unless there was a previous crash (if so, nonzero exit
2546 * status is to be expected in SIGQUIT response; don't clutter log)
2550 LogChildExit(LOG, procname, pid, exitstatus);
2552 (errmsg("terminating any other active server processes")));
2555 /* Process regular backends */
2556 for (curr = DLGetHead(BackendList); curr; curr = next)
2558 next = DLGetSucc(curr);
2559 bp = (Backend *) DLE_VAL(curr);
2563 * Found entry for freshly-dead backend, so remove it.
2567 (void) ReleasePostmasterChildSlot(bp->child_slot);
2569 ShmemBackendArrayRemove(bp);
2574 /* Keep looping so we can signal remaining backends */
2579 * This backend is still alive. Unless we did so already, tell it
2580 * to commit hara-kiri.
2582 * SIGQUIT is the special signal that says exit without proc_exit
2583 * and let the user know what's going on. But if SendStop is set
2584 * (-s on command line), then we send SIGSTOP instead, so that we
2585 * can get core dumps from all backends by hand.
2587 * We could exclude dead_end children here, but at least in the
2588 * SIGSTOP case it seems better to include them.
2593 (errmsg_internal("sending %s to process %d",
2594 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2596 signal_child(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
2601 /* Take care of the startup process too */
2602 if (pid == StartupPID)
2604 else if (StartupPID != 0 && !FatalError)
2607 (errmsg_internal("sending %s to process %d",
2608 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2609 (int) StartupPID)));
2610 signal_child(StartupPID, (SendStop ? SIGSTOP : SIGQUIT));
2613 /* Take care of the bgwriter too */
2614 if (pid == BgWriterPID)
2616 else if (BgWriterPID != 0 && !FatalError)
2619 (errmsg_internal("sending %s to process %d",
2620 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2621 (int) BgWriterPID)));
2622 signal_child(BgWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
2625 /* Take care of the walwriter too */
2626 if (pid == WalWriterPID)
2628 else if (WalWriterPID != 0 && !FatalError)
2631 (errmsg_internal("sending %s to process %d",
2632 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2633 (int) WalWriterPID)));
2634 signal_child(WalWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
2637 /* Take care of the autovacuum launcher too */
2638 if (pid == AutoVacPID)
2640 else if (AutoVacPID != 0 && !FatalError)
2643 (errmsg_internal("sending %s to process %d",
2644 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2645 (int) AutoVacPID)));
2646 signal_child(AutoVacPID, (SendStop ? SIGSTOP : SIGQUIT));
2650 * Force a power-cycle of the pgarch process too. (This isn't absolutely
2651 * necessary, but it seems like a good idea for robustness, and it
2652 * simplifies the state-machine logic in the case where a shutdown request
2653 * arrives during crash processing.)
2655 if (PgArchPID != 0 && !FatalError)
2658 (errmsg_internal("sending %s to process %d",
2661 signal_child(PgArchPID, SIGQUIT);
2665 * Force a power-cycle of the pgstat process too. (This isn't absolutely
2666 * necessary, but it seems like a good idea for robustness, and it
2667 * simplifies the state-machine logic in the case where a shutdown request
2668 * arrives during crash processing.)
2670 if (PgStatPID != 0 && !FatalError)
2673 (errmsg_internal("sending %s to process %d",
2676 signal_child(PgStatPID, SIGQUIT);
2677 allow_immediate_pgstat_restart();
2680 /* We do NOT restart the syslogger */
2683 /* We now transit into a state of waiting for children to die */
2684 if (pmState == PM_RECOVERY ||
2685 pmState == PM_RECOVERY_CONSISTENT ||
2686 pmState == PM_RUN ||
2687 pmState == PM_WAIT_BACKUP ||
2688 pmState == PM_SHUTDOWN)
2689 pmState = PM_WAIT_BACKENDS;
2693 * Log the death of a child process.
2696 LogChildExit(int lev, const char *procname, int pid, int exitstatus)
2698 if (WIFEXITED(exitstatus))
2702 translator: %s is a noun phrase describing a child process, such as
2704 (errmsg("%s (PID %d) exited with exit code %d",
2705 procname, pid, WEXITSTATUS(exitstatus))));
2706 else if (WIFSIGNALED(exitstatus))
2711 translator: %s is a noun phrase describing a child process, such as
2713 (errmsg("%s (PID %d) was terminated by exception 0x%X",
2714 procname, pid, WTERMSIG(exitstatus)),
2715 errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value.")));
2716 #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST
2720 translator: %s is a noun phrase describing a child process, such as
2722 (errmsg("%s (PID %d) was terminated by signal %d: %s",
2723 procname, pid, WTERMSIG(exitstatus),
2724 WTERMSIG(exitstatus) < NSIG ?
2725 sys_siglist[WTERMSIG(exitstatus)] : "(unknown)")));
2730 translator: %s is a noun phrase describing a child process, such as
2732 (errmsg("%s (PID %d) was terminated by signal %d",
2733 procname, pid, WTERMSIG(exitstatus))));
2739 translator: %s is a noun phrase describing a child process, such as
2741 (errmsg("%s (PID %d) exited with unrecognized status %d",
2742 procname, pid, exitstatus)));
2746 * Advance the postmaster's state machine and take actions as appropriate
2748 * This is common code for pmdie() and reaper(), which receive the signals
2749 * that might mean we need to change state.
2752 PostmasterStateMachine(void)
2754 if (pmState == PM_WAIT_BACKUP)
2757 * PM_WAIT_BACKUP state ends when online backup mode is not active.
2759 if (!BackupInProgress())
2760 pmState = PM_WAIT_BACKENDS;
2764 * If we are in a state-machine state that implies waiting for backends to
2765 * exit, see if they're all gone, and change state if so.
2767 if (pmState == PM_WAIT_BACKENDS)
2770 * PM_WAIT_BACKENDS state ends when we have no regular backends
2771 * (including autovac workers) and no walwriter or autovac launcher.
2772 * If we are doing crash recovery then we expect the bgwriter to exit
2773 * too, otherwise not. The archiver, stats, and syslogger processes
2774 * are disregarded since they are not connected to shared memory; we
2775 * also disregard dead_end children here.
2777 if (CountChildren() == 0 &&
2779 (BgWriterPID == 0 || !FatalError) &&
2780 WalWriterPID == 0 &&
2786 * Start waiting for dead_end children to die. This state
2787 * change causes ServerLoop to stop creating new ones.
2789 pmState = PM_WAIT_DEAD_END;
2792 * We already SIGQUIT'd the archiver and stats processes, if
2793 * any, when we entered FatalError state.
2799 * If we get here, we are proceeding with normal shutdown. All
2800 * the regular children are gone, and it's time to tell the
2801 * bgwriter to do a shutdown checkpoint.
2803 Assert(Shutdown > NoShutdown);
2804 /* Start the bgwriter if not running */
2805 if (BgWriterPID == 0)
2806 BgWriterPID = StartBackgroundWriter();
2807 /* And tell it to shut down */
2808 if (BgWriterPID != 0)
2810 signal_child(BgWriterPID, SIGUSR2);
2811 pmState = PM_SHUTDOWN;
2816 * If we failed to fork a bgwriter, just shut down. Any
2817 * required cleanup will happen at next restart. We set
2818 * FatalError so that an "abnormal shutdown" message gets
2819 * logged when we exit.
2822 pmState = PM_WAIT_DEAD_END;
2824 /* Kill the archiver and stats collector too */
2826 signal_child(PgArchPID, SIGQUIT);
2828 signal_child(PgStatPID, SIGQUIT);
2834 if (pmState == PM_WAIT_DEAD_END)
2837 * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
2838 * (ie, no dead_end children remain), and the archiver and stats
2839 * collector are gone too.
2841 * The reason we wait for those two is to protect them against a new
2842 * postmaster starting conflicting subprocesses; this isn't an
2843 * ironclad protection, but it at least helps in the
2844 * shutdown-and-immediately-restart scenario. Note that they have
2845 * already been sent appropriate shutdown signals, either during a
2846 * normal state transition leading up to PM_WAIT_DEAD_END, or during
2847 * FatalError processing.
2849 if (DLGetHead(BackendList) == NULL &&
2850 PgArchPID == 0 && PgStatPID == 0)
2852 /* These other guys should be dead already */
2853 Assert(StartupPID == 0);
2854 Assert(BgWriterPID == 0);
2855 Assert(WalWriterPID == 0);
2856 Assert(AutoVacPID == 0);
2857 /* syslogger is not considered here */
2858 pmState = PM_NO_CHILDREN;
2863 * If we've been told to shut down, we exit as soon as there are no
2864 * remaining children. If there was a crash, cleanup will occur at the
2865 * next startup. (Before PostgreSQL 8.3, we tried to recover from the
2866 * crash before exiting, but that seems unwise if we are quitting because
2867 * we got SIGTERM from init --- there may well not be time for recovery
2868 * before init decides to SIGKILL us.)
2870 * Note that the syslogger continues to run. It will exit when it sees
2871 * EOF on its input pipe, which happens when there are no more upstream
2874 if (Shutdown > NoShutdown && pmState == PM_NO_CHILDREN)
2878 ereport(LOG, (errmsg("abnormal database system shutdown")));
2884 * Terminate backup mode to avoid recovery after a clean fast
2889 /* Normal exit from the postmaster is here */
2895 * If recovery failed, wait for all non-syslogger children to exit, and
2896 * then exit postmaster. We don't try to reinitialize when recovery fails,
2897 * because more than likely it will just fail again and we will keep
2900 if (RecoveryError && pmState == PM_NO_CHILDREN)
2904 * If we need to recover from a crash, wait for all non-syslogger children
2905 * to exit, then reset shmem and StartupDataBase.
2907 if (FatalError && pmState == PM_NO_CHILDREN)
2910 (errmsg("all server processes terminated; reinitializing")));
2913 reset_shared(PostPortNumber);
2915 StartupPID = StartupDataBase();
2916 Assert(StartupPID != 0);
2917 pmState = PM_STARTUP;
2923 * Send a signal to a postmaster child process
2925 * On systems that have setsid(), each child process sets itself up as a
2926 * process group leader. For signals that are generally interpreted in the
2927 * appropriate fashion, we signal the entire process group not just the
2928 * direct child process. This allows us to, for example, SIGQUIT a blocked
2929 * archive_recovery script, or SIGINT a script being run by a backend via
2932 * There is a race condition for recently-forked children: they might not
2933 * have executed setsid() yet. So we signal the child directly as well as
2934 * the group. We assume such a child will handle the signal before trying
2935 * to spawn any grandchild processes. We also assume that signaling the
2936 * child twice will not cause any problems.
2939 signal_child(pid_t pid, int signal)
2941 if (kill(pid, signal) < 0)
2942 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
2950 if (kill(-pid, signal) < 0)
2951 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) (-pid), signal);
2960 * Send a signal to all backend children, including autovacuum workers
2961 * (but NOT special children; dead_end children are never signaled, either).
2962 * If only_autovac is TRUE, only the autovacuum worker processes are signalled.
2965 SignalSomeChildren(int signal, bool only_autovac)
2969 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2971 Backend *bp = (Backend *) DLE_VAL(curr);
2975 if (only_autovac && !bp->is_autovacuum)
2979 (errmsg_internal("sending signal %d to process %d",
2980 signal, (int) bp->pid)));
2981 signal_child(bp->pid, signal);
2986 * BackendStartup -- start backend process
2988 * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
2990 * Note: if you change this code, also consider StartAutovacuumWorker.
2993 BackendStartup(Port *port)
2995 Backend *bn; /* for backend cleanup */
2999 * Create backend data structure. Better before the fork() so we can
3000 * handle failure cleanly.
3002 bn = (Backend *) malloc(sizeof(Backend));
3006 (errcode(ERRCODE_OUT_OF_MEMORY),
3007 errmsg("out of memory")));
3008 return STATUS_ERROR;
3012 * Compute the cancel key that will be assigned to this backend. The
3013 * backend will have its own copy in the forked-off process' value of
3014 * MyCancelKey, so that it can transmit the key to the frontend.
3016 MyCancelKey = PostmasterRandom();
3017 bn->cancel_key = MyCancelKey;
3019 /* Pass down canAcceptConnections state */
3020 port->canAcceptConnections = canAcceptConnections();
3021 bn->dead_end = (port->canAcceptConnections != CAC_OK &&
3022 port->canAcceptConnections != CAC_WAITBACKUP);
3025 * Unless it's a dead_end child, assign it a child slot number
3028 bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
3033 pid = backend_forkexec(port);
3034 #else /* !EXEC_BACKEND */
3035 pid = fork_process();
3036 if (pid == 0) /* child */
3041 * Let's clean up ourselves as the postmaster child, and close the
3042 * postmaster's listen sockets. (In EXEC_BACKEND case this is all
3043 * done in SubPostmasterMain.)
3045 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
3047 MyProcPid = getpid(); /* reset MyProcPid */
3049 MyStartTime = time(NULL);
3051 /* We don't want the postmaster's proc_exit() handlers */
3054 /* Close the postmaster's sockets */
3055 ClosePostmasterPorts(false);
3057 /* Perform additional initialization and client authentication */
3058 BackendInitialize(port);
3060 /* And run the backend */
3061 proc_exit(BackendRun(port));
3063 #endif /* EXEC_BACKEND */
3067 /* in parent, fork failed */
3068 int save_errno = errno;
3071 (void) ReleasePostmasterChildSlot(bn->child_slot);
3075 (errmsg("could not fork new process for connection: %m")));
3076 report_fork_failure_to_client(port, save_errno);
3077 return STATUS_ERROR;
3080 /* in parent, successful fork */
3082 (errmsg_internal("forked new backend, pid=%d socket=%d",
3083 (int) pid, port->sock)));
3086 * Everything's been successful, it's safe to add this backend to our list
3090 bn->is_autovacuum = false;
3091 DLInitElem(&bn->elem, bn);
3092 DLAddHead(BackendList, &bn->elem);
3095 ShmemBackendArrayAdd(bn);
3102 * Try to report backend fork() failure to client before we close the
3103 * connection. Since we do not care to risk blocking the postmaster on
3104 * this connection, we set the connection to non-blocking and try only once.
3106 * This is grungy special-purpose code; we cannot use backend libpq since
3107 * it's not up and running.
3110 report_fork_failure_to_client(Port *port, int errnum)
3115 /* Format the error message packet (always V2 protocol) */
3116 snprintf(buffer, sizeof(buffer), "E%s%s\n",
3117 _("could not fork new process for connection: "),
3120 /* Set port to non-blocking. Don't do send() if this fails */
3121 if (!pg_set_noblock(port->sock))
3124 /* We'll retry after EINTR, but ignore all other failures */
3127 rc = send(port->sock, buffer, strlen(buffer) + 1, 0);
3128 } while (rc < 0 && errno == EINTR);
3133 * split_opts -- split a string of options and append it to an argv array
3135 * NB: the string is destructively modified!
3137 * Since no current POSTGRES arguments require any quoting characters,
3138 * we can use the simple-minded tactic of assuming each set of space-
3139 * delimited characters is a separate argv element.
3141 * If you don't like that, well, we *used* to pass the whole option string
3142 * as ONE argument to execl(), which was even less intelligent...
3145 split_opts(char **argv, int *argcp, char *s)
3149 while (isspace((unsigned char) *s))
3153 argv[(*argcp)++] = s;
3154 while (*s && !isspace((unsigned char) *s))
3163 * BackendInitialize -- initialize an interactive (postmaster-child)
3164 * backend process, and perform client authentication.
3166 * returns: nothing. Will not return at all if there's any failure.
3168 * Note: this code does not depend on having any access to shared memory.
3169 * In the EXEC_BACKEND case, we are physically attached to shared memory
3170 * but have not yet set up most of our local pointers to shmem structures.
3173 BackendInitialize(Port *port)
3176 char remote_host[NI_MAXHOST];
3177 char remote_port[NI_MAXSERV];
3178 char remote_ps_data[NI_MAXHOST];
3180 /* Save port etc. for ps status */
3184 * PreAuthDelay is a debugging aid for investigating problems in the
3185 * authentication cycle: it can be set in postgresql.conf to allow time to
3186 * attach to the newly-forked backend with a debugger. (See also the -W
3187 * backend switch, which we allow clients to pass through PGOPTIONS, but
3188 * it is not honored until after authentication.)
3190 if (PreAuthDelay > 0)
3191 pg_usleep(PreAuthDelay * 1000000L);
3193 ClientAuthInProgress = true; /* limit visibility of log messages */
3195 /* save process start time */
3196 port->SessionStartTime = GetCurrentTimestamp();
3197 MyStartTime = timestamptz_to_time_t(port->SessionStartTime);
3199 /* set these to empty in case they are needed before we set them up */
3200 port->remote_host = "";
3201 port->remote_port = "";
3204 * Initialize libpq and enable reporting of ereport errors to the client.
3205 * Must do this now because authentication uses libpq to send messages.
3207 pq_init(); /* initialize libpq to talk to client */
3208 whereToSendOutput = DestRemote; /* now safe to ereport to client */
3211 * If possible, make this process a group leader, so that the postmaster
3212 * can signal any child processes too. (We do this now on the off chance
3213 * that something might spawn a child process during authentication.)
3217 elog(FATAL, "setsid() failed: %m");
3221 * We arrange for a simple exit(1) if we receive SIGTERM or SIGQUIT during
3222 * any client authentication related communication. Otherwise the
3223 * postmaster cannot shutdown the database FAST or IMMED cleanly if a
3224 * buggy client blocks a backend during authentication.
3226 pqsignal(SIGTERM, authdie);
3227 pqsignal(SIGQUIT, authdie);
3228 pqsignal(SIGALRM, authdie);
3229 PG_SETMASK(&AuthBlockSig);
3232 * Get the remote host name and port for logging and status display.
3234 remote_host[0] = '\0';
3235 remote_port[0] = '\0';
3236 if (pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
3237 remote_host, sizeof(remote_host),
3238 remote_port, sizeof(remote_port),
3239 (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV))
3241 int ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
3242 remote_host, sizeof(remote_host),
3243 remote_port, sizeof(remote_port),
3244 NI_NUMERICHOST | NI_NUMERICSERV);
3248 (errmsg_internal("pg_getnameinfo_all() failed: %s",
3249 gai_strerror(ret))));
3251 snprintf(remote_ps_data, sizeof(remote_ps_data),
3252 remote_port[0] == '\0' ? "%s" : "%s(%s)",
3253 remote_host, remote_port);
3255 if (Log_connections)
3257 (errmsg("connection received: host=%s%s%s",
3258 remote_host, remote_port[0] ? " port=" : "",
3262 * save remote_host and remote_port in port structure
3264 port->remote_host = strdup(remote_host);
3265 port->remote_port = strdup(remote_port);
3268 * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
3269 * etcetera from the postmaster, and have to load them ourselves. Build
3270 * the PostmasterContext (which didn't exist before, in this process) to
3273 * FIXME: [fork/exec] Ugh. Is there a way around this overhead?
3276 Assert(PostmasterContext == NULL);
3277 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
3279 ALLOCSET_DEFAULT_MINSIZE,
3280 ALLOCSET_DEFAULT_INITSIZE,
3281 ALLOCSET_DEFAULT_MAXSIZE);
3282 MemoryContextSwitchTo(PostmasterContext);
3287 * It makes no sense to continue if we fail to load the HBA file,
3288 * since there is no way to connect to the database in this case.
3291 (errmsg("could not load pg_hba.conf")));
3298 * Ready to begin client interaction. We will give up and exit(0) after a
3299 * time delay, so that a broken client can't hog a connection
3300 * indefinitely. PreAuthDelay doesn't count against the time limit.
3302 if (!enable_sig_alarm(AuthenticationTimeout * 1000, false))
3303 elog(FATAL, "could not set timer for authorization timeout");
3306 * Receive the startup packet (which might turn out to be a cancel request
3309 status = ProcessStartupPacket(port, false);
3311 if (status != STATUS_OK)
3315 * Now that we have the user and database name, we can set the process
3316 * title for ps. It's good to do this as early as possible in startup.
3318 init_ps_display(port->user_name, port->database_name, remote_ps_data,
3319 update_process_title ? "authentication" : "");
3322 * Now perform authentication exchange.
3324 ClientAuthentication(port); /* might not return, if failure */
3327 * Done with authentication. Disable timeout, and prevent SIGTERM/SIGQUIT
3328 * again until backend startup is complete.
3330 if (!disable_sig_alarm(false))
3331 elog(FATAL, "could not disable timer for authorization timeout");
3332 PG_SETMASK(&BlockSig);
3334 if (Log_connections)
3336 (errmsg("connection authorized: user=%s database=%s",
3337 port->user_name, port->database_name)));
3342 * BackendRun -- set up the backend's argument list and invoke PostgresMain()
3345 * Shouldn't return at all.
3346 * If PostgresMain() fails, return status.
3349 BackendRun(Port *port)
3360 * Don't want backend to be able to see the postmaster random number
3361 * generator state. We have to clobber the static random_seed *and* start
3362 * a new random sequence in the random() library function.
3365 random_start_time.tv_usec = 0;
3366 /* slightly hacky way to get integer microseconds part of timestamptz */
3367 TimestampDifference(0, port->SessionStartTime, &secs, &usecs);
3368 srandom((unsigned int) (MyProcPid ^ usecs));
3371 * Now, build the argv vector that will be given to PostgresMain.
3373 * The layout of the command line is
3374 * postgres [secure switches] -y databasename [insecure switches]
3375 * where the switches after -y come from the client request.
3377 * The maximum possible number of commandline arguments that could come
3378 * from ExtraOptions or port->cmdline_options is (strlen + 1) / 2; see
3382 maxac = 10; /* for fixed args supplied below */
3383 maxac += (strlen(ExtraOptions) + 1) / 2;
3384 if (port->cmdline_options)
3385 maxac += (strlen(port->cmdline_options) + 1) / 2;
3387 av = (char **) MemoryContextAlloc(TopMemoryContext,
3388 maxac * sizeof(char *));
3391 av[ac++] = "postgres";
3394 * Pass any backend switches specified with -o in the postmaster's own
3395 * command line. We assume these are secure. (It's OK to mangle
3396 * ExtraOptions now, since we're safely inside a subprocess.)
3398 split_opts(av, &ac, ExtraOptions);
3400 /* Tell the backend what protocol the frontend is using. */
3401 snprintf(protobuf, sizeof(protobuf), "-v%u", port->proto);
3402 av[ac++] = protobuf;
3405 * Tell the backend it is being called from the postmaster, and which
3406 * database to use. -y marks the end of secure switches.
3409 av[ac++] = port->database_name;
3412 * Pass the (insecure) option switches from the connection request. (It's
3413 * OK to mangle port->cmdline_options now.)
3415 if (port->cmdline_options)
3416 split_opts(av, &ac, port->cmdline_options);
3423 * Release postmaster's working memory context so that backend can recycle
3424 * the space. Note this does not trash *MyProcPort, because ConnCreate()
3425 * allocated that space with malloc() ... else we'd need to copy the Port
3426 * data here. Also, subsidiary data such as the username isn't lost
3427 * either; see ProcessStartupPacket().
3429 MemoryContextSwitchTo(TopMemoryContext);
3430 MemoryContextDelete(PostmasterContext);
3431 PostmasterContext = NULL;
3434 * Debug: print arguments being passed to backend
3437 (errmsg_internal("%s child[%d]: starting with (",
3438 progname, (int) getpid())));
3439 for (i = 0; i < ac; ++i)
3441 (errmsg_internal("\t%s", av[i])));
3443 (errmsg_internal(")")));
3445 ClientAuthInProgress = false; /* client_min_messages is active now */
3447 return (PostgresMain(ac, av, port->user_name));
3454 * postmaster_forkexec -- fork and exec a postmaster subprocess
3456 * The caller must have set up the argv array already, except for argv[2]
3457 * which will be filled with the name of the temp variable file.
3459 * Returns the child process PID, or -1 on fork failure (a suitable error
3460 * message has been logged on failure).
3462 * All uses of this routine will dispatch to SubPostmasterMain in the
3466 postmaster_forkexec(int argc, char *argv[])
3470 /* This entry point passes dummy values for the Port variables */
3471 memset(&port, 0, sizeof(port));
3472 return internal_forkexec(argc, argv, &port);
3476 * backend_forkexec -- fork/exec off a backend process
3478 * Some operating systems (WIN32) don't have fork() so we have to simulate
3479 * it by storing parameters that need to be passed to the child and
3480 * then create a new child process.
3482 * returns the pid of the fork/exec'd process, or -1 on failure
3485 backend_forkexec(Port *port)
3490 av[ac++] = "postgres";
3491 av[ac++] = "--forkbackend";
3492 av[ac++] = NULL; /* filled in by internal_forkexec */
3495 Assert(ac < lengthof(av));
3497 return internal_forkexec(ac, av, port);
3503 * internal_forkexec non-win32 implementation
3505 * - writes out backend variables to the parameter file
3506 * - fork():s, and then exec():s the child process
3509 internal_forkexec(int argc, char *argv[], Port *port)
3511 static unsigned long tmpBackendFileNum = 0;
3513 char tmpfilename[MAXPGPATH];
3514 BackendParameters param;
3517 if (!save_backend_variables(¶m, port))
3518 return -1; /* log made by save_backend_variables */
3520 /* Calculate name for temp file */
3521 snprintf(tmpfilename, MAXPGPATH, "%s/%s.backend_var.%d.%lu",
3522 PG_TEMP_FILES_DIR, PG_TEMP_FILE_PREFIX,
3523 MyProcPid, ++tmpBackendFileNum);
3526 fp = AllocateFile(tmpfilename, PG_BINARY_W);
3529 /* As in OpenTemporaryFile, try to make the temp-file directory */
3530 mkdir(PG_TEMP_FILES_DIR, S_IRWXU);
3532 fp = AllocateFile(tmpfilename, PG_BINARY_W);
3536 (errcode_for_file_access(),
3537 errmsg("could not create file \"%s\": %m",
3543 if (fwrite(¶m, sizeof(param), 1, fp) != 1)
3546 (errcode_for_file_access(),
3547 errmsg("could not write to file \"%s\": %m", tmpfilename)));
3556 (errcode_for_file_access(),
3557 errmsg("could not write to file \"%s\": %m", tmpfilename)));
3561 /* Make sure caller set up argv properly */
3563 Assert(argv[argc] == NULL);
3564 Assert(strncmp(argv[1], "--fork", 6) == 0);
3565 Assert(argv[2] == NULL);
3567 /* Insert temp file name after --fork argument */
3568 argv[2] = tmpfilename;
3570 /* Fire off execv in child */
3571 if ((pid = fork_process()) == 0)
3573 if (execv(postgres_exec_path, argv) < 0)
3576 (errmsg("could not execute server process \"%s\": %m",
3577 postgres_exec_path)));
3578 /* We're already in the child process here, can't return */
3583 return pid; /* Parent returns pid, or -1 on fork failure */
3588 * internal_forkexec win32 implementation
3590 * - starts backend using CreateProcess(), in suspended state
3591 * - writes out backend variables to the parameter file
3592 * - during this, duplicates handles and sockets required for
3593 * inheritance into the new process
3594 * - resumes execution of the new process once the backend parameter
3598 internal_forkexec(int argc, char *argv[], Port *port)
3601 PROCESS_INFORMATION pi;
3604 char cmdLine[MAXPGPATH * 2];
3606 BackendParameters *param;
3607 SECURITY_ATTRIBUTES sa;
3608 char paramHandleStr[32];
3609 win32_deadchild_waitinfo *childinfo;
3611 /* Make sure caller set up argv properly */
3613 Assert(argv[argc] == NULL);
3614 Assert(strncmp(argv[1], "--fork", 6) == 0);
3615 Assert(argv[2] == NULL);
3617 /* Set up shared memory for parameter passing */
3618 ZeroMemory(&sa, sizeof(sa));
3619 sa.nLength = sizeof(sa);
3620 sa.bInheritHandle = TRUE;
3621 paramHandle = CreateFileMapping(INVALID_HANDLE_VALUE,
3625 sizeof(BackendParameters),
3627 if (paramHandle == INVALID_HANDLE_VALUE)
3629 elog(LOG, "could not create backend parameter file mapping: error code %d",
3630 (int) GetLastError());
3634 param = MapViewOfFile(paramHandle, FILE_MAP_WRITE, 0, 0, sizeof(BackendParameters));
3637 elog(LOG, "could not map backend parameter memory: error code %d",
3638 (int) GetLastError());
3639 CloseHandle(paramHandle);
3643 /* Insert temp file name after --fork argument */
3644 sprintf(paramHandleStr, "%lu", (DWORD) paramHandle);
3645 argv[2] = paramHandleStr;
3647 /* Format the cmd line */
3648 cmdLine[sizeof(cmdLine) - 1] = '\0';
3649 cmdLine[sizeof(cmdLine) - 2] = '\0';
3650 snprintf(cmdLine, sizeof(cmdLine) - 1, "\"%s\"", postgres_exec_path);
3652 while (argv[++i] != NULL)
3654 j = strlen(cmdLine);
3655 snprintf(cmdLine + j, sizeof(cmdLine) - 1 - j, " \"%s\"", argv[i]);
3657 if (cmdLine[sizeof(cmdLine) - 2] != '\0')
3659 elog(LOG, "subprocess command line too long");
3663 memset(&pi, 0, sizeof(pi));
3664 memset(&si, 0, sizeof(si));
3668 * Create the subprocess in a suspended state. This will be resumed later,
3669 * once we have written out the parameter file.
3671 if (!CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, CREATE_SUSPENDED,
3672 NULL, NULL, &si, &pi))
3674 elog(LOG, "CreateProcess call failed: %m (error code %d)",
3675 (int) GetLastError());
3679 if (!save_backend_variables(param, port, pi.hProcess, pi.dwProcessId))
3682 * log made by save_backend_variables, but we have to clean up the
3683 * mess with the half-started process
3685 if (!TerminateProcess(pi.hProcess, 255))
3687 (errmsg_internal("could not terminate unstarted process: error code %d",
3688 (int) GetLastError())));
3689 CloseHandle(pi.hProcess);
3690 CloseHandle(pi.hThread);
3691 return -1; /* log made by save_backend_variables */
3694 /* Drop the parameter shared memory that is now inherited to the backend */
3695 if (!UnmapViewOfFile(param))
3696 elog(LOG, "could not unmap view of backend parameter file: error code %d",
3697 (int) GetLastError());
3698 if (!CloseHandle(paramHandle))
3699 elog(LOG, "could not close handle to backend parameter file: error code %d",
3700 (int) GetLastError());
3703 * Reserve the memory region used by our main shared memory segment before we
3704 * resume the child process.
3706 if (!pgwin32_ReserveSharedMemoryRegion(pi.hProcess))
3709 * Failed to reserve the memory, so terminate the newly created
3710 * process and give up.
3712 if (!TerminateProcess(pi.hProcess, 255))
3714 (errmsg_internal("could not terminate process that failed to reserve memory: error code %d",
3715 (int) GetLastError())));
3716 CloseHandle(pi.hProcess);
3717 CloseHandle(pi.hThread);
3718 return -1; /* logging done made by pgwin32_ReserveSharedMemoryRegion() */
3722 * Now that the backend variables are written out, we start the child
3723 * thread so it can start initializing while we set up the rest of the
3726 if (ResumeThread(pi.hThread) == -1)
3728 if (!TerminateProcess(pi.hProcess, 255))
3731 (errmsg_internal("could not terminate unstartable process: error code %d",
3732 (int) GetLastError())));
3733 CloseHandle(pi.hProcess);
3734 CloseHandle(pi.hThread);
3737 CloseHandle(pi.hProcess);
3738 CloseHandle(pi.hThread);
3740 (errmsg_internal("could not resume thread of unstarted process: error code %d",
3741 (int) GetLastError())));
3746 * Queue a waiter for to signal when this child dies. The wait will be
3747 * handled automatically by an operating system thread pool.
3749 * Note: use malloc instead of palloc, since it needs to be thread-safe.
3750 * Struct will be free():d from the callback function that runs on a
3753 childinfo = malloc(sizeof(win32_deadchild_waitinfo));
3756 (errcode(ERRCODE_OUT_OF_MEMORY),
3757 errmsg("out of memory")));
3759 childinfo->procHandle = pi.hProcess;
3760 childinfo->procId = pi.dwProcessId;
3762 if (!RegisterWaitForSingleObject(&childinfo->waitHandle,
3764 pgwin32_deadchild_callback,
3767 WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD))
3769 (errmsg_internal("could not register process for wait: error code %d",
3770 (int) GetLastError())));
3772 /* Don't close pi.hProcess here - the wait thread needs access to it */
3774 CloseHandle(pi.hThread);
3776 return pi.dwProcessId;
3782 * SubPostmasterMain -- Get the fork/exec'd process into a state equivalent
3783 * to what it would be if we'd simply forked on Unix, and then
3784 * dispatch to the appropriate place.
3786 * The first two command line arguments are expected to be "--forkFOO"
3787 * (where FOO indicates which postmaster child we are to become), and
3788 * the name of a variables file that we can read to load data that would
3789 * have been inherited by fork() on Unix. Remaining arguments go to the
3790 * subprocess FooMain() routine.
3793 SubPostmasterMain(int argc, char *argv[])
3797 /* Do this sooner rather than later... */
3798 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
3800 MyProcPid = getpid(); /* reset MyProcPid */
3802 MyStartTime = time(NULL);
3805 * make sure stderr is in binary mode before anything can possibly be
3806 * written to it, in case it's actually the syslogger pipe, so the pipe
3807 * chunking protocol isn't disturbed. Non-logpipe data gets translated on
3808 * redirection (e.g. via pg_ctl -l) anyway.
3811 _setmode(fileno(stderr), _O_BINARY);
3814 /* Lose the postmaster's on-exit routines (really a no-op) */
3817 /* In EXEC_BACKEND case we will not have inherited these settings */
3818 IsPostmasterEnvironment = true;
3819 whereToSendOutput = DestNone;
3821 /* Setup essential subsystems (to ensure elog() behaves sanely) */
3822 MemoryContextInit();
3823 InitializeGUCOptions();
3825 /* Read in the variables file */
3826 memset(&port, 0, sizeof(Port));
3827 read_backend_variables(argv[2], &port);
3830 * Set up memory area for GSS information. Mirrors the code in ConnCreate
3831 * for the non-exec case.
3833 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
3834 port.gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
3837 (errcode(ERRCODE_OUT_OF_MEMORY),
3838 errmsg("out of memory")));
3842 /* Check we got appropriate args */
3844 elog(FATAL, "invalid subpostmaster invocation");
3847 * If appropriate, physically re-attach to shared memory segment. We want
3848 * to do this before going any further to ensure that we can attach at the
3849 * same address the postmaster used.
3851 if (strcmp(argv[1], "--forkbackend") == 0 ||
3852 strcmp(argv[1], "--forkavlauncher") == 0 ||
3853 strcmp(argv[1], "--forkavworker") == 0 ||
3854 strcmp(argv[1], "--forkboot") == 0)
3855 PGSharedMemoryReAttach();
3857 /* autovacuum needs this set before calling InitProcess */
3858 if (strcmp(argv[1], "--forkavlauncher") == 0)
3859 AutovacuumLauncherIAm();
3860 if (strcmp(argv[1], "--forkavworker") == 0)
3861 AutovacuumWorkerIAm();
3864 * Start our win32 signal implementation. This has to be done after we
3865 * read the backend variables, because we need to pick up the signal pipe
3866 * from the parent process.
3869 pgwin32_signal_initialize();
3872 /* In EXEC_BACKEND case we will not have inherited these settings */
3874 PG_SETMASK(&BlockSig);
3876 /* Read in remaining GUC variables */
3877 read_nondefault_variables();
3880 * Reload any libraries that were preloaded by the postmaster. Since we
3881 * exec'd this process, those libraries didn't come along with us; but we
3882 * should load them into all child processes to be consistent with the
3883 * non-EXEC_BACKEND behavior.
3885 process_shared_preload_libraries();
3887 /* Run backend or appropriate child */
3888 if (strcmp(argv[1], "--forkbackend") == 0)
3890 Assert(argc == 3); /* shouldn't be any more args */
3892 /* Close the postmaster's sockets */
3893 ClosePostmasterPorts(false);
3896 * Need to reinitialize the SSL library in the backend, since the
3897 * context structures contain function pointers and cannot be passed
3898 * through the parameter file.
3900 * XXX should we do this in all child processes? For the moment it's
3901 * enough to do it in backend children.
3905 secure_initialize();
3909 * Perform additional initialization and client authentication.
3911 * We want to do this before InitProcess() for a couple of reasons: 1.
3912 * so that we aren't eating up a PGPROC slot while waiting on the
3913 * client. 2. so that if InitProcess() fails due to being out of
3914 * PGPROC slots, we have already initialized libpq and are able to
3915 * report the error to the client.
3917 BackendInitialize(&port);
3919 /* Restore basic shared memory pointers */
3920 InitShmemAccess(UsedShmemSegAddr);
3922 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3926 * Attach process to shared data structures. If testing EXEC_BACKEND
3927 * on Linux, you must run this as root before starting the postmaster:
3929 * echo 0 >/proc/sys/kernel/randomize_va_space
3931 * This prevents a randomized stack base address that causes child
3932 * shared memory to be at a different address than the parent, making
3933 * it impossible to attached to shared memory. Return the value to
3934 * '1' when finished.
3936 CreateSharedMemoryAndSemaphores(false, 0);
3938 /* And run the backend */
3939 proc_exit(BackendRun(&port));
3941 if (strcmp(argv[1], "--forkboot") == 0)
3943 /* Close the postmaster's sockets */
3944 ClosePostmasterPorts(false);
3946 /* Restore basic shared memory pointers */
3947 InitShmemAccess(UsedShmemSegAddr);
3949 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3950 InitAuxiliaryProcess();
3952 /* Attach process to shared data structures */
3953 CreateSharedMemoryAndSemaphores(false, 0);
3955 AuxiliaryProcessMain(argc - 2, argv + 2);
3958 if (strcmp(argv[1], "--forkavlauncher") == 0)
3960 /* Close the postmaster's sockets */
3961 ClosePostmasterPorts(false);
3963 /* Restore basic shared memory pointers */
3964 InitShmemAccess(UsedShmemSegAddr);
3966 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3967 InitAuxiliaryProcess();
3969 /* Attach process to shared data structures */
3970 CreateSharedMemoryAndSemaphores(false, 0);
3972 AutoVacLauncherMain(argc - 2, argv + 2);
3975 if (strcmp(argv[1], "--forkavworker") == 0)
3977 /* Close the postmaster's sockets */
3978 ClosePostmasterPorts(false);
3980 /* Restore basic shared memory pointers */
3981 InitShmemAccess(UsedShmemSegAddr);
3983 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3986 /* Attach process to shared data structures */
3987 CreateSharedMemoryAndSemaphores(false, 0);
3989 AutoVacWorkerMain(argc - 2, argv + 2);
3992 if (strcmp(argv[1], "--forkarch") == 0)
3994 /* Close the postmaster's sockets */
3995 ClosePostmasterPorts(false);
3997 /* Do not want to attach to shared memory */
3999 PgArchiverMain(argc, argv);
4002 if (strcmp(argv[1], "--forkcol") == 0)
4004 /* Close the postmaster's sockets */
4005 ClosePostmasterPorts(false);
4007 /* Do not want to attach to shared memory */
4009 PgstatCollectorMain(argc, argv);
4012 if (strcmp(argv[1], "--forklog") == 0)
4014 /* Close the postmaster's sockets */
4015 ClosePostmasterPorts(true);
4017 /* Do not want to attach to shared memory */
4019 SysLoggerMain(argc, argv);
4023 return 1; /* shouldn't get here */
4025 #endif /* EXEC_BACKEND */
4029 * ExitPostmaster -- cleanup
4031 * Do NOT call exit() directly --- always go through here!
4034 ExitPostmaster(int status)
4036 /* should cleanup shared memory and kill all backends */
4039 * Not sure of the semantics here. When the Postmaster dies, should the
4040 * backends all be killed? probably not.
4042 * MUST -- vadim 05-10-1999
4049 * sigusr1_handler - handle signal conditions from child processes
4052 sigusr1_handler(SIGNAL_ARGS)
4054 int save_errno = errno;
4056 PG_SETMASK(&BlockSig);
4059 * RECOVERY_STARTED and RECOVERY_CONSISTENT signals are ignored in
4060 * unexpected states. If the startup process quickly starts up, completes
4061 * recovery, exits, we might process the death of the startup process
4062 * first. We don't want to go back to recovery in that case.
4064 if (CheckPostmasterSignal(PMSIGNAL_RECOVERY_STARTED) &&
4065 pmState == PM_STARTUP)
4067 /* WAL redo has started. We're out of reinitialization. */
4071 * Crank up the background writer. It doesn't matter if this fails,
4072 * we'll just try again later.
4074 Assert(BgWriterPID == 0);
4075 BgWriterPID = StartBackgroundWriter();
4077 pmState = PM_RECOVERY;
4079 if (CheckPostmasterSignal(PMSIGNAL_RECOVERY_CONSISTENT) &&
4080 pmState == PM_RECOVERY)
4083 * Load the flat authorization file into postmaster's cache. The
4084 * startup process won't have recomputed this from the database yet,
4085 * so it may change following recovery.
4090 * Likewise, start other special children as needed.
4092 Assert(PgStatPID == 0);
4093 PgStatPID = pgstat_start();
4095 /* XXX at this point we could accept read-only connections */
4097 (errmsg("database system is in consistent recovery mode")));
4099 pmState = PM_RECOVERY_CONSISTENT;
4102 if (CheckPostmasterSignal(PMSIGNAL_PASSWORD_CHANGE))
4105 * Authorization file has changed.
4110 if (CheckPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER) &&
4114 * Send SIGUSR1 to archiver process, to wake it up and begin archiving
4115 * next transaction log file.
4117 signal_child(PgArchPID, SIGUSR1);
4120 if (CheckPostmasterSignal(PMSIGNAL_ROTATE_LOGFILE) &&
4123 /* Tell syslogger to rotate logfile */
4124 signal_child(SysLoggerPID, SIGUSR1);
4127 if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER))
4130 * Start one iteration of the autovacuum daemon, even if autovacuuming
4131 * is nominally not enabled. This is so we can have an active defense
4132 * against transaction ID wraparound. We set a flag for the main loop
4133 * to do it rather than trying to do it here --- this is because the
4134 * autovac process itself may send the signal, and we want to handle
4135 * that by launching another iteration as soon as the current one
4138 start_autovac_launcher = true;
4141 if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER))
4143 /* The autovacuum launcher wants us to start a worker process. */
4144 StartAutovacuumWorker();
4147 PG_SETMASK(&UnBlockSig);
4154 * Dummy signal handler
4156 * We use this for signals that we don't actually use in the postmaster,
4157 * but we do use in backends. If we were to SIG_IGN such signals in the
4158 * postmaster, then a newly started backend might drop a signal that arrives
4159 * before it's able to reconfigure its signal processing. (See notes in
4163 dummy_handler(SIGNAL_ARGS)
4171 RandomSalt(char *md5Salt)
4176 * We use % 255, sacrificing one possible byte value, so as to ensure that
4177 * all bits of the random() value participate in the result. While at it,
4178 * add one to avoid generating any null bytes.
4180 rand = PostmasterRandom();
4181 md5Salt[0] = (rand % 255) + 1;
4182 rand = PostmasterRandom();
4183 md5Salt[1] = (rand % 255) + 1;
4184 rand = PostmasterRandom();
4185 md5Salt[2] = (rand % 255) + 1;
4186 rand = PostmasterRandom();
4187 md5Salt[3] = (rand % 255) + 1;
4194 PostmasterRandom(void)
4197 * Select a random seed at the time of first receiving a request.
4199 if (random_seed == 0)
4203 struct timeval random_stop_time;
4205 gettimeofday(&random_stop_time, NULL);
4208 * We are not sure how much precision is in tv_usec, so we swap
4209 * the high and low 16 bits of 'random_stop_time' and XOR them
4210 * with 'random_start_time'. On the off chance that the result is
4211 * 0, we loop until it isn't.
4213 random_seed = random_start_time.tv_usec ^
4214 ((random_stop_time.tv_usec << 16) |
4215 ((random_stop_time.tv_usec >> 16) & 0xffff));
4217 while (random_seed == 0);
4219 srandom(random_seed);
4226 * Count up number of child processes (excluding special children and
4227 * dead_end children)
4235 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
4237 Backend *bp = (Backend *) DLE_VAL(curr);
4247 * StartChildProcess -- start an auxiliary process for the postmaster
4249 * xlop determines what kind of child will be started. All child types
4250 * initially go to AuxiliaryProcessMain, which will handle common setup.
4252 * Return value of StartChildProcess is subprocess' PID, or 0 if failed
4253 * to start subprocess.
4256 StartChildProcess(AuxProcType type)
4264 * Set up command-line arguments for subprocess
4266 av[ac++] = "postgres";
4269 av[ac++] = "--forkboot";
4270 av[ac++] = NULL; /* filled in by postmaster_forkexec */
4273 snprintf(typebuf, sizeof(typebuf), "-x%d", type);
4277 Assert(ac < lengthof(av));
4280 pid = postmaster_forkexec(ac, av);
4281 #else /* !EXEC_BACKEND */
4282 pid = fork_process();
4284 if (pid == 0) /* child */
4286 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
4288 /* Close the postmaster's sockets */
4289 ClosePostmasterPorts(false);
4291 /* Lose the postmaster's on-exit routines and port connections */
4294 /* Release postmaster's working memory context */
4295 MemoryContextSwitchTo(TopMemoryContext);
4296 MemoryContextDelete(PostmasterContext);
4297 PostmasterContext = NULL;
4299 AuxiliaryProcessMain(ac, av);
4302 #endif /* EXEC_BACKEND */
4306 /* in parent, fork failed */
4307 int save_errno = errno;
4312 case StartupProcess:
4314 (errmsg("could not fork startup process: %m")));
4316 case BgWriterProcess:
4318 (errmsg("could not fork background writer process: %m")));
4320 case WalWriterProcess:
4322 (errmsg("could not fork WAL writer process: %m")));
4326 (errmsg("could not fork process: %m")));
4331 * fork failure is fatal during startup, but there's no need to choke
4332 * immediately if starting other child types fails.
4334 if (type == StartupProcess)
4340 * in parent, successful fork
4346 * StartAutovacuumWorker
4347 * Start an autovac worker process.
4349 * This function is here because it enters the resulting PID into the
4350 * postmaster's private backends list.
4352 * NB -- this code very roughly matches BackendStartup.
4355 StartAutovacuumWorker(void)
4360 * If not in condition to run a process, don't try, but handle it like a
4361 * fork failure. This does not normally happen, since the signal is only
4362 * supposed to be sent by autovacuum launcher when it's OK to do it, but
4363 * we have to check to avoid race-condition problems during DB state
4366 if (canAcceptConnections() == CAC_OK)
4368 bn = (Backend *) malloc(sizeof(Backend));
4372 * Compute the cancel key that will be assigned to this session.
4373 * We probably don't need cancel keys for autovac workers, but
4374 * we'd better have something random in the field to prevent
4375 * unfriendly people from sending cancels to them.
4377 MyCancelKey = PostmasterRandom();
4378 bn->cancel_key = MyCancelKey;
4380 /* Autovac workers are not dead_end and need a child slot */
4381 bn->dead_end = false;
4382 bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
4384 bn->pid = StartAutoVacWorker();
4387 bn->is_autovacuum = true;
4388 DLInitElem(&bn->elem, bn);
4389 DLAddHead(BackendList, &bn->elem);
4391 ShmemBackendArrayAdd(bn);
4398 * fork failed, fall through to report -- actual error message was
4399 * logged by StartAutoVacWorker
4401 (void) ReleasePostmasterChildSlot(bn->child_slot);
4406 (errcode(ERRCODE_OUT_OF_MEMORY),
4407 errmsg("out of memory")));
4411 * Report the failure to the launcher, if it's running. (If it's not, we
4412 * might not even be connected to shared memory, so don't try to call
4413 * AutoVacWorkerFailed.) Note that we also need to signal it so that it
4414 * responds to the condition, but we don't do that here, instead waiting
4415 * for ServerLoop to do it. This way we avoid a ping-pong signalling in
4416 * quick succession between the autovac launcher and postmaster in case
4419 if (AutoVacPID != 0)
4421 AutoVacWorkerFailed();
4422 avlauncher_needs_signal = true;
4427 * Create the opts file
4430 CreateOptsFile(int argc, char *argv[], char *fullprogname)
4435 #define OPTS_FILE "postmaster.opts"
4437 if ((fp = fopen(OPTS_FILE, "w")) == NULL)
4439 elog(LOG, "could not create file \"%s\": %m", OPTS_FILE);
4443 fprintf(fp, "%s", fullprogname);
4444 for (i = 1; i < argc; i++)
4445 fprintf(fp, " \"%s\"", argv[i]);
4450 elog(LOG, "could not write file \"%s\": %m", OPTS_FILE);
4459 * MaxLivePostmasterChildren
4461 * This reports the number of entries needed in per-child-process arrays
4462 * (the PMChildFlags array, and if EXEC_BACKEND the ShmemBackendArray).
4463 * These arrays include regular backends and autovac workers, but not special
4464 * children nor dead_end children. This allows the arrays to have a fixed
4465 * maximum size, to wit the same too-many-children limit enforced by
4466 * canAcceptConnections(). The exact value isn't too critical as long as
4467 * it's more than MaxBackends.
4470 MaxLivePostmasterChildren(void)
4472 return 2 * MaxBackends;
4479 * The following need to be available to the save/restore_backend_variables
4482 extern slock_t *ShmemLock;
4483 extern LWLock *LWLockArray;
4484 extern slock_t *ProcStructLock;
4485 extern PROC_HDR *ProcGlobal;
4486 extern PGPROC *AuxiliaryProcs;
4487 extern PMSignalData *PMSignalState;
4488 extern int pgStatSock;
4491 #define write_inheritable_socket(dest, src, childpid) (*(dest) = (src))
4492 #define read_inheritable_socket(dest, src) (*(dest) = *(src))
4494 static bool write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE child);
4495 static bool write_inheritable_socket(InheritableSocket *dest, SOCKET src,
4497 static void read_inheritable_socket(SOCKET *dest, InheritableSocket *src);
4501 /* Save critical backend variables into the BackendParameters struct */
4504 save_backend_variables(BackendParameters *param, Port *port)
4507 save_backend_variables(BackendParameters *param, Port *port,
4508 HANDLE childProcess, pid_t childPid)
4511 memcpy(¶m->port, port, sizeof(Port));
4512 if (!write_inheritable_socket(¶m->portsocket, port->sock, childPid))
4515 strlcpy(param->DataDir, DataDir, MAXPGPATH);
4517 memcpy(¶m->ListenSocket, &ListenSocket, sizeof(ListenSocket));
4519 param->MyCancelKey = MyCancelKey;
4520 param->MyPMChildSlot = MyPMChildSlot;
4522 param->UsedShmemSegID = UsedShmemSegID;
4523 param->UsedShmemSegAddr = UsedShmemSegAddr;
4525 param->ShmemLock = ShmemLock;
4526 param->ShmemVariableCache = ShmemVariableCache;
4527 param->ShmemBackendArray = ShmemBackendArray;
4529 param->LWLockArray = LWLockArray;
4530 param->ProcStructLock = ProcStructLock;
4531 param->ProcGlobal = ProcGlobal;
4532 param->AuxiliaryProcs = AuxiliaryProcs;
4533 param->PMSignalState = PMSignalState;
4534 if (!write_inheritable_socket(¶m->pgStatSock, pgStatSock, childPid))
4537 param->PostmasterPid = PostmasterPid;
4538 param->PgStartTime = PgStartTime;
4539 param->PgReloadTime = PgReloadTime;
4541 param->redirection_done = redirection_done;
4544 param->PostmasterHandle = PostmasterHandle;
4545 if (!write_duplicated_handle(¶m->initial_signal_pipe,
4546 pgwin32_create_signal_listener(childPid),
4551 memcpy(¶m->syslogPipe, &syslogPipe, sizeof(syslogPipe));
4553 strlcpy(param->my_exec_path, my_exec_path, MAXPGPATH);
4555 strlcpy(param->pkglib_path, pkglib_path, MAXPGPATH);
4557 strlcpy(param->ExtraOptions, ExtraOptions, MAXPGPATH);
4565 * Duplicate a handle for usage in a child process, and write the child
4566 * process instance of the handle to the parameter file.
4569 write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE childProcess)
4571 HANDLE hChild = INVALID_HANDLE_VALUE;
4573 if (!DuplicateHandle(GetCurrentProcess(),
4579 DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS))
4582 (errmsg_internal("could not duplicate handle to be written to backend parameter file: error code %d",
4583 (int) GetLastError())));
4592 * Duplicate a socket for usage in a child process, and write the resulting
4593 * structure to the parameter file.
4594 * This is required because a number of LSPs (Layered Service Providers) very
4595 * common on Windows (antivirus, firewalls, download managers etc) break
4596 * straight socket inheritance.
4599 write_inheritable_socket(InheritableSocket *dest, SOCKET src, pid_t childpid)
4601 dest->origsocket = src;
4602 if (src != 0 && src != -1)
4605 if (WSADuplicateSocket(src, childpid, &dest->wsainfo) != 0)
4608 (errmsg("could not duplicate socket %d for use in backend: error code %d",
4609 src, WSAGetLastError())));
4617 * Read a duplicate socket structure back, and get the socket descriptor.
4620 read_inheritable_socket(SOCKET *dest, InheritableSocket *src)
4624 if (src->origsocket == -1 || src->origsocket == 0)
4626 /* Not a real socket! */
4627 *dest = src->origsocket;
4631 /* Actual socket, so create from structure */
4632 s = WSASocket(FROM_PROTOCOL_INFO,
4638 if (s == INVALID_SOCKET)
4640 write_stderr("could not create inherited socket: error code %d\n",
4647 * To make sure we don't get two references to the same socket, close
4648 * the original one. (This would happen when inheritance actually
4651 closesocket(src->origsocket);
4657 read_backend_variables(char *id, Port *port)
4659 BackendParameters param;
4662 /* Non-win32 implementation reads from file */
4666 fp = AllocateFile(id, PG_BINARY_R);
4669 write_stderr("could not read from backend variables file \"%s\": %s\n",
4670 id, strerror(errno));
4674 if (fread(¶m, sizeof(param), 1, fp) != 1)
4676 write_stderr("could not read from backend variables file \"%s\": %s\n",
4677 id, strerror(errno));
4683 if (unlink(id) != 0)
4685 write_stderr("could not remove file \"%s\": %s\n",
4686 id, strerror(errno));
4690 /* Win32 version uses mapped file */
4692 BackendParameters *paramp;
4694 paramHandle = (HANDLE) atol(id);
4695 paramp = MapViewOfFile(paramHandle, FILE_MAP_READ, 0, 0, 0);
4698 write_stderr("could not map view of backend variables: error code %d\n",
4699 (int) GetLastError());
4703 memcpy(¶m, paramp, sizeof(BackendParameters));
4705 if (!UnmapViewOfFile(paramp))
4707 write_stderr("could not unmap view of backend variables: error code %d\n",
4708 (int) GetLastError());
4712 if (!CloseHandle(paramHandle))
4714 write_stderr("could not close handle to backend parameter variables: error code %d\n",
4715 (int) GetLastError());
4720 restore_backend_variables(¶m, port);
4723 /* Restore critical backend variables from the BackendParameters struct */
4725 restore_backend_variables(BackendParameters *param, Port *port)
4727 memcpy(port, ¶m->port, sizeof(Port));
4728 read_inheritable_socket(&port->sock, ¶m->portsocket);
4730 SetDataDir(param->DataDir);
4732 memcpy(&ListenSocket, ¶m->ListenSocket, sizeof(ListenSocket));
4734 MyCancelKey = param->MyCancelKey;
4735 MyPMChildSlot = param->MyPMChildSlot;
4737 UsedShmemSegID = param->UsedShmemSegID;
4738 UsedShmemSegAddr = param->UsedShmemSegAddr;
4740 ShmemLock = param->ShmemLock;
4741 ShmemVariableCache = param->ShmemVariableCache;
4742 ShmemBackendArray = param->ShmemBackendArray;
4744 LWLockArray = param->LWLockArray;
4745 ProcStructLock = param->ProcStructLock;
4746 ProcGlobal = param->ProcGlobal;
4747 AuxiliaryProcs = param->AuxiliaryProcs;
4748 PMSignalState = param->PMSignalState;
4749 read_inheritable_socket(&pgStatSock, ¶m->pgStatSock);
4751 PostmasterPid = param->PostmasterPid;
4752 PgStartTime = param->PgStartTime;
4753 PgReloadTime = param->PgReloadTime;
4755 redirection_done = param->redirection_done;
4758 PostmasterHandle = param->PostmasterHandle;
4759 pgwin32_initial_signal_pipe = param->initial_signal_pipe;
4762 memcpy(&syslogPipe, ¶m->syslogPipe, sizeof(syslogPipe));
4764 strlcpy(my_exec_path, param->my_exec_path, MAXPGPATH);
4766 strlcpy(pkglib_path, param->pkglib_path, MAXPGPATH);
4768 strlcpy(ExtraOptions, param->ExtraOptions, MAXPGPATH);
4773 ShmemBackendArraySize(void)
4775 return mul_size(MaxLivePostmasterChildren(), sizeof(Backend));
4779 ShmemBackendArrayAllocation(void)
4781 Size size = ShmemBackendArraySize();
4783 ShmemBackendArray = (Backend *) ShmemAlloc(size);
4784 /* Mark all slots as empty */
4785 memset(ShmemBackendArray, 0, size);
4789 ShmemBackendArrayAdd(Backend *bn)
4791 /* The array slot corresponding to my PMChildSlot should be free */
4792 int i = bn->child_slot - 1;
4794 Assert(ShmemBackendArray[i].pid == 0);
4795 ShmemBackendArray[i] = *bn;
4799 ShmemBackendArrayRemove(Backend *bn)
4801 int i = bn->child_slot - 1;
4803 Assert(ShmemBackendArray[i].pid == bn->pid);
4804 /* Mark the slot as empty */
4805 ShmemBackendArray[i].pid = 0;
4807 #endif /* EXEC_BACKEND */
4813 win32_waitpid(int *exitstatus)
4820 * Check if there are any dead children. If there are, return the pid of
4821 * the first one that died.
4823 if (GetQueuedCompletionStatus(win32ChildQueue, &dwd, &key, &ovl, 0))
4825 *exitstatus = (int) key;
4833 * Note! Code below executes on a thread pool! All operations must
4834 * be thread safe! Note that elog() and friends must *not* be used.
4837 pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
4839 win32_deadchild_waitinfo *childinfo = (win32_deadchild_waitinfo *) lpParameter;
4842 if (TimerOrWaitFired)
4843 return; /* timeout. Should never happen, since we use
4844 * INFINITE as timeout value. */
4847 * Remove handle from wait - required even though it's set to wait only
4850 UnregisterWaitEx(childinfo->waitHandle, NULL);
4852 if (!GetExitCodeProcess(childinfo->procHandle, &exitcode))
4855 * Should never happen. Inform user and set a fixed exitcode.
4857 write_stderr("could not read exit code for process\n");
4861 if (!PostQueuedCompletionStatus(win32ChildQueue, childinfo->procId, (ULONG_PTR) exitcode, NULL))
4862 write_stderr("could not post child completion status\n");
4865 * Handle is per-process, so we close it here instead of in the
4866 * originating thread
4868 CloseHandle(childinfo->procHandle);
4871 * Free struct that was allocated before the call to
4872 * RegisterWaitForSingleObject()
4876 /* Queue SIGCHLD signal */
4877 pg_queue_signal(SIGCHLD);