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.585 2009/07/24 20:12:42 mha 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 (-S) */
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;
295 * State for assigning random salts and cancel keys.
296 * Also, the global MyCancelKey passes the cancel key assigned to a given
297 * backend from the postmaster to that backend (via fork).
299 static unsigned int random_seed = 0;
300 static struct timeval random_start_time;
306 #ifdef HAVE_INT_OPTRESET
307 extern int optreset; /* might not be declared by system headers */
311 * postmaster.c - function prototypes
313 static void getInstallationPaths(const char *argv0);
314 static void checkDataDir(void);
317 static void reg_reply(DNSServiceRegistrationReplyErrorType errorCode,
320 static void pmdaemonize(void);
321 static Port *ConnCreate(int serverFd);
322 static void ConnFree(Port *port);
323 static void reset_shared(int port);
324 static void SIGHUP_handler(SIGNAL_ARGS);
325 static void pmdie(SIGNAL_ARGS);
326 static void reaper(SIGNAL_ARGS);
327 static void sigusr1_handler(SIGNAL_ARGS);
328 static void dummy_handler(SIGNAL_ARGS);
329 static void CleanupBackend(int pid, int exitstatus);
330 static void HandleChildCrash(int pid, int exitstatus, const char *procname);
331 static void LogChildExit(int lev, const char *procname,
332 int pid, int exitstatus);
333 static void PostmasterStateMachine(void);
334 static void BackendInitialize(Port *port);
335 static int BackendRun(Port *port);
336 static void ExitPostmaster(int status);
337 static int ServerLoop(void);
338 static int BackendStartup(Port *port);
339 static int ProcessStartupPacket(Port *port, bool SSLdone);
340 static void processCancelRequest(Port *port, void *pkt);
341 static int initMasks(fd_set *rmask);
342 static void report_fork_failure_to_client(Port *port, int errnum);
343 static enum CAC_state canAcceptConnections(void);
344 static long PostmasterRandom(void);
345 static void RandomSalt(char *md5Salt);
346 static void signal_child(pid_t pid, int signal);
347 static void SignalSomeChildren(int signal, bool only_autovac);
349 #define SignalChildren(sig) SignalSomeChildren(sig, false)
350 #define SignalAutovacWorkers(sig) SignalSomeChildren(sig, true)
351 static int CountChildren(void);
352 static bool CreateOptsFile(int argc, char *argv[], char *fullprogname);
353 static pid_t StartChildProcess(AuxProcType type);
354 static void StartAutovacuumWorker(void);
359 static pid_t win32_waitpid(int *exitstatus);
360 static void WINAPI pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired);
362 static HANDLE win32ChildQueue;
369 } win32_deadchild_waitinfo;
371 HANDLE PostmasterHandle;
374 static pid_t backend_forkexec(Port *port);
375 static pid_t internal_forkexec(int argc, char *argv[], Port *port);
377 /* Type for a socket that can be inherited to a client process */
381 SOCKET origsocket; /* Original socket value, or -1 if not a
383 WSAPROTOCOL_INFO wsainfo;
386 typedef int InheritableSocket;
389 typedef struct LWLock LWLock; /* ugly kluge */
392 * Structure contains all variables passed to exec:ed backends
397 InheritableSocket portsocket;
398 char DataDir[MAXPGPATH];
399 int ListenSocket[MAXLISTEN];
402 unsigned long UsedShmemSegID;
403 void *UsedShmemSegAddr;
405 VariableCache ShmemVariableCache;
406 Backend *ShmemBackendArray;
408 slock_t *ProcStructLock;
409 PROC_HDR *ProcGlobal;
410 PGPROC *AuxiliaryProcs;
411 PMSignalData *PMSignalState;
412 InheritableSocket pgStatSock;
414 TimestampTz PgStartTime;
415 TimestampTz PgReloadTime;
416 bool redirection_done;
418 HANDLE PostmasterHandle;
419 HANDLE initial_signal_pipe;
420 HANDLE syslogPipe[2];
424 char my_exec_path[MAXPGPATH];
425 char pkglib_path[MAXPGPATH];
426 char ExtraOptions[MAXPGPATH];
429 static void read_backend_variables(char *id, Port *port);
430 static void restore_backend_variables(BackendParameters *param, Port *port);
433 static bool save_backend_variables(BackendParameters *param, Port *port);
435 static bool save_backend_variables(BackendParameters *param, Port *port,
436 HANDLE childProcess, pid_t childPid);
439 static void ShmemBackendArrayAdd(Backend *bn);
440 static void ShmemBackendArrayRemove(Backend *bn);
441 #endif /* EXEC_BACKEND */
443 #define StartupDataBase() StartChildProcess(StartupProcess)
444 #define StartBackgroundWriter() StartChildProcess(BgWriterProcess)
445 #define StartWalWriter() StartChildProcess(WalWriterProcess)
447 /* Macros to check exit status of a child process */
448 #define EXIT_STATUS_0(st) ((st) == 0)
449 #define EXIT_STATUS_1(st) (WIFEXITED(st) && WEXITSTATUS(st) == 1)
453 * Postmaster main entry point
456 PostmasterMain(int argc, char *argv[])
460 char *userDoption = NULL;
463 MyProcPid = PostmasterPid = getpid();
465 MyStartTime = time(NULL);
467 IsPostmasterEnvironment = true;
470 * for security, no dir or file created can be group or other accessible
472 umask((mode_t) 0077);
475 * Fire up essential subsystems: memory management
480 * By default, palloc() requests in the postmaster will be allocated in
481 * the PostmasterContext, which is space that can be recycled by backends.
482 * Allocated data that needs to be available to backends should be
483 * allocated in TopMemoryContext.
485 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
487 ALLOCSET_DEFAULT_MINSIZE,
488 ALLOCSET_DEFAULT_INITSIZE,
489 ALLOCSET_DEFAULT_MAXSIZE);
490 MemoryContextSwitchTo(PostmasterContext);
492 /* Initialize paths to installation files */
493 getInstallationPaths(argv[0]);
498 InitializeGUCOptions();
503 * Parse command-line options. CAUTION: keep this in sync with
504 * tcop/postgres.c (the option sets should not conflict) and with the
505 * common help() function in main/main.c.
507 while ((opt = getopt(argc, argv, "A:B:c:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:W:-:")) != -1)
512 SetConfigOption("debug_assertions", optarg, PGC_POSTMASTER, PGC_S_ARGV);
516 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
520 userDoption = optarg;
524 set_debug_options(atoi(optarg), PGC_POSTMASTER, PGC_S_ARGV);
528 SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
532 SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
536 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
540 if (!set_plan_disabling_options(optarg, PGC_POSTMASTER, PGC_S_ARGV))
542 write_stderr("%s: invalid argument for option -f: \"%s\"\n",
549 SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
553 SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
557 /* only used by interactive backend */
561 SetConfigOption("unix_socket_directory", optarg, PGC_POSTMASTER, PGC_S_ARGV);
565 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
569 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
573 /* Don't reinit shared mem after abnormal exit */
578 SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
582 /* Other options to pass to the backend on the command line */
583 snprintf(ExtraOptions + strlen(ExtraOptions),
584 sizeof(ExtraOptions) - strlen(ExtraOptions),
589 SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
593 SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
597 /* only used by single-user backend */
601 SetConfigOption("work_mem", optarg, PGC_POSTMASTER, PGC_S_ARGV);
605 SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
611 * In the event that some backend dumps core, send SIGSTOP,
612 * rather than SIGQUIT, to all its peers. This lets the wily
613 * post_hacker collect core dumps from everyone.
620 const char *tmp = get_stats_option_name(optarg);
624 SetConfigOption(tmp, "true", PGC_POSTMASTER, PGC_S_ARGV);
628 write_stderr("%s: invalid argument for option -t: \"%s\"\n",
636 SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
645 ParseLongOption(optarg, &name, &value);
650 (errcode(ERRCODE_SYNTAX_ERROR),
651 errmsg("--%s requires a value",
655 (errcode(ERRCODE_SYNTAX_ERROR),
656 errmsg("-c %s requires a value",
660 SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
668 write_stderr("Try \"%s --help\" for more information.\n",
675 * Postmaster accepts no non-option switch arguments.
679 write_stderr("%s: invalid argument: \"%s\"\n",
680 progname, argv[optind]);
681 write_stderr("Try \"%s --help\" for more information.\n",
687 * Locate the proper configuration files and data directory, and read
688 * postgresql.conf for the first time.
690 if (!SelectConfigFiles(userDoption, progname))
693 /* Verify that DataDir looks reasonable */
696 /* And switch working directory into it */
700 * Check for invalid combinations of GUC settings.
702 if (ReservedBackends >= MaxBackends)
704 write_stderr("%s: superuser_reserved_connections must be less than max_connections\n", progname);
709 * Other one-time internal sanity checks can go here, if they are fast.
710 * (Put any slow processing further down, after postmaster.pid creation.)
712 if (!CheckDateTokenTables())
714 write_stderr("%s: invalid datetoken tables, please fix\n", progname);
719 * Now that we are done processing the postmaster arguments, reset
720 * getopt(3) library so that it will work correctly in subprocesses.
723 #ifdef HAVE_INT_OPTRESET
724 optreset = 1; /* some systems need this too */
727 /* For debugging: display postmaster environment */
729 extern char **environ;
733 (errmsg_internal("%s: PostmasterMain: initial environ dump:",
736 (errmsg_internal("-----------------------------------------")));
737 for (p = environ; *p; ++p)
739 (errmsg_internal("\t%s", *p)));
741 (errmsg_internal("-----------------------------------------")));
745 * Fork away from controlling terminal, if -S specified.
747 * Must do this before we grab any interlock files, else the interlocks
748 * will show the wrong PID.
754 * Create lockfile for data directory.
756 * We want to do this before we try to grab the input sockets, because the
757 * data directory interlock is more reliable than the socket-file
758 * interlock (thanks to whoever decided to put socket files in /tmp :-().
759 * For the same reason, it's best to grab the TCP socket(s) before the
762 CreateDataDirLockFile(true);
765 * If timezone is not set, determine what the OS uses. (In theory this
766 * should be done during GUC initialization, but because it can take as
767 * much as several seconds, we delay it until after we've created the
768 * postmaster.pid file. This prevents problems with boot scripts that
769 * expect the pidfile to appear quickly. Also, we avoid problems with
770 * trying to locate the timezone files too early in initialization.)
772 pg_timezone_initialize();
775 * Likewise, init timezone_abbreviations if not already set.
777 pg_timezone_abbrev_initialize();
780 * Initialize SSL library, if specified.
788 * process any libraries that should be preloaded at postmaster start
790 process_shared_preload_libraries();
793 * Remove old temporary files. At this point there can be no other
794 * Postgres processes running in this directory, so this should be safe.
799 * Establish input sockets.
801 for (i = 0; i < MAXLISTEN; i++)
802 ListenSocket[i] = -1;
811 /* Need a modifiable copy of ListenAddresses */
812 rawstring = pstrdup(ListenAddresses);
814 /* Parse string into list of identifiers */
815 if (!SplitIdentifierString(rawstring, ',', &elemlist))
817 /* syntax error in list */
819 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
820 errmsg("invalid list syntax for \"listen_addresses\"")));
825 char *curhost = (char *) lfirst(l);
827 if (strcmp(curhost, "*") == 0)
828 status = StreamServerPort(AF_UNSPEC, NULL,
829 (unsigned short) PostPortNumber,
831 ListenSocket, MAXLISTEN);
833 status = StreamServerPort(AF_UNSPEC, curhost,
834 (unsigned short) PostPortNumber,
836 ListenSocket, MAXLISTEN);
837 if (status == STATUS_OK)
841 (errmsg("could not create listen socket for \"%s\"",
845 if (!success && list_length(elemlist))
847 (errmsg("could not create any TCP/IP sockets")));
854 /* Register for Bonjour only if we opened TCP socket(s) */
855 if (ListenSocket[0] != -1 && bonjour_name != NULL)
857 DNSServiceRegistrationCreate(bonjour_name,
860 htons(PostPortNumber),
862 (DNSServiceRegistrationReply) reg_reply,
867 #ifdef HAVE_UNIX_SOCKETS
868 status = StreamServerPort(AF_UNIX, NULL,
869 (unsigned short) PostPortNumber,
871 ListenSocket, MAXLISTEN);
872 if (status != STATUS_OK)
874 (errmsg("could not create Unix-domain socket")));
878 * check that we have some socket to listen on
880 if (ListenSocket[0] == -1)
882 (errmsg("no socket created for listening")));
885 * Set up shared memory and semaphores.
887 reset_shared(PostPortNumber);
890 * Estimate number of openable files. This must happen after setting up
891 * semaphores, because on some platforms semaphores count as open files.
896 * Load configuration files for client authentication.
901 * It makes no sense continue if we fail to load the HBA file, since
902 * there is no way to connect to the database in this case.
905 (errmsg("could not load pg_hba.conf")));
910 * Initialize the list of active backends.
912 BackendList = DLNewList();
917 * Initialize I/O completion port used to deliver list of dead children.
919 win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
920 if (win32ChildQueue == NULL)
922 (errmsg("could not create I/O completion port for child queue")));
925 * Set up a handle that child processes can use to check whether the
926 * postmaster is still running.
928 if (DuplicateHandle(GetCurrentProcess(),
934 DUPLICATE_SAME_ACCESS) == 0)
936 (errmsg_internal("could not duplicate postmaster handle: error code %d",
937 (int) GetLastError())));
941 * Record postmaster options. We delay this till now to avoid recording
942 * bogus options (eg, NBuffers too high for available memory).
944 if (!CreateOptsFile(argc, argv, my_exec_path))
948 /* Write out nondefault GUC settings for child processes to use */
949 write_nondefault_variables(PGC_POSTMASTER);
953 * Write the external PID file if requested
955 if (external_pid_file)
957 FILE *fpidfile = fopen(external_pid_file, "w");
961 fprintf(fpidfile, "%d\n", MyProcPid);
963 /* Should we remove the pid file on postmaster exit? */
966 write_stderr("%s: could not write external PID file \"%s\": %s\n",
967 progname, external_pid_file, strerror(errno));
971 * Set up signal handlers for the postmaster process.
973 * CAUTION: when changing this list, check for side-effects on the signal
974 * handling setup of child processes. See tcop/postgres.c,
975 * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/walwriter.c,
976 * postmaster/autovacuum.c, postmaster/pgarch.c, postmaster/pgstat.c, and
977 * postmaster/syslogger.c.
980 PG_SETMASK(&BlockSig);
982 pqsignal(SIGHUP, SIGHUP_handler); /* reread config file and have
983 * children do same */
984 pqsignal(SIGINT, pmdie); /* send SIGTERM and shut down */
985 pqsignal(SIGQUIT, pmdie); /* send SIGQUIT and die */
986 pqsignal(SIGTERM, pmdie); /* wait for children and shut down */
987 pqsignal(SIGALRM, SIG_IGN); /* ignored */
988 pqsignal(SIGPIPE, SIG_IGN); /* ignored */
989 pqsignal(SIGUSR1, sigusr1_handler); /* message from child process */
990 pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
991 pqsignal(SIGCHLD, reaper); /* handle child termination */
992 pqsignal(SIGTTIN, SIG_IGN); /* ignored */
993 pqsignal(SIGTTOU, SIG_IGN); /* ignored */
994 /* ignore SIGXFSZ, so that ulimit violations work like disk full */
996 pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
1000 * If enabled, start up syslogger collection subprocess
1002 SysLoggerPID = SysLogger_Start();
1005 * Reset whereToSendOutput from DestDebug (its starting state) to
1006 * DestNone. This stops ereport from sending log messages to stderr unless
1007 * Log_destination permits. We don't do this until the postmaster is
1008 * fully launched, since startup failures may as well be reported to
1011 whereToSendOutput = DestNone;
1014 * Initialize stats collection subsystem (this does NOT start the
1015 * collector process!)
1020 * Initialize the autovacuum subsystem (again, no process start yet)
1025 * Remember postmaster startup time
1027 PgStartTime = GetCurrentTimestamp();
1028 /* PostmasterRandom wants its own copy */
1029 gettimeofday(&random_start_time, NULL);
1032 * We're ready to rock and roll...
1034 StartupPID = StartupDataBase();
1035 Assert(StartupPID != 0);
1036 pmState = PM_STARTUP;
1038 status = ServerLoop();
1041 * ServerLoop probably shouldn't ever return, but if it does, close down.
1043 ExitPostmaster(status != STATUS_OK);
1045 return 0; /* not reached */
1050 * Compute and check the directory paths to files that are part of the
1051 * installation (as deduced from the postgres executable's own location)
1054 getInstallationPaths(const char *argv0)
1058 /* Locate the postgres executable itself */
1059 if (find_my_exec(argv0, my_exec_path) < 0)
1060 elog(FATAL, "%s: could not locate my own executable path", argv0);
1063 /* Locate executable backend before we change working directory */
1064 if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1065 postgres_exec_path) < 0)
1067 (errmsg("%s: could not locate matching postgres executable",
1072 * Locate the pkglib directory --- this has to be set early in case we try
1073 * to load any modules from it in response to postgresql.conf entries.
1075 get_pkglib_path(my_exec_path, pkglib_path);
1078 * Verify that there's a readable directory there; otherwise the Postgres
1079 * installation is incomplete or corrupt. (A typical cause of this
1080 * failure is that the postgres executable has been moved or hardlinked to
1081 * some directory that's not a sibling of the installation lib/
1084 pdir = AllocateDir(pkglib_path);
1087 (errcode_for_file_access(),
1088 errmsg("could not open directory \"%s\": %m",
1090 errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1095 * XXX is it worth similarly checking the share/ directory? If the lib/
1096 * directory is there, then share/ probably is too.
1102 * Validate the proposed data directory
1107 char path[MAXPGPATH];
1109 struct stat stat_buf;
1113 if (stat(DataDir, &stat_buf) != 0)
1115 if (errno == ENOENT)
1117 (errcode_for_file_access(),
1118 errmsg("data directory \"%s\" does not exist",
1122 (errcode_for_file_access(),
1123 errmsg("could not read permissions of directory \"%s\": %m",
1127 /* eventual chdir would fail anyway, but let's test ... */
1128 if (!S_ISDIR(stat_buf.st_mode))
1130 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1131 errmsg("specified data directory \"%s\" is not a directory",
1135 * Check that the directory belongs to my userid; if not, reject.
1137 * This check is an essential part of the interlock that prevents two
1138 * postmasters from starting in the same directory (see CreateLockFile()).
1139 * Do not remove or weaken it.
1141 * XXX can we safely enable this check on Windows?
1143 #if !defined(WIN32) && !defined(__CYGWIN__)
1144 if (stat_buf.st_uid != geteuid())
1146 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1147 errmsg("data directory \"%s\" has wrong ownership",
1149 errhint("The server must be started by the user that owns the data directory.")));
1153 * Check if the directory has group or world access. If so, reject.
1155 * It would be possible to allow weaker constraints (for example, allow
1156 * group access) but we cannot make a general assumption that that is
1157 * okay; for example there are platforms where nearly all users
1158 * customarily belong to the same group. Perhaps this test should be
1161 * XXX temporarily suppress check when on Windows, because there may not
1162 * be proper support for Unix-y file permissions. Need to think of a
1163 * reasonable check to apply on Windows.
1165 #if !defined(WIN32) && !defined(__CYGWIN__)
1166 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
1168 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1169 errmsg("data directory \"%s\" has group or world access",
1171 errdetail("Permissions should be u=rwx (0700).")));
1174 /* Look for PG_VERSION before looking for pg_control */
1175 ValidatePgVersion(DataDir);
1177 snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1179 fp = AllocateFile(path, PG_BINARY_R);
1182 write_stderr("%s: could not find the database system\n"
1183 "Expected to find it in the directory \"%s\",\n"
1184 "but could not open file \"%s\": %s\n",
1185 progname, DataDir, path, strerror(errno));
1195 * empty callback function for DNSServiceRegistrationCreate()
1198 reg_reply(DNSServiceRegistrationReplyErrorType errorCode, void *context)
1201 #endif /* USE_BONJOUR */
1205 * Fork away from the controlling terminal (-S option)
1214 pid = fork_process();
1215 if (pid == (pid_t) -1)
1217 write_stderr("%s: could not fork background process: %s\n",
1218 progname, strerror(errno));
1223 /* Parent should just exit, without doing any atexit cleanup */
1227 MyProcPid = PostmasterPid = getpid(); /* reset PID vars to child */
1229 MyStartTime = time(NULL);
1232 * GH: If there's no setsid(), we hopefully don't need silent mode. Until
1233 * there's a better solution.
1238 write_stderr("%s: could not dissociate from controlling TTY: %s\n",
1239 progname, strerror(errno));
1243 i = open(DEVNULL, O_RDWR, 0);
1250 elog(FATAL, "SilentMode not supported under WIN32");
1256 * Main idle loop of postmaster
1266 last_touch_time = time(NULL);
1268 nSockets = initMasks(&readmask);
1276 * Wait for a connection request to arrive.
1278 * We wait at most one minute, to ensure that the other background
1279 * tasks handled below get done even when no requests are arriving.
1281 * If we are in PM_WAIT_DEAD_END state, then we don't want to accept
1282 * any new connections, so we don't call select() at all; just sleep
1283 * for a little bit with signals unblocked.
1285 memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
1287 PG_SETMASK(&UnBlockSig);
1289 if (pmState == PM_WAIT_DEAD_END)
1291 pg_usleep(100000L); /* 100 msec seems reasonable */
1296 /* must set timeout each time; some OSes change it! */
1297 struct timeval timeout;
1299 timeout.tv_sec = 60;
1300 timeout.tv_usec = 0;
1302 selres = select(nSockets, &rmask, NULL, NULL, &timeout);
1306 * Block all signals until we wait again. (This makes it safe for our
1307 * signal handlers to do nontrivial work.)
1309 PG_SETMASK(&BlockSig);
1311 /* Now check the select() result */
1314 if (errno != EINTR && errno != EWOULDBLOCK)
1317 (errcode_for_socket_access(),
1318 errmsg("select() failed in postmaster: %m")));
1319 return STATUS_ERROR;
1324 * New connection pending on any of our sockets? If so, fork a child
1325 * process to deal with it.
1331 for (i = 0; i < MAXLISTEN; i++)
1333 if (ListenSocket[i] == -1)
1335 if (FD_ISSET(ListenSocket[i], &rmask))
1339 port = ConnCreate(ListenSocket[i]);
1342 BackendStartup(port);
1345 * We no longer need the open socket or port structure
1348 StreamClose(port->sock);
1355 /* If we have lost the log collector, try to start a new one */
1356 if (SysLoggerPID == 0 && Logging_collector)
1357 SysLoggerPID = SysLogger_Start();
1360 * If no background writer process is running, and we are not in a
1361 * state that prevents it, start one. It doesn't matter if this
1362 * fails, we'll just try again later.
1364 if (BgWriterPID == 0 &&
1365 (pmState == PM_RUN || pmState == PM_RECOVERY ||
1366 pmState == PM_RECOVERY_CONSISTENT))
1367 BgWriterPID = StartBackgroundWriter();
1370 * Likewise, if we have lost the walwriter process, try to start a new
1373 if (WalWriterPID == 0 && pmState == PM_RUN)
1374 WalWriterPID = StartWalWriter();
1376 /* If we have lost the autovacuum launcher, try to start a new one */
1377 if (AutoVacPID == 0 &&
1378 (AutoVacuumingActive() || start_autovac_launcher) &&
1381 AutoVacPID = StartAutoVacLauncher();
1382 if (AutoVacPID != 0)
1383 start_autovac_launcher = false; /* signal processed */
1386 /* If we have lost the archiver, try to start a new one */
1387 if (XLogArchivingActive() && PgArchPID == 0 && pmState == PM_RUN)
1388 PgArchPID = pgarch_start();
1390 /* If we have lost the stats collector, try to start a new one */
1391 if (PgStatPID == 0 && pmState == PM_RUN)
1392 PgStatPID = pgstat_start();
1395 * Touch the socket and lock file every 58 minutes, to ensure that
1396 * they are not removed by overzealous /tmp-cleaning tasks. We assume
1397 * no one runs cleaners with cutoff times of less than an hour ...
1400 if (now - last_touch_time >= 58 * SECS_PER_MINUTE)
1403 TouchSocketLockFile();
1404 last_touch_time = now;
1411 * Initialise the masks for select() for the ports we are listening on.
1412 * Return the number of sockets to listen on.
1415 initMasks(fd_set *rmask)
1422 for (i = 0; i < MAXLISTEN; i++)
1424 int fd = ListenSocket[i];
1439 * Read a client's startup packet and do something according to it.
1441 * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
1442 * not return at all.
1444 * (Note that ereport(FATAL) stuff is sent to the client, so only use it
1445 * if that's what you want. Return STATUS_ERROR if you don't want to
1446 * send anything to the client, which would typically be appropriate
1447 * if we detect a communications failure.)
1450 ProcessStartupPacket(Port *port, bool SSLdone)
1454 ProtocolVersion proto;
1455 MemoryContext oldcontext;
1457 if (pq_getbytes((char *) &len, 4) == EOF)
1460 * EOF after SSLdone probably means the client didn't like our
1461 * response to NEGOTIATE_SSL_CODE. That's not an error condition, so
1462 * don't clutter the log with a complaint.
1466 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1467 errmsg("incomplete startup packet")));
1468 return STATUS_ERROR;
1474 if (len < (int32) sizeof(ProtocolVersion) ||
1475 len > MAX_STARTUP_PACKET_LENGTH)
1478 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1479 errmsg("invalid length of startup packet")));
1480 return STATUS_ERROR;
1484 * Allocate at least the size of an old-style startup packet, plus one
1485 * extra byte, and make sure all are zeroes. This ensures we will have
1486 * null termination of all strings, in both fixed- and variable-length
1489 if (len <= (int32) sizeof(StartupPacket))
1490 buf = palloc0(sizeof(StartupPacket) + 1);
1492 buf = palloc0(len + 1);
1494 if (pq_getbytes(buf, len) == EOF)
1497 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1498 errmsg("incomplete startup packet")));
1499 return STATUS_ERROR;
1503 * The first field is either a protocol version number or a special
1506 port->proto = proto = ntohl(*((ProtocolVersion *) buf));
1508 if (proto == CANCEL_REQUEST_CODE)
1510 processCancelRequest(port, buf);
1511 return 127; /* XXX */
1514 if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
1519 /* No SSL when disabled or on Unix sockets */
1520 if (!EnableSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
1523 SSLok = 'S'; /* Support for SSL */
1525 SSLok = 'N'; /* No support for SSL */
1529 if (send(port->sock, &SSLok, 1, 0) != 1)
1532 goto retry1; /* if interrupted, just retry */
1534 (errcode_for_socket_access(),
1535 errmsg("failed to send SSL negotiation response: %m")));
1536 return STATUS_ERROR; /* close the connection */
1540 if (SSLok == 'S' && secure_open_server(port) == -1)
1541 return STATUS_ERROR;
1543 /* regular startup packet, cancel, etc packet should follow... */
1544 /* but not another SSL negotiation request */
1545 return ProcessStartupPacket(port, true);
1548 /* Could add additional special packet types here */
1551 * Set FrontendProtocol now so that ereport() knows what format to send if
1552 * we fail during startup.
1554 FrontendProtocol = proto;
1556 /* Check we can handle the protocol the frontend is using. */
1558 if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
1559 PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
1560 (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
1561 PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
1563 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1564 errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
1565 PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
1566 PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST),
1567 PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST),
1568 PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))));
1571 * Now fetch parameters out of startup packet and save them into the Port
1572 * structure. All data structures attached to the Port struct must be
1573 * allocated in TopMemoryContext so that they won't disappear when we pass
1574 * them to PostgresMain (see BackendRun). We need not worry about leaking
1575 * this storage on failure, since we aren't in the postmaster process
1578 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1580 if (PG_PROTOCOL_MAJOR(proto) >= 3)
1582 int32 offset = sizeof(ProtocolVersion);
1585 * Scan packet body for name/option pairs. We can assume any string
1586 * beginning within the packet body is null-terminated, thanks to
1587 * zeroing extra byte above.
1589 port->guc_options = NIL;
1591 while (offset < len)
1593 char *nameptr = ((char *) buf) + offset;
1597 if (*nameptr == '\0')
1598 break; /* found packet terminator */
1599 valoffset = offset + strlen(nameptr) + 1;
1600 if (valoffset >= len)
1601 break; /* missing value, will complain below */
1602 valptr = ((char *) buf) + valoffset;
1604 if (strcmp(nameptr, "database") == 0)
1605 port->database_name = pstrdup(valptr);
1606 else if (strcmp(nameptr, "user") == 0)
1607 port->user_name = pstrdup(valptr);
1608 else if (strcmp(nameptr, "options") == 0)
1609 port->cmdline_options = pstrdup(valptr);
1612 /* Assume it's a generic GUC option */
1613 port->guc_options = lappend(port->guc_options,
1615 port->guc_options = lappend(port->guc_options,
1618 offset = valoffset + strlen(valptr) + 1;
1622 * If we didn't find a packet terminator exactly at the end of the
1623 * given packet length, complain.
1625 if (offset != len - 1)
1627 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1628 errmsg("invalid startup packet layout: expected terminator as last byte")));
1633 * Get the parameters from the old-style, fixed-width-fields startup
1634 * packet as C strings. The packet destination was cleared first so a
1635 * short packet has zeros silently added. We have to be prepared to
1636 * truncate the pstrdup result for oversize fields, though.
1638 StartupPacket *packet = (StartupPacket *) buf;
1640 port->database_name = pstrdup(packet->database);
1641 if (strlen(port->database_name) > sizeof(packet->database))
1642 port->database_name[sizeof(packet->database)] = '\0';
1643 port->user_name = pstrdup(packet->user);
1644 if (strlen(port->user_name) > sizeof(packet->user))
1645 port->user_name[sizeof(packet->user)] = '\0';
1646 port->cmdline_options = pstrdup(packet->options);
1647 if (strlen(port->cmdline_options) > sizeof(packet->options))
1648 port->cmdline_options[sizeof(packet->options)] = '\0';
1649 port->guc_options = NIL;
1652 /* Check a user name was given. */
1653 if (port->user_name == NULL || port->user_name[0] == '\0')
1655 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1656 errmsg("no PostgreSQL user name specified in startup packet")));
1658 /* The database defaults to the user name. */
1659 if (port->database_name == NULL || port->database_name[0] == '\0')
1660 port->database_name = pstrdup(port->user_name);
1662 if (Db_user_namespace)
1665 * If user@, it is a global user, remove '@'. We only want to do this
1666 * if there is an '@' at the end and no earlier in the user string or
1667 * they may fake as a local user of another database attaching to this
1670 if (strchr(port->user_name, '@') ==
1671 port->user_name + strlen(port->user_name) - 1)
1672 *strchr(port->user_name, '@') = '\0';
1675 /* Append '@' and dbname */
1678 db_user = palloc(strlen(port->user_name) +
1679 strlen(port->database_name) + 2);
1680 sprintf(db_user, "%s@%s", port->user_name, port->database_name);
1681 port->user_name = db_user;
1686 * Truncate given database and user names to length of a Postgres name.
1687 * This avoids lookup failures when overlength names are given.
1689 if (strlen(port->database_name) >= NAMEDATALEN)
1690 port->database_name[NAMEDATALEN - 1] = '\0';
1691 if (strlen(port->user_name) >= NAMEDATALEN)
1692 port->user_name[NAMEDATALEN - 1] = '\0';
1695 * Done putting stuff in TopMemoryContext.
1697 MemoryContextSwitchTo(oldcontext);
1700 * If we're going to reject the connection due to database state, say so
1701 * now instead of wasting cycles on an authentication exchange. (This also
1702 * allows a pg_ping utility to be written.)
1704 switch (port->canAcceptConnections)
1708 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1709 errmsg("the database system is starting up")));
1713 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1714 errmsg("the database system is shutting down")));
1718 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1719 errmsg("the database system is in recovery mode")));
1723 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
1724 errmsg("sorry, too many clients already")));
1726 case CAC_WAITBACKUP:
1727 /* OK for now, will check in InitPostgres */
1738 * The client has sent a cancel request packet, not a normal
1739 * start-a-new-connection packet. Perform the necessary processing.
1740 * Nothing is sent back to the client.
1743 processCancelRequest(Port *port, void *pkt)
1745 CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
1747 long cancelAuthCode;
1750 #ifndef EXEC_BACKEND
1756 backendPID = (int) ntohl(canc->backendPID);
1757 cancelAuthCode = (long) ntohl(canc->cancelAuthCode);
1760 * See if we have a matching backend. In the EXEC_BACKEND case, we can no
1761 * longer access the postmaster's own backend list, and must rely on the
1762 * duplicate array in shared memory.
1764 #ifndef EXEC_BACKEND
1765 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
1767 bp = (Backend *) DLE_VAL(curr);
1769 for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
1771 bp = (Backend *) &ShmemBackendArray[i];
1773 if (bp->pid == backendPID)
1775 if (bp->cancel_key == cancelAuthCode)
1777 /* Found a match; signal that backend to cancel current op */
1779 (errmsg_internal("processing cancel request: sending SIGINT to process %d",
1781 signal_child(bp->pid, SIGINT);
1784 /* Right PID, wrong key: no way, Jose */
1786 (errmsg("wrong key in cancel request for process %d",
1792 /* No matching backend */
1794 (errmsg("PID %d in cancel request did not match any process",
1799 * canAcceptConnections --- check to see if database state allows connections.
1801 static enum CAC_state
1802 canAcceptConnections(void)
1805 * Can't start backends when in startup/shutdown/recovery state.
1807 * In state PM_WAIT_BACKUP only superusers can connect (this must be
1808 * allowed so that a superuser can end online backup mode); we return
1809 * CAC_WAITBACKUP code to indicate that this must be checked later.
1811 if (pmState != PM_RUN)
1813 if (pmState == PM_WAIT_BACKUP)
1814 return CAC_WAITBACKUP; /* allow superusers only */
1815 if (Shutdown > NoShutdown)
1816 return CAC_SHUTDOWN; /* shutdown is pending */
1818 (pmState == PM_STARTUP ||
1819 pmState == PM_RECOVERY ||
1820 pmState == PM_RECOVERY_CONSISTENT))
1821 return CAC_STARTUP; /* normal startup */
1822 return CAC_RECOVERY; /* else must be crash recovery */
1826 * Don't start too many children.
1828 * We allow more connections than we can have backends here because some
1829 * might still be authenticating; they might fail auth, or some existing
1830 * backend might exit before the auth cycle is completed. The exact
1831 * MaxBackends limit is enforced when a new backend tries to join the
1832 * shared-inval backend array.
1834 * The limit here must match the sizes of the per-child-process arrays;
1835 * see comments for MaxLivePostmasterChildren().
1837 if (CountChildren() >= MaxLivePostmasterChildren())
1845 * ConnCreate -- create a local connection data structure
1848 ConnCreate(int serverFd)
1852 if (!(port = (Port *) calloc(1, sizeof(Port))))
1855 (errcode(ERRCODE_OUT_OF_MEMORY),
1856 errmsg("out of memory")));
1860 if (StreamConnection(serverFd, port) != STATUS_OK)
1862 if (port->sock >= 0)
1863 StreamClose(port->sock);
1870 * Precompute password salt values to use for this connection. It's
1871 * slightly annoying to do this long in advance of knowing whether
1872 * we'll need 'em or not, but we must do the random() calls before we
1873 * fork, not after. Else the postmaster's random sequence won't get
1874 * advanced, and all backends would end up using the same salt...
1876 RandomSalt(port->md5Salt);
1880 * Allocate GSSAPI specific state struct
1882 #ifndef EXEC_BACKEND
1883 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
1884 port->gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
1888 (errcode(ERRCODE_OUT_OF_MEMORY),
1889 errmsg("out of memory")));
1900 * ConnFree -- free a local connection data structure
1903 ConnFree(Port *conn)
1915 * ClosePostmasterPorts -- close all the postmaster's open sockets
1917 * This is called during child process startup to release file descriptors
1918 * that are not needed by that child process. The postmaster still has
1919 * them open, of course.
1921 * Note: we pass am_syslogger as a boolean because we don't want to set
1922 * the global variable yet when this is called.
1925 ClosePostmasterPorts(bool am_syslogger)
1929 /* Close the listen sockets */
1930 for (i = 0; i < MAXLISTEN; i++)
1932 if (ListenSocket[i] != -1)
1934 StreamClose(ListenSocket[i]);
1935 ListenSocket[i] = -1;
1939 /* If using syslogger, close the read side of the pipe */
1943 if (syslogPipe[0] >= 0)
1944 close(syslogPipe[0]);
1948 CloseHandle(syslogPipe[0]);
1956 * reset_shared -- reset shared memory and semaphores
1959 reset_shared(int port)
1962 * Create or re-create shared memory and semaphores.
1964 * Note: in each "cycle of life" we will normally assign the same IPC keys
1965 * (if using SysV shmem and/or semas), since the port number is used to
1966 * determine IPC keys. This helps ensure that we will clean up dead IPC
1967 * objects if the postmaster crashes and is restarted.
1969 CreateSharedMemoryAndSemaphores(false, port);
1974 * SIGHUP -- reread config files, and tell children to do same
1977 SIGHUP_handler(SIGNAL_ARGS)
1979 int save_errno = errno;
1981 PG_SETMASK(&BlockSig);
1983 if (Shutdown <= SmartShutdown)
1986 (errmsg("received SIGHUP, reloading configuration files")));
1987 ProcessConfigFile(PGC_SIGHUP);
1988 SignalChildren(SIGHUP);
1989 if (StartupPID != 0)
1990 signal_child(StartupPID, SIGHUP);
1991 if (BgWriterPID != 0)
1992 signal_child(BgWriterPID, SIGHUP);
1993 if (WalWriterPID != 0)
1994 signal_child(WalWriterPID, SIGHUP);
1995 if (AutoVacPID != 0)
1996 signal_child(AutoVacPID, SIGHUP);
1998 signal_child(PgArchPID, SIGHUP);
1999 if (SysLoggerPID != 0)
2000 signal_child(SysLoggerPID, SIGHUP);
2002 signal_child(PgStatPID, SIGHUP);
2004 /* Reload authentication config files too */
2007 (errmsg("pg_hba.conf not reloaded")));
2012 /* Update the starting-point file for future children */
2013 write_nondefault_variables(PGC_SIGHUP);
2017 PG_SETMASK(&UnBlockSig);
2024 * pmdie -- signal handler for processing various postmaster signals.
2029 int save_errno = errno;
2031 PG_SETMASK(&BlockSig);
2034 (errmsg_internal("postmaster received signal %d",
2035 postgres_signal_arg)));
2037 switch (postgres_signal_arg)
2044 * Wait for children to end their work, then shut down.
2046 if (Shutdown >= SmartShutdown)
2048 Shutdown = SmartShutdown;
2050 (errmsg("received smart shutdown request")));
2052 if (pmState == PM_RUN || pmState == PM_RECOVERY ||
2053 pmState == PM_RECOVERY_CONSISTENT)
2055 /* autovacuum workers are told to shut down immediately */
2056 SignalAutovacWorkers(SIGTERM);
2057 /* and the autovac launcher too */
2058 if (AutoVacPID != 0)
2059 signal_child(AutoVacPID, SIGTERM);
2060 /* and the walwriter too */
2061 if (WalWriterPID != 0)
2062 signal_child(WalWriterPID, SIGTERM);
2063 pmState = PM_WAIT_BACKUP;
2067 * Now wait for online backup mode to end and backends to exit.
2068 * If that is already the case, PostmasterStateMachine will take
2071 PostmasterStateMachine();
2079 * Abort all children with SIGTERM (rollback active transactions
2080 * and exit) and shut down when they are gone.
2082 if (Shutdown >= FastShutdown)
2084 Shutdown = FastShutdown;
2086 (errmsg("received fast shutdown request")));
2088 if (StartupPID != 0)
2089 signal_child(StartupPID, SIGTERM);
2090 if (pmState == PM_RECOVERY)
2092 /* only bgwriter is active in this state */
2093 pmState = PM_WAIT_BACKENDS;
2095 if (pmState == PM_RUN ||
2096 pmState == PM_WAIT_BACKUP ||
2097 pmState == PM_RECOVERY_CONSISTENT)
2100 (errmsg("aborting any active transactions")));
2101 /* shut down all backends and autovac workers */
2102 SignalChildren(SIGTERM);
2103 /* and the autovac launcher too */
2104 if (AutoVacPID != 0)
2105 signal_child(AutoVacPID, SIGTERM);
2106 /* and the walwriter too */
2107 if (WalWriterPID != 0)
2108 signal_child(WalWriterPID, SIGTERM);
2109 pmState = PM_WAIT_BACKENDS;
2113 * Now wait for backends to exit. If there are none,
2114 * PostmasterStateMachine will take the next step.
2116 PostmasterStateMachine();
2122 * Immediate Shutdown:
2124 * abort all children with SIGQUIT and exit without attempt to
2125 * properly shut down data base system.
2128 (errmsg("received immediate shutdown request")));
2129 SignalChildren(SIGQUIT);
2130 if (StartupPID != 0)
2131 signal_child(StartupPID, SIGQUIT);
2132 if (BgWriterPID != 0)
2133 signal_child(BgWriterPID, SIGQUIT);
2134 if (WalWriterPID != 0)
2135 signal_child(WalWriterPID, SIGQUIT);
2136 if (AutoVacPID != 0)
2137 signal_child(AutoVacPID, SIGQUIT);
2139 signal_child(PgArchPID, SIGQUIT);
2141 signal_child(PgStatPID, SIGQUIT);
2146 PG_SETMASK(&UnBlockSig);
2152 * Reaper -- signal handler to cleanup after a child process dies.
2157 int save_errno = errno;
2158 int pid; /* process id of dead child process */
2159 int exitstatus; /* its exit status */
2161 /* These macros hide platform variations in getting child status */
2163 int status; /* child exit status */
2165 #define LOOPTEST() ((pid = waitpid(-1, &status, WNOHANG)) > 0)
2166 #define LOOPHEADER() (exitstatus = status)
2167 #else /* !HAVE_WAITPID */
2169 union wait status; /* child exit status */
2171 #define LOOPTEST() ((pid = wait3(&status, WNOHANG, NULL)) > 0)
2172 #define LOOPHEADER() (exitstatus = status.w_status)
2174 #define LOOPTEST() ((pid = win32_waitpid(&exitstatus)) > 0)
2175 #define LOOPHEADER()
2177 #endif /* HAVE_WAITPID */
2179 PG_SETMASK(&BlockSig);
2182 (errmsg_internal("reaping dead processes")));
2189 * Check if this child was a startup process.
2191 if (pid == StartupPID)
2196 * Unexpected exit of startup process (including FATAL exit)
2197 * during PM_STARTUP is treated as catastrophic. There are no
2198 * other processes running yet, so we can just exit.
2200 if (pmState == PM_STARTUP && !EXIT_STATUS_0(exitstatus))
2202 LogChildExit(LOG, _("startup process"),
2205 (errmsg("aborting startup due to startup process failure")));
2210 * Startup process exited in response to a shutdown request (or it
2211 * completed normally regardless of the shutdown request).
2213 if (Shutdown > NoShutdown &&
2214 (EXIT_STATUS_0(exitstatus) || EXIT_STATUS_1(exitstatus)))
2216 pmState = PM_WAIT_BACKENDS;
2217 /* PostmasterStateMachine logic does the rest */
2222 * Any unexpected exit (including FATAL exit) of the startup
2223 * process is treated as a crash, except that we don't want to
2226 if (!EXIT_STATUS_0(exitstatus))
2228 RecoveryError = true;
2229 HandleChildCrash(pid, exitstatus,
2230 _("startup process"));
2235 * Startup succeeded, commence normal operations
2241 * Load the flat authorization file into postmaster's cache. The
2242 * startup process has recomputed this from the database contents,
2243 * so we wait till it finishes before loading it.
2248 * Crank up the background writer, if we didn't do that already
2249 * when we entered consistent recovery state. It doesn't matter
2250 * if this fails, we'll just try again later.
2252 if (BgWriterPID == 0)
2253 BgWriterPID = StartBackgroundWriter();
2256 * Likewise, start other special children as needed. In a restart
2257 * situation, some of them may be alive already.
2259 if (WalWriterPID == 0)
2260 WalWriterPID = StartWalWriter();
2261 if (AutoVacuumingActive() && AutoVacPID == 0)
2262 AutoVacPID = StartAutoVacLauncher();
2263 if (XLogArchivingActive() && PgArchPID == 0)
2264 PgArchPID = pgarch_start();
2266 PgStatPID = pgstat_start();
2268 /* at this point we are really open for business */
2270 (errmsg("database system is ready to accept connections")));
2276 * Was it the bgwriter?
2278 if (pid == BgWriterPID)
2281 if (EXIT_STATUS_0(exitstatus) && pmState == PM_SHUTDOWN)
2284 * OK, we saw normal exit of the bgwriter after it's been told
2285 * to shut down. We expect that it wrote a shutdown
2286 * checkpoint. (If for some reason it didn't, recovery will
2287 * occur on next postmaster start.)
2289 * At this point we should have no normal backend children
2290 * left (else we'd not be in PM_SHUTDOWN state) but we might
2291 * have dead_end children to wait for.
2293 * If we have an archiver subprocess, tell it to do a last
2294 * archive cycle and quit; otherwise we can go directly to
2295 * PM_WAIT_DEAD_END state.
2297 Assert(Shutdown > NoShutdown);
2301 /* Waken archiver for the last time */
2302 signal_child(PgArchPID, SIGUSR2);
2303 pmState = PM_SHUTDOWN_2;
2306 pmState = PM_WAIT_DEAD_END;
2309 * We can also shut down the stats collector now; there's
2310 * nothing left for it to do.
2313 signal_child(PgStatPID, SIGQUIT);
2318 * Any unexpected exit of the bgwriter (including FATAL exit)
2319 * is treated as a crash.
2321 HandleChildCrash(pid, exitstatus,
2322 _("background writer process"));
2329 * Was it the wal writer? Normal exit can be ignored; we'll start a
2330 * new one at the next iteration of the postmaster's main loop, if
2331 * necessary. Any other exit condition is treated as a crash.
2333 if (pid == WalWriterPID)
2336 if (!EXIT_STATUS_0(exitstatus))
2337 HandleChildCrash(pid, exitstatus,
2338 _("WAL writer process"));
2343 * Was it the autovacuum launcher? Normal exit can be ignored; we'll
2344 * start a new one at the next iteration of the postmaster's main
2345 * loop, if necessary. Any other exit condition is treated as a
2348 if (pid == AutoVacPID)
2351 if (!EXIT_STATUS_0(exitstatus))
2352 HandleChildCrash(pid, exitstatus,
2353 _("autovacuum launcher process"));
2358 * Was it the archiver? If so, just try to start a new one; no need
2359 * to force reset of the rest of the system. (If fail, we'll try
2360 * again in future cycles of the main loop.) But if we were waiting
2361 * for it to shut down, advance to the next shutdown step.
2363 if (pid == PgArchPID)
2366 if (!EXIT_STATUS_0(exitstatus))
2367 LogChildExit(LOG, _("archiver process"),
2369 if (XLogArchivingActive() && pmState == PM_RUN)
2370 PgArchPID = pgarch_start();
2371 else if (pmState == PM_SHUTDOWN_2)
2372 pmState = PM_WAIT_DEAD_END;
2377 * Was it the statistics collector? If so, just try to start a new
2378 * one; no need to force reset of the rest of the system. (If fail,
2379 * we'll try again in future cycles of the main loop.)
2381 if (pid == PgStatPID)
2384 if (!EXIT_STATUS_0(exitstatus))
2385 LogChildExit(LOG, _("statistics collector process"),
2387 if (pmState == PM_RUN)
2388 PgStatPID = pgstat_start();
2392 /* Was it the system logger? If so, try to start a new one */
2393 if (pid == SysLoggerPID)
2396 /* for safety's sake, launch new logger *first* */
2397 SysLoggerPID = SysLogger_Start();
2398 if (!EXIT_STATUS_0(exitstatus))
2399 LogChildExit(LOG, _("system logger process"),
2405 * Else do standard backend child cleanup.
2407 CleanupBackend(pid, exitstatus);
2408 } /* loop over pending child-death reports */
2411 * After cleaning out the SIGCHLD queue, see if we have any state changes
2412 * or actions to make.
2414 PostmasterStateMachine();
2416 /* Done with signal handler */
2417 PG_SETMASK(&UnBlockSig);
2424 * CleanupBackend -- cleanup after terminated backend.
2426 * Remove all local state associated with backend.
2429 CleanupBackend(int pid,
2430 int exitstatus) /* child's exit status. */
2434 LogChildExit(DEBUG2, _("server process"), pid, exitstatus);
2437 * If a backend dies in an ugly way then we must signal all other backends
2438 * to quickdie. If exit status is zero (normal) or one (FATAL exit), we
2439 * assume everything is all right and proceed to remove the backend from
2440 * the active backend list.
2442 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2444 HandleChildCrash(pid, exitstatus, _("server process"));
2448 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2450 Backend *bp = (Backend *) DLE_VAL(curr);
2456 if (!ReleasePostmasterChildSlot(bp->child_slot))
2459 * Uh-oh, the child failed to clean itself up. Treat as a
2462 HandleChildCrash(pid, exitstatus, _("server process"));
2466 ShmemBackendArrayRemove(bp);
2477 * HandleChildCrash -- cleanup after failed backend, bgwriter, walwriter,
2480 * The objectives here are to clean up our local state about the child
2481 * process, and to signal all other remaining children to quickdie.
2484 HandleChildCrash(int pid, int exitstatus, const char *procname)
2491 * Make log entry unless there was a previous crash (if so, nonzero exit
2492 * status is to be expected in SIGQUIT response; don't clutter log)
2496 LogChildExit(LOG, procname, pid, exitstatus);
2498 (errmsg("terminating any other active server processes")));
2501 /* Process regular backends */
2502 for (curr = DLGetHead(BackendList); curr; curr = next)
2504 next = DLGetSucc(curr);
2505 bp = (Backend *) DLE_VAL(curr);
2509 * Found entry for freshly-dead backend, so remove it.
2513 (void) ReleasePostmasterChildSlot(bp->child_slot);
2515 ShmemBackendArrayRemove(bp);
2520 /* Keep looping so we can signal remaining backends */
2525 * This backend is still alive. Unless we did so already, tell it
2526 * to commit hara-kiri.
2528 * SIGQUIT is the special signal that says exit without proc_exit
2529 * and let the user know what's going on. But if SendStop is set
2530 * (-s on command line), then we send SIGSTOP instead, so that we
2531 * can get core dumps from all backends by hand.
2533 * We could exclude dead_end children here, but at least in the
2534 * SIGSTOP case it seems better to include them.
2539 (errmsg_internal("sending %s to process %d",
2540 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2542 signal_child(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
2547 /* Take care of the startup process too */
2548 if (pid == StartupPID)
2550 else if (StartupPID != 0 && !FatalError)
2553 (errmsg_internal("sending %s to process %d",
2554 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2555 (int) StartupPID)));
2556 signal_child(StartupPID, (SendStop ? SIGSTOP : SIGQUIT));
2559 /* Take care of the bgwriter too */
2560 if (pid == BgWriterPID)
2562 else if (BgWriterPID != 0 && !FatalError)
2565 (errmsg_internal("sending %s to process %d",
2566 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2567 (int) BgWriterPID)));
2568 signal_child(BgWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
2571 /* Take care of the walwriter too */
2572 if (pid == WalWriterPID)
2574 else if (WalWriterPID != 0 && !FatalError)
2577 (errmsg_internal("sending %s to process %d",
2578 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2579 (int) WalWriterPID)));
2580 signal_child(WalWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
2583 /* Take care of the autovacuum launcher too */
2584 if (pid == AutoVacPID)
2586 else if (AutoVacPID != 0 && !FatalError)
2589 (errmsg_internal("sending %s to process %d",
2590 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2591 (int) AutoVacPID)));
2592 signal_child(AutoVacPID, (SendStop ? SIGSTOP : SIGQUIT));
2596 * Force a power-cycle of the pgarch process too. (This isn't absolutely
2597 * necessary, but it seems like a good idea for robustness, and it
2598 * simplifies the state-machine logic in the case where a shutdown request
2599 * arrives during crash processing.)
2601 if (PgArchPID != 0 && !FatalError)
2604 (errmsg_internal("sending %s to process %d",
2607 signal_child(PgArchPID, SIGQUIT);
2611 * Force a power-cycle of the pgstat process too. (This isn't absolutely
2612 * necessary, but it seems like a good idea for robustness, and it
2613 * simplifies the state-machine logic in the case where a shutdown request
2614 * arrives during crash processing.)
2616 if (PgStatPID != 0 && !FatalError)
2619 (errmsg_internal("sending %s to process %d",
2622 signal_child(PgStatPID, SIGQUIT);
2623 allow_immediate_pgstat_restart();
2626 /* We do NOT restart the syslogger */
2629 /* We now transit into a state of waiting for children to die */
2630 if (pmState == PM_RECOVERY ||
2631 pmState == PM_RECOVERY_CONSISTENT ||
2632 pmState == PM_RUN ||
2633 pmState == PM_WAIT_BACKUP ||
2634 pmState == PM_SHUTDOWN)
2635 pmState = PM_WAIT_BACKENDS;
2639 * Log the death of a child process.
2642 LogChildExit(int lev, const char *procname, int pid, int exitstatus)
2644 if (WIFEXITED(exitstatus))
2648 translator: %s is a noun phrase describing a child process, such as
2650 (errmsg("%s (PID %d) exited with exit code %d",
2651 procname, pid, WEXITSTATUS(exitstatus))));
2652 else if (WIFSIGNALED(exitstatus))
2657 translator: %s is a noun phrase describing a child process, such as
2659 (errmsg("%s (PID %d) was terminated by exception 0x%X",
2660 procname, pid, WTERMSIG(exitstatus)),
2661 errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value.")));
2662 #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST
2666 translator: %s is a noun phrase describing a child process, such as
2668 (errmsg("%s (PID %d) was terminated by signal %d: %s",
2669 procname, pid, WTERMSIG(exitstatus),
2670 WTERMSIG(exitstatus) < NSIG ?
2671 sys_siglist[WTERMSIG(exitstatus)] : "(unknown)")));
2676 translator: %s is a noun phrase describing a child process, such as
2678 (errmsg("%s (PID %d) was terminated by signal %d",
2679 procname, pid, WTERMSIG(exitstatus))));
2685 translator: %s is a noun phrase describing a child process, such as
2687 (errmsg("%s (PID %d) exited with unrecognized status %d",
2688 procname, pid, exitstatus)));
2692 * Advance the postmaster's state machine and take actions as appropriate
2694 * This is common code for pmdie() and reaper(), which receive the signals
2695 * that might mean we need to change state.
2698 PostmasterStateMachine(void)
2700 if (pmState == PM_WAIT_BACKUP)
2703 * PM_WAIT_BACKUP state ends when online backup mode is not active.
2705 if (!BackupInProgress())
2706 pmState = PM_WAIT_BACKENDS;
2710 * If we are in a state-machine state that implies waiting for backends to
2711 * exit, see if they're all gone, and change state if so.
2713 if (pmState == PM_WAIT_BACKENDS)
2716 * PM_WAIT_BACKENDS state ends when we have no regular backends
2717 * (including autovac workers) and no walwriter or autovac launcher.
2718 * If we are doing crash recovery then we expect the bgwriter to exit
2719 * too, otherwise not. The archiver, stats, and syslogger processes
2720 * are disregarded since they are not connected to shared memory; we
2721 * also disregard dead_end children here.
2723 if (CountChildren() == 0 &&
2725 (BgWriterPID == 0 || !FatalError) &&
2726 WalWriterPID == 0 &&
2732 * Start waiting for dead_end children to die. This state
2733 * change causes ServerLoop to stop creating new ones.
2735 pmState = PM_WAIT_DEAD_END;
2738 * We already SIGQUIT'd the archiver and stats processes, if
2739 * any, when we entered FatalError state.
2745 * If we get here, we are proceeding with normal shutdown. All
2746 * the regular children are gone, and it's time to tell the
2747 * bgwriter to do a shutdown checkpoint.
2749 Assert(Shutdown > NoShutdown);
2750 /* Start the bgwriter if not running */
2751 if (BgWriterPID == 0)
2752 BgWriterPID = StartBackgroundWriter();
2753 /* And tell it to shut down */
2754 if (BgWriterPID != 0)
2756 signal_child(BgWriterPID, SIGUSR2);
2757 pmState = PM_SHUTDOWN;
2762 * If we failed to fork a bgwriter, just shut down. Any
2763 * required cleanup will happen at next restart. We set
2764 * FatalError so that an "abnormal shutdown" message gets
2765 * logged when we exit.
2768 pmState = PM_WAIT_DEAD_END;
2770 /* Kill the archiver and stats collector too */
2772 signal_child(PgArchPID, SIGQUIT);
2774 signal_child(PgStatPID, SIGQUIT);
2780 if (pmState == PM_WAIT_DEAD_END)
2783 * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
2784 * (ie, no dead_end children remain), and the archiver and stats
2785 * collector are gone too.
2787 * The reason we wait for those two is to protect them against a new
2788 * postmaster starting conflicting subprocesses; this isn't an
2789 * ironclad protection, but it at least helps in the
2790 * shutdown-and-immediately-restart scenario. Note that they have
2791 * already been sent appropriate shutdown signals, either during a
2792 * normal state transition leading up to PM_WAIT_DEAD_END, or during
2793 * FatalError processing.
2795 if (DLGetHead(BackendList) == NULL &&
2796 PgArchPID == 0 && PgStatPID == 0)
2798 /* These other guys should be dead already */
2799 Assert(StartupPID == 0);
2800 Assert(BgWriterPID == 0);
2801 Assert(WalWriterPID == 0);
2802 Assert(AutoVacPID == 0);
2803 /* syslogger is not considered here */
2804 pmState = PM_NO_CHILDREN;
2809 * If we've been told to shut down, we exit as soon as there are no
2810 * remaining children. If there was a crash, cleanup will occur at the
2811 * next startup. (Before PostgreSQL 8.3, we tried to recover from the
2812 * crash before exiting, but that seems unwise if we are quitting because
2813 * we got SIGTERM from init --- there may well not be time for recovery
2814 * before init decides to SIGKILL us.)
2816 * Note that the syslogger continues to run. It will exit when it sees
2817 * EOF on its input pipe, which happens when there are no more upstream
2820 if (Shutdown > NoShutdown && pmState == PM_NO_CHILDREN)
2824 ereport(LOG, (errmsg("abnormal database system shutdown")));
2830 * Terminate backup mode to avoid recovery after a clean fast
2835 /* Normal exit from the postmaster is here */
2841 * If recovery failed, wait for all non-syslogger children to exit, and
2842 * then exit postmaster. We don't try to reinitialize when recovery fails,
2843 * because more than likely it will just fail again and we will keep
2846 if (RecoveryError && pmState == PM_NO_CHILDREN)
2850 * If we need to recover from a crash, wait for all non-syslogger children
2851 * to exit, then reset shmem and StartupDataBase.
2853 if (FatalError && pmState == PM_NO_CHILDREN)
2856 (errmsg("all server processes terminated; reinitializing")));
2859 reset_shared(PostPortNumber);
2861 StartupPID = StartupDataBase();
2862 Assert(StartupPID != 0);
2863 pmState = PM_STARTUP;
2869 * Send a signal to a postmaster child process
2871 * On systems that have setsid(), each child process sets itself up as a
2872 * process group leader. For signals that are generally interpreted in the
2873 * appropriate fashion, we signal the entire process group not just the
2874 * direct child process. This allows us to, for example, SIGQUIT a blocked
2875 * archive_recovery script, or SIGINT a script being run by a backend via
2878 * There is a race condition for recently-forked children: they might not
2879 * have executed setsid() yet. So we signal the child directly as well as
2880 * the group. We assume such a child will handle the signal before trying
2881 * to spawn any grandchild processes. We also assume that signaling the
2882 * child twice will not cause any problems.
2885 signal_child(pid_t pid, int signal)
2887 if (kill(pid, signal) < 0)
2888 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
2896 if (kill(-pid, signal) < 0)
2897 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) (-pid), signal);
2906 * Send a signal to all backend children, including autovacuum workers
2907 * (but NOT special children; dead_end children are never signaled, either).
2908 * If only_autovac is TRUE, only the autovacuum worker processes are signalled.
2911 SignalSomeChildren(int signal, bool only_autovac)
2915 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2917 Backend *bp = (Backend *) DLE_VAL(curr);
2921 if (only_autovac && !bp->is_autovacuum)
2925 (errmsg_internal("sending signal %d to process %d",
2926 signal, (int) bp->pid)));
2927 signal_child(bp->pid, signal);
2932 * BackendStartup -- start backend process
2934 * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
2936 * Note: if you change this code, also consider StartAutovacuumWorker.
2939 BackendStartup(Port *port)
2941 Backend *bn; /* for backend cleanup */
2945 * Create backend data structure. Better before the fork() so we can
2946 * handle failure cleanly.
2948 bn = (Backend *) malloc(sizeof(Backend));
2952 (errcode(ERRCODE_OUT_OF_MEMORY),
2953 errmsg("out of memory")));
2954 return STATUS_ERROR;
2958 * Compute the cancel key that will be assigned to this backend. The
2959 * backend will have its own copy in the forked-off process' value of
2960 * MyCancelKey, so that it can transmit the key to the frontend.
2962 MyCancelKey = PostmasterRandom();
2963 bn->cancel_key = MyCancelKey;
2965 /* Pass down canAcceptConnections state */
2966 port->canAcceptConnections = canAcceptConnections();
2967 bn->dead_end = (port->canAcceptConnections != CAC_OK &&
2968 port->canAcceptConnections != CAC_WAITBACKUP);
2971 * Unless it's a dead_end child, assign it a child slot number
2974 bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
2979 pid = backend_forkexec(port);
2980 #else /* !EXEC_BACKEND */
2981 pid = fork_process();
2982 if (pid == 0) /* child */
2987 * Let's clean up ourselves as the postmaster child, and close the
2988 * postmaster's listen sockets. (In EXEC_BACKEND case this is all
2989 * done in SubPostmasterMain.)
2991 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
2993 MyProcPid = getpid(); /* reset MyProcPid */
2995 MyStartTime = time(NULL);
2997 /* We don't want the postmaster's proc_exit() handlers */
3000 /* Close the postmaster's sockets */
3001 ClosePostmasterPorts(false);
3003 /* Perform additional initialization and client authentication */
3004 BackendInitialize(port);
3006 /* And run the backend */
3007 proc_exit(BackendRun(port));
3009 #endif /* EXEC_BACKEND */
3013 /* in parent, fork failed */
3014 int save_errno = errno;
3019 (errmsg("could not fork new process for connection: %m")));
3020 report_fork_failure_to_client(port, save_errno);
3021 return STATUS_ERROR;
3024 /* in parent, successful fork */
3026 (errmsg_internal("forked new backend, pid=%d socket=%d",
3027 (int) pid, port->sock)));
3030 * Everything's been successful, it's safe to add this backend to our list
3034 bn->is_autovacuum = false;
3035 DLInitElem(&bn->elem, bn);
3036 DLAddHead(BackendList, &bn->elem);
3039 ShmemBackendArrayAdd(bn);
3046 * Try to report backend fork() failure to client before we close the
3047 * connection. Since we do not care to risk blocking the postmaster on
3048 * this connection, we set the connection to non-blocking and try only once.
3050 * This is grungy special-purpose code; we cannot use backend libpq since
3051 * it's not up and running.
3054 report_fork_failure_to_client(Port *port, int errnum)
3059 /* Format the error message packet (always V2 protocol) */
3060 snprintf(buffer, sizeof(buffer), "E%s%s\n",
3061 _("could not fork new process for connection: "),
3064 /* Set port to non-blocking. Don't do send() if this fails */
3065 if (!pg_set_noblock(port->sock))
3068 /* We'll retry after EINTR, but ignore all other failures */
3071 rc = send(port->sock, buffer, strlen(buffer) + 1, 0);
3072 } while (rc < 0 && errno == EINTR);
3077 * split_opts -- split a string of options and append it to an argv array
3079 * NB: the string is destructively modified!
3081 * Since no current POSTGRES arguments require any quoting characters,
3082 * we can use the simple-minded tactic of assuming each set of space-
3083 * delimited characters is a separate argv element.
3085 * If you don't like that, well, we *used* to pass the whole option string
3086 * as ONE argument to execl(), which was even less intelligent...
3089 split_opts(char **argv, int *argcp, char *s)
3093 while (isspace((unsigned char) *s))
3097 argv[(*argcp)++] = s;
3098 while (*s && !isspace((unsigned char) *s))
3107 * BackendInitialize -- initialize an interactive (postmaster-child)
3108 * backend process, and perform client authentication.
3110 * returns: nothing. Will not return at all if there's any failure.
3112 * Note: this code does not depend on having any access to shared memory.
3113 * In the EXEC_BACKEND case, we are physically attached to shared memory
3114 * but have not yet set up most of our local pointers to shmem structures.
3117 BackendInitialize(Port *port)
3120 char remote_host[NI_MAXHOST];
3121 char remote_port[NI_MAXSERV];
3122 char remote_ps_data[NI_MAXHOST];
3124 /* Save port etc. for ps status */
3128 * PreAuthDelay is a debugging aid for investigating problems in the
3129 * authentication cycle: it can be set in postgresql.conf to allow time to
3130 * attach to the newly-forked backend with a debugger. (See also the -W
3131 * backend switch, which we allow clients to pass through PGOPTIONS, but
3132 * it is not honored until after authentication.)
3134 if (PreAuthDelay > 0)
3135 pg_usleep(PreAuthDelay * 1000000L);
3137 ClientAuthInProgress = true; /* limit visibility of log messages */
3139 /* save process start time */
3140 port->SessionStartTime = GetCurrentTimestamp();
3141 MyStartTime = timestamptz_to_time_t(port->SessionStartTime);
3143 /* set these to empty in case they are needed before we set them up */
3144 port->remote_host = "";
3145 port->remote_port = "";
3148 * Initialize libpq and enable reporting of ereport errors to the client.
3149 * Must do this now because authentication uses libpq to send messages.
3151 pq_init(); /* initialize libpq to talk to client */
3152 whereToSendOutput = DestRemote; /* now safe to ereport to client */
3155 * If possible, make this process a group leader, so that the postmaster
3156 * can signal any child processes too. (We do this now on the off chance
3157 * that something might spawn a child process during authentication.)
3161 elog(FATAL, "setsid() failed: %m");
3165 * We arrange for a simple exit(1) if we receive SIGTERM or SIGQUIT during
3166 * any client authentication related communication. Otherwise the
3167 * postmaster cannot shutdown the database FAST or IMMED cleanly if a
3168 * buggy client blocks a backend during authentication.
3170 pqsignal(SIGTERM, authdie);
3171 pqsignal(SIGQUIT, authdie);
3172 pqsignal(SIGALRM, authdie);
3173 PG_SETMASK(&AuthBlockSig);
3176 * Get the remote host name and port for logging and status display.
3178 remote_host[0] = '\0';
3179 remote_port[0] = '\0';
3180 if (pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
3181 remote_host, sizeof(remote_host),
3182 remote_port, sizeof(remote_port),
3183 (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV))
3185 int ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
3186 remote_host, sizeof(remote_host),
3187 remote_port, sizeof(remote_port),
3188 NI_NUMERICHOST | NI_NUMERICSERV);
3192 (errmsg_internal("pg_getnameinfo_all() failed: %s",
3193 gai_strerror(ret))));
3195 snprintf(remote_ps_data, sizeof(remote_ps_data),
3196 remote_port[0] == '\0' ? "%s" : "%s(%s)",
3197 remote_host, remote_port);
3199 if (Log_connections)
3201 (errmsg("connection received: host=%s%s%s",
3202 remote_host, remote_port[0] ? " port=" : "",
3206 * save remote_host and remote_port in port structure
3208 port->remote_host = strdup(remote_host);
3209 port->remote_port = strdup(remote_port);
3212 * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
3213 * etcetera from the postmaster, and have to load them ourselves. Build
3214 * the PostmasterContext (which didn't exist before, in this process) to
3217 * FIXME: [fork/exec] Ugh. Is there a way around this overhead?
3220 Assert(PostmasterContext == NULL);
3221 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
3223 ALLOCSET_DEFAULT_MINSIZE,
3224 ALLOCSET_DEFAULT_INITSIZE,
3225 ALLOCSET_DEFAULT_MAXSIZE);
3226 MemoryContextSwitchTo(PostmasterContext);
3231 * It makes no sense continue if we fail to load the HBA file, since
3232 * there is no way to connect to the database in this case.
3235 (errmsg("could not load pg_hba.conf")));
3242 * Ready to begin client interaction. We will give up and exit(0) after a
3243 * time delay, so that a broken client can't hog a connection
3244 * indefinitely. PreAuthDelay doesn't count against the time limit.
3246 if (!enable_sig_alarm(AuthenticationTimeout * 1000, false))
3247 elog(FATAL, "could not set timer for authorization timeout");
3250 * Receive the startup packet (which might turn out to be a cancel request
3253 status = ProcessStartupPacket(port, false);
3255 if (status != STATUS_OK)
3259 * Now that we have the user and database name, we can set the process
3260 * title for ps. It's good to do this as early as possible in startup.
3262 init_ps_display(port->user_name, port->database_name, remote_ps_data,
3263 update_process_title ? "authentication" : "");
3266 * Now perform authentication exchange.
3268 ClientAuthentication(port); /* might not return, if failure */
3271 * Done with authentication. Disable timeout, and prevent SIGTERM/SIGQUIT
3272 * again until backend startup is complete.
3274 if (!disable_sig_alarm(false))
3275 elog(FATAL, "could not disable timer for authorization timeout");
3276 PG_SETMASK(&BlockSig);
3278 if (Log_connections)
3280 (errmsg("connection authorized: user=%s database=%s",
3281 port->user_name, port->database_name)));
3286 * BackendRun -- set up the backend's argument list and invoke PostgresMain()
3289 * Shouldn't return at all.
3290 * If PostgresMain() fails, return status.
3293 BackendRun(Port *port)
3304 * Don't want backend to be able to see the postmaster random number
3305 * generator state. We have to clobber the static random_seed *and* start
3306 * a new random sequence in the random() library function.
3309 random_start_time.tv_usec = 0;
3310 /* slightly hacky way to get integer microseconds part of timestamptz */
3311 TimestampDifference(0, port->SessionStartTime, &secs, &usecs);
3312 srandom((unsigned int) (MyProcPid ^ usecs));
3315 * Now, build the argv vector that will be given to PostgresMain.
3317 * The layout of the command line is
3318 * postgres [secure switches] -y databasename [insecure switches]
3319 * where the switches after -y come from the client request.
3321 * The maximum possible number of commandline arguments that could come
3322 * from ExtraOptions or port->cmdline_options is (strlen + 1) / 2; see
3326 maxac = 10; /* for fixed args supplied below */
3327 maxac += (strlen(ExtraOptions) + 1) / 2;
3328 if (port->cmdline_options)
3329 maxac += (strlen(port->cmdline_options) + 1) / 2;
3331 av = (char **) MemoryContextAlloc(TopMemoryContext,
3332 maxac * sizeof(char *));
3335 av[ac++] = "postgres";
3338 * Pass any backend switches specified with -o in the postmaster's own
3339 * command line. We assume these are secure. (It's OK to mangle
3340 * ExtraOptions now, since we're safely inside a subprocess.)
3342 split_opts(av, &ac, ExtraOptions);
3344 /* Tell the backend what protocol the frontend is using. */
3345 snprintf(protobuf, sizeof(protobuf), "-v%u", port->proto);
3346 av[ac++] = protobuf;
3349 * Tell the backend it is being called from the postmaster, and which
3350 * database to use. -y marks the end of secure switches.
3353 av[ac++] = port->database_name;
3356 * Pass the (insecure) option switches from the connection request. (It's
3357 * OK to mangle port->cmdline_options now.)
3359 if (port->cmdline_options)
3360 split_opts(av, &ac, port->cmdline_options);
3367 * Release postmaster's working memory context so that backend can recycle
3368 * the space. Note this does not trash *MyProcPort, because ConnCreate()
3369 * allocated that space with malloc() ... else we'd need to copy the Port
3370 * data here. Also, subsidiary data such as the username isn't lost
3371 * either; see ProcessStartupPacket().
3373 MemoryContextSwitchTo(TopMemoryContext);
3374 MemoryContextDelete(PostmasterContext);
3375 PostmasterContext = NULL;
3378 * Debug: print arguments being passed to backend
3381 (errmsg_internal("%s child[%d]: starting with (",
3382 progname, (int) getpid())));
3383 for (i = 0; i < ac; ++i)
3385 (errmsg_internal("\t%s", av[i])));
3387 (errmsg_internal(")")));
3389 ClientAuthInProgress = false; /* client_min_messages is active now */
3391 return (PostgresMain(ac, av, port->user_name));
3398 * postmaster_forkexec -- fork and exec a postmaster subprocess
3400 * The caller must have set up the argv array already, except for argv[2]
3401 * which will be filled with the name of the temp variable file.
3403 * Returns the child process PID, or -1 on fork failure (a suitable error
3404 * message has been logged on failure).
3406 * All uses of this routine will dispatch to SubPostmasterMain in the
3410 postmaster_forkexec(int argc, char *argv[])
3414 /* This entry point passes dummy values for the Port variables */
3415 memset(&port, 0, sizeof(port));
3416 return internal_forkexec(argc, argv, &port);
3420 * backend_forkexec -- fork/exec off a backend process
3422 * Some operating systems (WIN32) don't have fork() so we have to simulate
3423 * it by storing parameters that need to be passed to the child and
3424 * then create a new child process.
3426 * returns the pid of the fork/exec'd process, or -1 on failure
3429 backend_forkexec(Port *port)
3434 av[ac++] = "postgres";
3435 av[ac++] = "--forkbackend";
3436 av[ac++] = NULL; /* filled in by internal_forkexec */
3439 Assert(ac < lengthof(av));
3441 return internal_forkexec(ac, av, port);
3447 * internal_forkexec non-win32 implementation
3449 * - writes out backend variables to the parameter file
3450 * - fork():s, and then exec():s the child process
3453 internal_forkexec(int argc, char *argv[], Port *port)
3455 static unsigned long tmpBackendFileNum = 0;
3457 char tmpfilename[MAXPGPATH];
3458 BackendParameters param;
3461 if (!save_backend_variables(¶m, port))
3462 return -1; /* log made by save_backend_variables */
3464 /* Calculate name for temp file */
3465 snprintf(tmpfilename, MAXPGPATH, "%s/%s.backend_var.%d.%lu",
3466 PG_TEMP_FILES_DIR, PG_TEMP_FILE_PREFIX,
3467 MyProcPid, ++tmpBackendFileNum);
3470 fp = AllocateFile(tmpfilename, PG_BINARY_W);
3473 /* As in OpenTemporaryFile, try to make the temp-file directory */
3474 mkdir(PG_TEMP_FILES_DIR, S_IRWXU);
3476 fp = AllocateFile(tmpfilename, PG_BINARY_W);
3480 (errcode_for_file_access(),
3481 errmsg("could not create file \"%s\": %m",
3487 if (fwrite(¶m, sizeof(param), 1, fp) != 1)
3490 (errcode_for_file_access(),
3491 errmsg("could not write to file \"%s\": %m", tmpfilename)));
3500 (errcode_for_file_access(),
3501 errmsg("could not write to file \"%s\": %m", tmpfilename)));
3505 /* Make sure caller set up argv properly */
3507 Assert(argv[argc] == NULL);
3508 Assert(strncmp(argv[1], "--fork", 6) == 0);
3509 Assert(argv[2] == NULL);
3511 /* Insert temp file name after --fork argument */
3512 argv[2] = tmpfilename;
3514 /* Fire off execv in child */
3515 if ((pid = fork_process()) == 0)
3517 if (execv(postgres_exec_path, argv) < 0)
3520 (errmsg("could not execute server process \"%s\": %m",
3521 postgres_exec_path)));
3522 /* We're already in the child process here, can't return */
3527 return pid; /* Parent returns pid, or -1 on fork failure */
3532 * internal_forkexec win32 implementation
3534 * - starts backend using CreateProcess(), in suspended state
3535 * - writes out backend variables to the parameter file
3536 * - during this, duplicates handles and sockets required for
3537 * inheritance into the new process
3538 * - resumes execution of the new process once the backend parameter
3542 internal_forkexec(int argc, char *argv[], Port *port)
3545 PROCESS_INFORMATION pi;
3548 char cmdLine[MAXPGPATH * 2];
3550 BackendParameters *param;
3551 SECURITY_ATTRIBUTES sa;
3552 char paramHandleStr[32];
3553 win32_deadchild_waitinfo *childinfo;
3555 /* Make sure caller set up argv properly */
3557 Assert(argv[argc] == NULL);
3558 Assert(strncmp(argv[1], "--fork", 6) == 0);
3559 Assert(argv[2] == NULL);
3561 /* Set up shared memory for parameter passing */
3562 ZeroMemory(&sa, sizeof(sa));
3563 sa.nLength = sizeof(sa);
3564 sa.bInheritHandle = TRUE;
3565 paramHandle = CreateFileMapping(INVALID_HANDLE_VALUE,
3569 sizeof(BackendParameters),
3571 if (paramHandle == INVALID_HANDLE_VALUE)
3573 elog(LOG, "could not create backend parameter file mapping: error code %d",
3574 (int) GetLastError());
3578 param = MapViewOfFile(paramHandle, FILE_MAP_WRITE, 0, 0, sizeof(BackendParameters));
3581 elog(LOG, "could not map backend parameter memory: error code %d",
3582 (int) GetLastError());
3583 CloseHandle(paramHandle);
3587 /* Insert temp file name after --fork argument */
3588 sprintf(paramHandleStr, "%lu", (DWORD) paramHandle);
3589 argv[2] = paramHandleStr;
3591 /* Format the cmd line */
3592 cmdLine[sizeof(cmdLine) - 1] = '\0';
3593 cmdLine[sizeof(cmdLine) - 2] = '\0';
3594 snprintf(cmdLine, sizeof(cmdLine) - 1, "\"%s\"", postgres_exec_path);
3596 while (argv[++i] != NULL)
3598 j = strlen(cmdLine);
3599 snprintf(cmdLine + j, sizeof(cmdLine) - 1 - j, " \"%s\"", argv[i]);
3601 if (cmdLine[sizeof(cmdLine) - 2] != '\0')
3603 elog(LOG, "subprocess command line too long");
3607 memset(&pi, 0, sizeof(pi));
3608 memset(&si, 0, sizeof(si));
3612 * Create the subprocess in a suspended state. This will be resumed later,
3613 * once we have written out the parameter file.
3615 if (!CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, CREATE_SUSPENDED,
3616 NULL, NULL, &si, &pi))
3618 elog(LOG, "CreateProcess call failed: %m (error code %d)",
3619 (int) GetLastError());
3623 if (!save_backend_variables(param, port, pi.hProcess, pi.dwProcessId))
3626 * log made by save_backend_variables, but we have to clean up the
3627 * mess with the half-started process
3629 if (!TerminateProcess(pi.hProcess, 255))
3631 (errmsg_internal("could not terminate unstarted process: error code %d",
3632 (int) GetLastError())));
3633 CloseHandle(pi.hProcess);
3634 CloseHandle(pi.hThread);
3635 return -1; /* log made by save_backend_variables */
3638 /* Drop the parameter shared memory that is now inherited to the backend */
3639 if (!UnmapViewOfFile(param))
3640 elog(LOG, "could not unmap view of backend parameter file: error code %d",
3641 (int) GetLastError());
3642 if (!CloseHandle(paramHandle))
3643 elog(LOG, "could not close handle to backend parameter file: error code %d",
3644 (int) GetLastError());
3647 * Reserve the memory region used by our main shared memory segment before we
3648 * resume the child process.
3650 if (!pgwin32_ReserveSharedMemoryRegion(pi.hProcess))
3653 * Failed to reserve the memory, so terminate the newly created
3654 * process and give up.
3656 if (!TerminateProcess(pi.hProcess, 255))
3658 (errmsg_internal("could not terminate process that failed to reserve memory: error code %d",
3659 (int) GetLastError())));
3660 CloseHandle(pi.hProcess);
3661 CloseHandle(pi.hThread);
3662 return -1; /* logging done made by pgwin32_ReserveSharedMemoryRegion() */
3666 * Now that the backend variables are written out, we start the child
3667 * thread so it can start initializing while we set up the rest of the
3670 if (ResumeThread(pi.hThread) == -1)
3672 if (!TerminateProcess(pi.hProcess, 255))
3675 (errmsg_internal("could not terminate unstartable process: error code %d",
3676 (int) GetLastError())));
3677 CloseHandle(pi.hProcess);
3678 CloseHandle(pi.hThread);
3681 CloseHandle(pi.hProcess);
3682 CloseHandle(pi.hThread);
3684 (errmsg_internal("could not resume thread of unstarted process: error code %d",
3685 (int) GetLastError())));
3690 * Queue a waiter for to signal when this child dies. The wait will be
3691 * handled automatically by an operating system thread pool.
3693 * Note: use malloc instead of palloc, since it needs to be thread-safe.
3694 * Struct will be free():d from the callback function that runs on a
3697 childinfo = malloc(sizeof(win32_deadchild_waitinfo));
3700 (errcode(ERRCODE_OUT_OF_MEMORY),
3701 errmsg("out of memory")));
3703 childinfo->procHandle = pi.hProcess;
3704 childinfo->procId = pi.dwProcessId;
3706 if (!RegisterWaitForSingleObject(&childinfo->waitHandle,
3708 pgwin32_deadchild_callback,
3711 WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD))
3713 (errmsg_internal("could not register process for wait: error code %d",
3714 (int) GetLastError())));
3716 /* Don't close pi.hProcess here - the wait thread needs access to it */
3718 CloseHandle(pi.hThread);
3720 return pi.dwProcessId;
3726 * SubPostmasterMain -- Get the fork/exec'd process into a state equivalent
3727 * to what it would be if we'd simply forked on Unix, and then
3728 * dispatch to the appropriate place.
3730 * The first two command line arguments are expected to be "--forkFOO"
3731 * (where FOO indicates which postmaster child we are to become), and
3732 * the name of a variables file that we can read to load data that would
3733 * have been inherited by fork() on Unix. Remaining arguments go to the
3734 * subprocess FooMain() routine.
3737 SubPostmasterMain(int argc, char *argv[])
3741 /* Do this sooner rather than later... */
3742 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
3744 MyProcPid = getpid(); /* reset MyProcPid */
3746 MyStartTime = time(NULL);
3749 * make sure stderr is in binary mode before anything can possibly be
3750 * written to it, in case it's actually the syslogger pipe, so the pipe
3751 * chunking protocol isn't disturbed. Non-logpipe data gets translated on
3752 * redirection (e.g. via pg_ctl -l) anyway.
3755 _setmode(fileno(stderr), _O_BINARY);
3758 /* Lose the postmaster's on-exit routines (really a no-op) */
3761 /* In EXEC_BACKEND case we will not have inherited these settings */
3762 IsPostmasterEnvironment = true;
3763 whereToSendOutput = DestNone;
3765 /* Setup essential subsystems (to ensure elog() behaves sanely) */
3766 MemoryContextInit();
3767 InitializeGUCOptions();
3769 /* Read in the variables file */
3770 memset(&port, 0, sizeof(Port));
3771 read_backend_variables(argv[2], &port);
3774 * Set up memory area for GSS information. Mirrors the code in ConnCreate
3775 * for the non-exec case.
3777 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
3778 port.gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
3781 (errcode(ERRCODE_OUT_OF_MEMORY),
3782 errmsg("out of memory")));
3786 /* Check we got appropriate args */
3788 elog(FATAL, "invalid subpostmaster invocation");
3791 * If appropriate, physically re-attach to shared memory segment. We want
3792 * to do this before going any further to ensure that we can attach at the
3793 * same address the postmaster used.
3795 if (strcmp(argv[1], "--forkbackend") == 0 ||
3796 strcmp(argv[1], "--forkavlauncher") == 0 ||
3797 strcmp(argv[1], "--forkavworker") == 0 ||
3798 strcmp(argv[1], "--forkboot") == 0)
3799 PGSharedMemoryReAttach();
3801 /* autovacuum needs this set before calling InitProcess */
3802 if (strcmp(argv[1], "--forkavlauncher") == 0)
3803 AutovacuumLauncherIAm();
3804 if (strcmp(argv[1], "--forkavworker") == 0)
3805 AutovacuumWorkerIAm();
3808 * Start our win32 signal implementation. This has to be done after we
3809 * read the backend variables, because we need to pick up the signal pipe
3810 * from the parent process.
3813 pgwin32_signal_initialize();
3816 /* In EXEC_BACKEND case we will not have inherited these settings */
3818 PG_SETMASK(&BlockSig);
3820 /* Read in remaining GUC variables */
3821 read_nondefault_variables();
3824 * Reload any libraries that were preloaded by the postmaster. Since we
3825 * exec'd this process, those libraries didn't come along with us; but we
3826 * should load them into all child processes to be consistent with the
3827 * non-EXEC_BACKEND behavior.
3829 process_shared_preload_libraries();
3831 /* Run backend or appropriate child */
3832 if (strcmp(argv[1], "--forkbackend") == 0)
3834 Assert(argc == 3); /* shouldn't be any more args */
3836 /* Close the postmaster's sockets */
3837 ClosePostmasterPorts(false);
3840 * Need to reinitialize the SSL library in the backend, since the
3841 * context structures contain function pointers and cannot be passed
3842 * through the parameter file.
3844 * XXX should we do this in all child processes? For the moment it's
3845 * enough to do it in backend children.
3849 secure_initialize();
3853 * Perform additional initialization and client authentication.
3855 * We want to do this before InitProcess() for a couple of reasons: 1.
3856 * so that we aren't eating up a PGPROC slot while waiting on the
3857 * client. 2. so that if InitProcess() fails due to being out of
3858 * PGPROC slots, we have already initialized libpq and are able to
3859 * report the error to the client.
3861 BackendInitialize(&port);
3863 /* Restore basic shared memory pointers */
3864 InitShmemAccess(UsedShmemSegAddr);
3866 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3870 * Attach process to shared data structures. If testing EXEC_BACKEND
3871 * on Linux, you must run this as root before starting the postmaster:
3873 * echo 0 >/proc/sys/kernel/randomize_va_space
3875 * This prevents a randomized stack base address that causes child
3876 * shared memory to be at a different address than the parent, making
3877 * it impossible to attached to shared memory. Return the value to
3878 * '1' when finished.
3880 CreateSharedMemoryAndSemaphores(false, 0);
3882 /* And run the backend */
3883 proc_exit(BackendRun(&port));
3885 if (strcmp(argv[1], "--forkboot") == 0)
3887 /* Close the postmaster's sockets */
3888 ClosePostmasterPorts(false);
3890 /* Restore basic shared memory pointers */
3891 InitShmemAccess(UsedShmemSegAddr);
3893 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3894 InitAuxiliaryProcess();
3896 /* Attach process to shared data structures */
3897 CreateSharedMemoryAndSemaphores(false, 0);
3899 AuxiliaryProcessMain(argc - 2, argv + 2);
3902 if (strcmp(argv[1], "--forkavlauncher") == 0)
3904 /* Close the postmaster's sockets */
3905 ClosePostmasterPorts(false);
3907 /* Restore basic shared memory pointers */
3908 InitShmemAccess(UsedShmemSegAddr);
3910 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3911 InitAuxiliaryProcess();
3913 /* Attach process to shared data structures */
3914 CreateSharedMemoryAndSemaphores(false, 0);
3916 AutoVacLauncherMain(argc - 2, argv + 2);
3919 if (strcmp(argv[1], "--forkavworker") == 0)
3921 /* Close the postmaster's sockets */
3922 ClosePostmasterPorts(false);
3924 /* Restore basic shared memory pointers */
3925 InitShmemAccess(UsedShmemSegAddr);
3927 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3930 /* Attach process to shared data structures */
3931 CreateSharedMemoryAndSemaphores(false, 0);
3933 AutoVacWorkerMain(argc - 2, argv + 2);
3936 if (strcmp(argv[1], "--forkarch") == 0)
3938 /* Close the postmaster's sockets */
3939 ClosePostmasterPorts(false);
3941 /* Do not want to attach to shared memory */
3943 PgArchiverMain(argc, argv);
3946 if (strcmp(argv[1], "--forkcol") == 0)
3948 /* Close the postmaster's sockets */
3949 ClosePostmasterPorts(false);
3951 /* Do not want to attach to shared memory */
3953 PgstatCollectorMain(argc, argv);
3956 if (strcmp(argv[1], "--forklog") == 0)
3958 /* Close the postmaster's sockets */
3959 ClosePostmasterPorts(true);
3961 /* Do not want to attach to shared memory */
3963 SysLoggerMain(argc, argv);
3967 return 1; /* shouldn't get here */
3969 #endif /* EXEC_BACKEND */
3973 * ExitPostmaster -- cleanup
3975 * Do NOT call exit() directly --- always go through here!
3978 ExitPostmaster(int status)
3980 /* should cleanup shared memory and kill all backends */
3983 * Not sure of the semantics here. When the Postmaster dies, should the
3984 * backends all be killed? probably not.
3986 * MUST -- vadim 05-10-1999
3993 * sigusr1_handler - handle signal conditions from child processes
3996 sigusr1_handler(SIGNAL_ARGS)
3998 int save_errno = errno;
4000 PG_SETMASK(&BlockSig);
4003 * RECOVERY_STARTED and RECOVERY_CONSISTENT signals are ignored in
4004 * unexpected states. If the startup process quickly starts up, completes
4005 * recovery, exits, we might process the death of the startup process
4006 * first. We don't want to go back to recovery in that case.
4008 if (CheckPostmasterSignal(PMSIGNAL_RECOVERY_STARTED) &&
4009 pmState == PM_STARTUP)
4011 /* WAL redo has started. We're out of reinitialization. */
4015 * Crank up the background writer. It doesn't matter if this fails,
4016 * we'll just try again later.
4018 Assert(BgWriterPID == 0);
4019 BgWriterPID = StartBackgroundWriter();
4021 pmState = PM_RECOVERY;
4023 if (CheckPostmasterSignal(PMSIGNAL_RECOVERY_CONSISTENT) &&
4024 pmState == PM_RECOVERY)
4027 * Load the flat authorization file into postmaster's cache. The
4028 * startup process won't have recomputed this from the database yet,
4029 * so it may change following recovery.
4034 * Likewise, start other special children as needed.
4036 Assert(PgStatPID == 0);
4037 PgStatPID = pgstat_start();
4039 /* XXX at this point we could accept read-only connections */
4041 (errmsg("database system is in consistent recovery mode")));
4043 pmState = PM_RECOVERY_CONSISTENT;
4046 if (CheckPostmasterSignal(PMSIGNAL_PASSWORD_CHANGE))
4049 * Authorization file has changed.
4054 if (CheckPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER) &&
4058 * Send SIGUSR1 to archiver process, to wake it up and begin archiving
4059 * next transaction log file.
4061 signal_child(PgArchPID, SIGUSR1);
4064 if (CheckPostmasterSignal(PMSIGNAL_ROTATE_LOGFILE) &&
4067 /* Tell syslogger to rotate logfile */
4068 signal_child(SysLoggerPID, SIGUSR1);
4071 if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER))
4074 * Start one iteration of the autovacuum daemon, even if autovacuuming
4075 * is nominally not enabled. This is so we can have an active defense
4076 * against transaction ID wraparound. We set a flag for the main loop
4077 * to do it rather than trying to do it here --- this is because the
4078 * autovac process itself may send the signal, and we want to handle
4079 * that by launching another iteration as soon as the current one
4082 start_autovac_launcher = true;
4085 if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER))
4087 /* The autovacuum launcher wants us to start a worker process. */
4088 StartAutovacuumWorker();
4091 PG_SETMASK(&UnBlockSig);
4098 * Dummy signal handler
4100 * We use this for signals that we don't actually use in the postmaster,
4101 * but we do use in backends. If we were to SIG_IGN such signals in the
4102 * postmaster, then a newly started backend might drop a signal that arrives
4103 * before it's able to reconfigure its signal processing. (See notes in
4107 dummy_handler(SIGNAL_ARGS)
4115 RandomSalt(char *md5Salt)
4120 * We use % 255, sacrificing one possible byte value, so as to ensure that
4121 * all bits of the random() value participate in the result. While at it,
4122 * add one to avoid generating any null bytes.
4124 rand = PostmasterRandom();
4125 md5Salt[0] = (rand % 255) + 1;
4126 rand = PostmasterRandom();
4127 md5Salt[1] = (rand % 255) + 1;
4128 rand = PostmasterRandom();
4129 md5Salt[2] = (rand % 255) + 1;
4130 rand = PostmasterRandom();
4131 md5Salt[3] = (rand % 255) + 1;
4138 PostmasterRandom(void)
4141 * Select a random seed at the time of first receiving a request.
4143 if (random_seed == 0)
4147 struct timeval random_stop_time;
4149 gettimeofday(&random_stop_time, NULL);
4152 * We are not sure how much precision is in tv_usec, so we swap
4153 * the high and low 16 bits of 'random_stop_time' and XOR them
4154 * with 'random_start_time'. On the off chance that the result is
4155 * 0, we loop until it isn't.
4157 random_seed = random_start_time.tv_usec ^
4158 ((random_stop_time.tv_usec << 16) |
4159 ((random_stop_time.tv_usec >> 16) & 0xffff));
4161 while (random_seed == 0);
4163 srandom(random_seed);
4170 * Count up number of child processes (excluding special children and
4171 * dead_end children)
4179 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
4181 Backend *bp = (Backend *) DLE_VAL(curr);
4191 * StartChildProcess -- start an auxiliary process for the postmaster
4193 * xlop determines what kind of child will be started. All child types
4194 * initially go to AuxiliaryProcessMain, which will handle common setup.
4196 * Return value of StartChildProcess is subprocess' PID, or 0 if failed
4197 * to start subprocess.
4200 StartChildProcess(AuxProcType type)
4208 * Set up command-line arguments for subprocess
4210 av[ac++] = "postgres";
4213 av[ac++] = "--forkboot";
4214 av[ac++] = NULL; /* filled in by postmaster_forkexec */
4217 snprintf(typebuf, sizeof(typebuf), "-x%d", type);
4221 Assert(ac < lengthof(av));
4224 pid = postmaster_forkexec(ac, av);
4225 #else /* !EXEC_BACKEND */
4226 pid = fork_process();
4228 if (pid == 0) /* child */
4230 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
4232 /* Close the postmaster's sockets */
4233 ClosePostmasterPorts(false);
4235 /* Lose the postmaster's on-exit routines and port connections */
4238 /* Release postmaster's working memory context */
4239 MemoryContextSwitchTo(TopMemoryContext);
4240 MemoryContextDelete(PostmasterContext);
4241 PostmasterContext = NULL;
4243 AuxiliaryProcessMain(ac, av);
4246 #endif /* EXEC_BACKEND */
4250 /* in parent, fork failed */
4251 int save_errno = errno;
4256 case StartupProcess:
4258 (errmsg("could not fork startup process: %m")));
4260 case BgWriterProcess:
4262 (errmsg("could not fork background writer process: %m")));
4264 case WalWriterProcess:
4266 (errmsg("could not fork WAL writer process: %m")));
4270 (errmsg("could not fork process: %m")));
4275 * fork failure is fatal during startup, but there's no need to choke
4276 * immediately if starting other child types fails.
4278 if (type == StartupProcess)
4284 * in parent, successful fork
4290 * StartAutovacuumWorker
4291 * Start an autovac worker process.
4293 * This function is here because it enters the resulting PID into the
4294 * postmaster's private backends list.
4296 * NB -- this code very roughly matches BackendStartup.
4299 StartAutovacuumWorker(void)
4304 * If not in condition to run a process, don't try, but handle it like a
4305 * fork failure. This does not normally happen, since the signal is only
4306 * supposed to be sent by autovacuum launcher when it's OK to do it, but
4307 * we have to check to avoid race-condition problems during DB state
4310 if (canAcceptConnections() == CAC_OK)
4312 bn = (Backend *) malloc(sizeof(Backend));
4316 * Compute the cancel key that will be assigned to this session.
4317 * We probably don't need cancel keys for autovac workers, but
4318 * we'd better have something random in the field to prevent
4319 * unfriendly people from sending cancels to them.
4321 MyCancelKey = PostmasterRandom();
4322 bn->cancel_key = MyCancelKey;
4324 /* Autovac workers are not dead_end and need a child slot */
4325 bn->dead_end = false;
4326 bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
4328 bn->pid = StartAutoVacWorker();
4331 bn->is_autovacuum = true;
4332 DLInitElem(&bn->elem, bn);
4333 DLAddHead(BackendList, &bn->elem);
4335 ShmemBackendArrayAdd(bn);
4342 * fork failed, fall through to report -- actual error message was
4343 * logged by StartAutoVacWorker
4349 (errcode(ERRCODE_OUT_OF_MEMORY),
4350 errmsg("out of memory")));
4354 * Report the failure to the launcher, if it's running. (If it's not, we
4355 * might not even be connected to shared memory, so don't try to call
4356 * AutoVacWorkerFailed.)
4358 if (AutoVacPID != 0)
4360 AutoVacWorkerFailed();
4361 kill(AutoVacPID, SIGUSR1);
4366 * Create the opts file
4369 CreateOptsFile(int argc, char *argv[], char *fullprogname)
4374 #define OPTS_FILE "postmaster.opts"
4376 if ((fp = fopen(OPTS_FILE, "w")) == NULL)
4378 elog(LOG, "could not create file \"%s\": %m", OPTS_FILE);
4382 fprintf(fp, "%s", fullprogname);
4383 for (i = 1; i < argc; i++)
4384 fprintf(fp, " \"%s\"", argv[i]);
4389 elog(LOG, "could not write file \"%s\": %m", OPTS_FILE);
4398 * MaxLivePostmasterChildren
4400 * This reports the number of entries needed in per-child-process arrays
4401 * (the PMChildFlags array, and if EXEC_BACKEND the ShmemBackendArray).
4402 * These arrays include regular backends and autovac workers, but not special
4403 * children nor dead_end children. This allows the arrays to have a fixed
4404 * maximum size, to wit the same too-many-children limit enforced by
4405 * canAcceptConnections(). The exact value isn't too critical as long as
4406 * it's more than MaxBackends.
4409 MaxLivePostmasterChildren(void)
4411 return 2 * MaxBackends;
4418 * The following need to be available to the save/restore_backend_variables
4421 extern slock_t *ShmemLock;
4422 extern LWLock *LWLockArray;
4423 extern slock_t *ProcStructLock;
4424 extern PROC_HDR *ProcGlobal;
4425 extern PGPROC *AuxiliaryProcs;
4426 extern PMSignalData *PMSignalState;
4427 extern int pgStatSock;
4430 #define write_inheritable_socket(dest, src, childpid) (*(dest) = (src))
4431 #define read_inheritable_socket(dest, src) (*(dest) = *(src))
4433 static void write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE child);
4434 static void write_inheritable_socket(InheritableSocket *dest, SOCKET src,
4436 static void read_inheritable_socket(SOCKET *dest, InheritableSocket *src);
4440 /* Save critical backend variables into the BackendParameters struct */
4443 save_backend_variables(BackendParameters *param, Port *port)
4446 save_backend_variables(BackendParameters *param, Port *port,
4447 HANDLE childProcess, pid_t childPid)
4450 memcpy(¶m->port, port, sizeof(Port));
4451 write_inheritable_socket(¶m->portsocket, port->sock, childPid);
4453 strlcpy(param->DataDir, DataDir, MAXPGPATH);
4455 memcpy(¶m->ListenSocket, &ListenSocket, sizeof(ListenSocket));
4457 param->MyCancelKey = MyCancelKey;
4458 param->MyPMChildSlot = MyPMChildSlot;
4460 param->UsedShmemSegID = UsedShmemSegID;
4461 param->UsedShmemSegAddr = UsedShmemSegAddr;
4463 param->ShmemLock = ShmemLock;
4464 param->ShmemVariableCache = ShmemVariableCache;
4465 param->ShmemBackendArray = ShmemBackendArray;
4467 param->LWLockArray = LWLockArray;
4468 param->ProcStructLock = ProcStructLock;
4469 param->ProcGlobal = ProcGlobal;
4470 param->AuxiliaryProcs = AuxiliaryProcs;
4471 param->PMSignalState = PMSignalState;
4472 write_inheritable_socket(¶m->pgStatSock, pgStatSock, childPid);
4474 param->PostmasterPid = PostmasterPid;
4475 param->PgStartTime = PgStartTime;
4476 param->PgReloadTime = PgReloadTime;
4478 param->redirection_done = redirection_done;
4481 param->PostmasterHandle = PostmasterHandle;
4482 write_duplicated_handle(¶m->initial_signal_pipe,
4483 pgwin32_create_signal_listener(childPid),
4487 memcpy(¶m->syslogPipe, &syslogPipe, sizeof(syslogPipe));
4489 strlcpy(param->my_exec_path, my_exec_path, MAXPGPATH);
4491 strlcpy(param->pkglib_path, pkglib_path, MAXPGPATH);
4493 strlcpy(param->ExtraOptions, ExtraOptions, MAXPGPATH);
4501 * Duplicate a handle for usage in a child process, and write the child
4502 * process instance of the handle to the parameter file.
4505 write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE childProcess)
4507 HANDLE hChild = INVALID_HANDLE_VALUE;
4509 if (!DuplicateHandle(GetCurrentProcess(),
4515 DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS))
4517 (errmsg_internal("could not duplicate handle to be written to backend parameter file: error code %d",
4518 (int) GetLastError())));
4524 * Duplicate a socket for usage in a child process, and write the resulting
4525 * structure to the parameter file.
4526 * This is required because a number of LSPs (Layered Service Providers) very
4527 * common on Windows (antivirus, firewalls, download managers etc) break
4528 * straight socket inheritance.
4531 write_inheritable_socket(InheritableSocket *dest, SOCKET src, pid_t childpid)
4533 dest->origsocket = src;
4534 if (src != 0 && src != -1)
4537 if (WSADuplicateSocket(src, childpid, &dest->wsainfo) != 0)
4539 (errmsg("could not duplicate socket %d for use in backend: error code %d",
4540 src, WSAGetLastError())));
4545 * Read a duplicate socket structure back, and get the socket descriptor.
4548 read_inheritable_socket(SOCKET *dest, InheritableSocket *src)
4552 if (src->origsocket == -1 || src->origsocket == 0)
4554 /* Not a real socket! */
4555 *dest = src->origsocket;
4559 /* Actual socket, so create from structure */
4560 s = WSASocket(FROM_PROTOCOL_INFO,
4566 if (s == INVALID_SOCKET)
4568 write_stderr("could not create inherited socket: error code %d\n",
4575 * To make sure we don't get two references to the same socket, close
4576 * the original one. (This would happen when inheritance actually
4579 closesocket(src->origsocket);
4585 read_backend_variables(char *id, Port *port)
4587 BackendParameters param;
4590 /* Non-win32 implementation reads from file */
4594 fp = AllocateFile(id, PG_BINARY_R);
4597 write_stderr("could not read from backend variables file \"%s\": %s\n",
4598 id, strerror(errno));
4602 if (fread(¶m, sizeof(param), 1, fp) != 1)
4604 write_stderr("could not read from backend variables file \"%s\": %s\n",
4605 id, strerror(errno));
4611 if (unlink(id) != 0)
4613 write_stderr("could not remove file \"%s\": %s\n",
4614 id, strerror(errno));
4618 /* Win32 version uses mapped file */
4620 BackendParameters *paramp;
4622 paramHandle = (HANDLE) atol(id);
4623 paramp = MapViewOfFile(paramHandle, FILE_MAP_READ, 0, 0, 0);
4626 write_stderr("could not map view of backend variables: error code %d\n",
4627 (int) GetLastError());
4631 memcpy(¶m, paramp, sizeof(BackendParameters));
4633 if (!UnmapViewOfFile(paramp))
4635 write_stderr("could not unmap view of backend variables: error code %d\n",
4636 (int) GetLastError());
4640 if (!CloseHandle(paramHandle))
4642 write_stderr("could not close handle to backend parameter variables: error code %d\n",
4643 (int) GetLastError());
4648 restore_backend_variables(¶m, port);
4651 /* Restore critical backend variables from the BackendParameters struct */
4653 restore_backend_variables(BackendParameters *param, Port *port)
4655 memcpy(port, ¶m->port, sizeof(Port));
4656 read_inheritable_socket(&port->sock, ¶m->portsocket);
4658 SetDataDir(param->DataDir);
4660 memcpy(&ListenSocket, ¶m->ListenSocket, sizeof(ListenSocket));
4662 MyCancelKey = param->MyCancelKey;
4663 MyPMChildSlot = param->MyPMChildSlot;
4665 UsedShmemSegID = param->UsedShmemSegID;
4666 UsedShmemSegAddr = param->UsedShmemSegAddr;
4668 ShmemLock = param->ShmemLock;
4669 ShmemVariableCache = param->ShmemVariableCache;
4670 ShmemBackendArray = param->ShmemBackendArray;
4672 LWLockArray = param->LWLockArray;
4673 ProcStructLock = param->ProcStructLock;
4674 ProcGlobal = param->ProcGlobal;
4675 AuxiliaryProcs = param->AuxiliaryProcs;
4676 PMSignalState = param->PMSignalState;
4677 read_inheritable_socket(&pgStatSock, ¶m->pgStatSock);
4679 PostmasterPid = param->PostmasterPid;
4680 PgStartTime = param->PgStartTime;
4681 PgReloadTime = param->PgReloadTime;
4683 redirection_done = param->redirection_done;
4686 PostmasterHandle = param->PostmasterHandle;
4687 pgwin32_initial_signal_pipe = param->initial_signal_pipe;
4690 memcpy(&syslogPipe, ¶m->syslogPipe, sizeof(syslogPipe));
4692 strlcpy(my_exec_path, param->my_exec_path, MAXPGPATH);
4694 strlcpy(pkglib_path, param->pkglib_path, MAXPGPATH);
4696 strlcpy(ExtraOptions, param->ExtraOptions, MAXPGPATH);
4701 ShmemBackendArraySize(void)
4703 return mul_size(MaxLivePostmasterChildren(), sizeof(Backend));
4707 ShmemBackendArrayAllocation(void)
4709 Size size = ShmemBackendArraySize();
4711 ShmemBackendArray = (Backend *) ShmemAlloc(size);
4712 /* Mark all slots as empty */
4713 memset(ShmemBackendArray, 0, size);
4717 ShmemBackendArrayAdd(Backend *bn)
4719 /* The array slot corresponding to my PMChildSlot should be free */
4720 int i = bn->child_slot - 1;
4722 Assert(ShmemBackendArray[i].pid == 0);
4723 ShmemBackendArray[i] = *bn;
4727 ShmemBackendArrayRemove(Backend *bn)
4729 int i = bn->child_slot - 1;
4731 Assert(ShmemBackendArray[i].pid == bn->pid);
4732 /* Mark the slot as empty */
4733 ShmemBackendArray[i].pid = 0;
4735 #endif /* EXEC_BACKEND */
4741 win32_waitpid(int *exitstatus)
4748 * Check if there are any dead children. If there are, return the pid of
4749 * the first one that died.
4751 if (GetQueuedCompletionStatus(win32ChildQueue, &dwd, &key, &ovl, 0))
4753 *exitstatus = (int) key;
4761 * Note! Code below executes on a thread pool! All operations must
4762 * be thread safe! Note that elog() and friends must *not* be used.
4765 pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
4767 win32_deadchild_waitinfo *childinfo = (win32_deadchild_waitinfo *) lpParameter;
4770 if (TimerOrWaitFired)
4771 return; /* timeout. Should never happen, since we use
4772 * INFINITE as timeout value. */
4775 * Remove handle from wait - required even though it's set to wait only
4778 UnregisterWaitEx(childinfo->waitHandle, NULL);
4780 if (!GetExitCodeProcess(childinfo->procHandle, &exitcode))
4783 * Should never happen. Inform user and set a fixed exitcode.
4785 write_stderr("could not read exit code for process\n");
4789 if (!PostQueuedCompletionStatus(win32ChildQueue, childinfo->procId, (ULONG_PTR) exitcode, NULL))
4790 write_stderr("could not post child completion status\n");
4793 * Handle is per-process, so we close it here instead of in the
4794 * originating thread
4796 CloseHandle(childinfo->procHandle);
4799 * Free struct that was allocated before the call to
4800 * RegisterWaitForSingleObject()
4804 /* Queue SIGCHLD signal */
4805 pg_queue_signal(SIGCHLD);