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-2007, 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.514 2007/01/28 03:50:34 momjian 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 "bootstrap/bootstrap.h"
97 #include "catalog/pg_control.h"
98 #include "lib/dllist.h"
99 #include "libpq/auth.h"
100 #include "libpq/ip.h"
101 #include "libpq/libpq.h"
102 #include "libpq/pqsignal.h"
103 #include "miscadmin.h"
105 #include "postmaster/autovacuum.h"
106 #include "postmaster/fork_process.h"
107 #include "postmaster/pgarch.h"
108 #include "postmaster/postmaster.h"
109 #include "postmaster/syslogger.h"
110 #include "storage/fd.h"
111 #include "storage/ipc.h"
112 #include "storage/pg_shmem.h"
113 #include "storage/pmsignal.h"
114 #include "storage/proc.h"
115 #include "tcop/tcopprot.h"
116 #include "utils/builtins.h"
117 #include "utils/datetime.h"
118 #include "utils/memutils.h"
119 #include "utils/ps_status.h"
122 #include "storage/spin.h"
127 * List of active backends (or child processes anyway; we don't actually
128 * know whether a given child has become a backend or is still in the
129 * authorization phase). This is used mainly to keep track of how many
130 * children we have and send them appropriate signals when necessary.
132 * "Special" children such as the startup and bgwriter tasks are not in
137 pid_t pid; /* process id of backend */
138 long cancel_key; /* cancel key for cancels for this backend */
141 static Dllist *BackendList;
145 * Number of entries in the backend table. Twice the number of backends,
146 * plus four other subprocesses (stats, bgwriter, autovac, logger).
148 #define NUM_BACKENDARRAY_ELEMS (2*MaxBackends + 4)
149 static Backend *ShmemBackendArray;
152 /* The socket number we are listening for connections on */
155 char *ListenAddresses;
158 * ReservedBackends is the number of backends reserved for superuser use.
159 * This number is taken out of the pool size given by MaxBackends so
160 * number of backend slots available to non-superusers is
161 * (MaxBackends - ReservedBackends). Note what this really means is
162 * "if there are <= ReservedBackends connections available, only superusers
163 * can make new connections" --- pre-existing superuser connections don't
164 * count against the limit.
166 int ReservedBackends;
168 /* The socket(s) we're listening to. */
170 static int ListenSocket[MAXLISTEN];
173 * Set by the -o option
175 static char ExtraOptions[MAXPGPATH];
178 * These globals control the behavior of the postmaster in case some
179 * backend dumps core. Normally, it kills all peers of the dead backend
180 * and reinitializes shared memory. By specifying -s or -n, we can have
181 * the postmaster stop (rather than kill) peers and not reinitialize
182 * shared data structures.
184 static bool Reinit = true;
185 static int SendStop = false;
187 /* still more option variables */
188 bool EnableSSL = false;
189 bool SilentMode = false; /* silent mode (-S) */
191 int PreAuthDelay = 0;
192 int AuthenticationTimeout = 60;
194 bool log_hostname; /* for ps display and logging */
195 bool Log_connections = false;
196 bool Db_user_namespace = false;
200 /* PIDs of special child processes; 0 when not running */
201 static pid_t StartupPID = 0,
208 /* Startup/shutdown state */
210 #define SmartShutdown 1
211 #define FastShutdown 2
213 static int Shutdown = NoShutdown;
215 static bool FatalError = false; /* T if recovering from backend crash */
217 bool ClientAuthInProgress = false; /* T during new-client
220 static bool force_autovac = false; /* received START_AUTOVAC signal */
223 * State for assigning random salts and cancel keys.
224 * Also, the global MyCancelKey passes the cancel key assigned to a given
225 * backend from the postmaster to that backend (via fork).
227 static unsigned int random_seed = 0;
233 #ifdef HAVE_INT_OPTRESET
238 * postmaster.c - function prototypes
240 static void checkDataDir(void);
243 static void reg_reply(DNSServiceRegistrationReplyErrorType errorCode,
246 static void pmdaemonize(void);
247 static Port *ConnCreate(int serverFd);
248 static void ConnFree(Port *port);
249 static void reset_shared(int port);
250 static void SIGHUP_handler(SIGNAL_ARGS);
251 static void pmdie(SIGNAL_ARGS);
252 static void reaper(SIGNAL_ARGS);
253 static void sigusr1_handler(SIGNAL_ARGS);
254 static void dummy_handler(SIGNAL_ARGS);
255 static void CleanupBackend(int pid, int exitstatus);
256 static void HandleChildCrash(int pid, int exitstatus, const char *procname);
257 static void LogChildExit(int lev, const char *procname,
258 int pid, int exitstatus);
259 static void BackendInitialize(Port *port);
260 static int BackendRun(Port *port);
261 static void ExitPostmaster(int status);
262 static int ServerLoop(void);
263 static int BackendStartup(Port *port);
264 static int ProcessStartupPacket(Port *port, bool SSLdone);
265 static void processCancelRequest(Port *port, void *pkt);
266 static int initMasks(fd_set *rmask);
267 static void report_fork_failure_to_client(Port *port, int errnum);
268 static enum CAC_state canAcceptConnections(void);
269 static long PostmasterRandom(void);
270 static void RandomSalt(char *cryptSalt, char *md5Salt);
271 static void signal_child(pid_t pid, int signal);
272 static void SignalChildren(int signal);
273 static int CountChildren(void);
274 static bool CreateOptsFile(int argc, char *argv[], char *fullprogname);
275 static pid_t StartChildProcess(int xlop);
280 static void win32_AddChild(pid_t pid, HANDLE handle);
281 static void win32_RemoveChild(pid_t pid);
282 static pid_t win32_waitpid(int *exitstatus);
283 static DWORD WINAPI win32_sigchld_waiter(LPVOID param);
285 static pid_t *win32_childPIDArray;
286 static HANDLE *win32_childHNDArray;
287 static unsigned long win32_numChildren = 0;
289 HANDLE PostmasterHandle;
292 static pid_t backend_forkexec(Port *port);
293 static pid_t internal_forkexec(int argc, char *argv[], Port *port);
295 /* Type for a socket that can be inherited to a client process */
299 SOCKET origsocket; /* Original socket value, or -1 if not a
301 WSAPROTOCOL_INFO wsainfo;
304 typedef int InheritableSocket;
307 typedef struct LWLock LWLock; /* ugly kluge */
310 * Structure contains all variables passed to exec:ed backends
315 InheritableSocket portsocket;
316 char DataDir[MAXPGPATH];
317 int ListenSocket[MAXLISTEN];
319 unsigned long UsedShmemSegID;
320 void *UsedShmemSegAddr;
322 VariableCache ShmemVariableCache;
323 Backend *ShmemBackendArray;
325 slock_t *ProcStructLock;
326 PROC_HDR *ProcGlobal;
328 InheritableSocket pgStatSock;
330 TimestampTz PgStartTime;
332 HANDLE PostmasterHandle;
333 HANDLE initial_signal_pipe;
334 HANDLE syslogPipe[2];
338 char my_exec_path[MAXPGPATH];
339 char pkglib_path[MAXPGPATH];
340 char ExtraOptions[MAXPGPATH];
341 char lc_collate[LOCALE_NAME_BUFLEN];
342 char lc_ctype[LOCALE_NAME_BUFLEN];
345 static void read_backend_variables(char *id, Port *port);
346 static void restore_backend_variables(BackendParameters * param, Port *port);
349 static bool save_backend_variables(BackendParameters * param, Port *port);
351 static bool save_backend_variables(BackendParameters * param, Port *port,
352 HANDLE childProcess, pid_t childPid);
355 static void ShmemBackendArrayAdd(Backend *bn);
356 static void ShmemBackendArrayRemove(pid_t pid);
357 #endif /* EXEC_BACKEND */
359 #define StartupDataBase() StartChildProcess(BS_XLOG_STARTUP)
360 #define StartBackgroundWriter() StartChildProcess(BS_XLOG_BGWRITER)
362 /* Macros to check exit status of a child process */
363 #define EXIT_STATUS_0(st) ((st) == 0)
364 #define EXIT_STATUS_1(st) (WIFEXITED(st) && WEXITSTATUS(st) == 1)
368 * Postmaster main entry point
371 PostmasterMain(int argc, char *argv[])
375 char *userDoption = NULL;
378 MyProcPid = PostmasterPid = getpid();
380 IsPostmasterEnvironment = true;
383 * for security, no dir or file created can be group or other accessible
385 umask((mode_t) 0077);
388 * Fire up essential subsystems: memory management
393 * By default, palloc() requests in the postmaster will be allocated in
394 * the PostmasterContext, which is space that can be recycled by backends.
395 * Allocated data that needs to be available to backends should be
396 * allocated in TopMemoryContext.
398 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
400 ALLOCSET_DEFAULT_MINSIZE,
401 ALLOCSET_DEFAULT_INITSIZE,
402 ALLOCSET_DEFAULT_MAXSIZE);
403 MemoryContextSwitchTo(PostmasterContext);
405 if (find_my_exec(argv[0], my_exec_path) < 0)
406 elog(FATAL, "%s: could not locate my own executable path",
409 get_pkglib_path(my_exec_path, pkglib_path);
414 InitializeGUCOptions();
419 * Parse command-line options. CAUTION: keep this in sync with
420 * tcop/postgres.c (the option sets should not conflict)
421 * and with the common help() function in main/main.c.
423 while ((opt = getopt(argc, argv, "A:B:c:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:W:-:")) != -1)
428 SetConfigOption("debug_assertions", optarg, PGC_POSTMASTER, PGC_S_ARGV);
432 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
436 userDoption = optarg;
440 set_debug_options(atoi(optarg), PGC_POSTMASTER, PGC_S_ARGV);
444 SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
448 SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
452 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
456 if (!set_plan_disabling_options(optarg, PGC_POSTMASTER, PGC_S_ARGV))
458 write_stderr("%s: invalid argument for option -f: \"%s\"\n",
465 SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
469 SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
473 /* only used by interactive backend */
477 SetConfigOption("unix_socket_directory", optarg, PGC_POSTMASTER, PGC_S_ARGV);
481 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
485 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
489 /* Don't reinit shared mem after abnormal exit */
494 SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
498 /* Other options to pass to the backend on the command line */
499 snprintf(ExtraOptions + strlen(ExtraOptions),
500 sizeof(ExtraOptions) - strlen(ExtraOptions),
505 SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
509 SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
513 /* only used by single-user backend */
517 SetConfigOption("work_mem", optarg, PGC_POSTMASTER, PGC_S_ARGV);
521 SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
527 * In the event that some backend dumps core, send SIGSTOP,
528 * rather than SIGQUIT, to all its peers. This lets the wily
529 * post_hacker collect core dumps from everyone.
536 const char *tmp = get_stats_option_name(optarg);
540 SetConfigOption(tmp, "true", PGC_POSTMASTER, PGC_S_ARGV);
544 write_stderr("%s: invalid argument for option -t: \"%s\"\n",
552 SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
561 ParseLongOption(optarg, &name, &value);
566 (errcode(ERRCODE_SYNTAX_ERROR),
567 errmsg("--%s requires a value",
571 (errcode(ERRCODE_SYNTAX_ERROR),
572 errmsg("-c %s requires a value",
576 SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
584 write_stderr("Try \"%s --help\" for more information.\n",
591 * Postmaster accepts no non-option switch arguments.
595 write_stderr("%s: invalid argument: \"%s\"\n",
596 progname, argv[optind]);
597 write_stderr("Try \"%s --help\" for more information.\n",
603 /* Locate executable backend before we change working directory */
604 if (find_other_exec(argv[0], "postgres", PG_VERSIONSTR,
605 postgres_exec_path) < 0)
607 (errmsg("%s: could not locate matching postgres executable",
612 * Locate the proper configuration files and data directory, and read
613 * postgresql.conf for the first time.
615 if (!SelectConfigFiles(userDoption, progname))
618 /* Verify that DataDir looks reasonable */
621 /* And switch working directory into it */
625 * Check for invalid combinations of GUC settings.
627 if (NBuffers < 2 * MaxBackends || NBuffers < 16)
630 * Do not accept -B so small that backends are likely to starve for
631 * lack of buffers. The specific choices here are somewhat arbitrary.
633 write_stderr("%s: the number of buffers (-B) must be at least twice the number of allowed connections (-N) and at least 16\n", progname);
637 if (ReservedBackends >= MaxBackends)
639 write_stderr("%s: superuser_reserved_connections must be less than max_connections\n", progname);
644 * Other one-time internal sanity checks can go here, if they are fast.
645 * (Put any slow processing further down, after postmaster.pid creation.)
647 if (!CheckDateTokenTables())
649 write_stderr("%s: invalid datetoken tables, please fix\n", progname);
654 * Now that we are done processing the postmaster arguments, reset
655 * getopt(3) library so that it will work correctly in subprocesses.
658 #ifdef HAVE_INT_OPTRESET
659 optreset = 1; /* some systems need this too */
662 /* For debugging: display postmaster environment */
664 extern char **environ;
668 (errmsg_internal("%s: PostmasterMain: initial environ dump:",
671 (errmsg_internal("-----------------------------------------")));
672 for (p = environ; *p; ++p)
674 (errmsg_internal("\t%s", *p)));
676 (errmsg_internal("-----------------------------------------")));
680 * Fork away from controlling terminal, if -S specified.
682 * Must do this before we grab any interlock files, else the interlocks
683 * will show the wrong PID.
689 * Create lockfile for data directory.
691 * We want to do this before we try to grab the input sockets, because the
692 * data directory interlock is more reliable than the socket-file
693 * interlock (thanks to whoever decided to put socket files in /tmp :-().
694 * For the same reason, it's best to grab the TCP socket(s) before the
697 CreateDataDirLockFile(true);
700 * If timezone is not set, determine what the OS uses. (In theory this
701 * should be done during GUC initialization, but because it can take as
702 * much as several seconds, we delay it until after we've created the
703 * postmaster.pid file. This prevents problems with boot scripts that
704 * expect the pidfile to appear quickly. Also, we avoid problems with
705 * trying to locate the timezone files too early in initialization.)
707 pg_timezone_initialize();
710 * Likewise, init timezone_abbreviations if not already set.
712 pg_timezone_abbrev_initialize();
715 * Initialize SSL library, if specified.
723 * process any libraries that should be preloaded at postmaster start
725 process_shared_preload_libraries();
728 * Remove old temporary files. At this point there can be no other
729 * Postgres processes running in this directory, so this should be safe.
734 * Establish input sockets.
736 for (i = 0; i < MAXLISTEN; i++)
737 ListenSocket[i] = -1;
746 /* Need a modifiable copy of ListenAddresses */
747 rawstring = pstrdup(ListenAddresses);
749 /* Parse string into list of identifiers */
750 if (!SplitIdentifierString(rawstring, ',', &elemlist))
752 /* syntax error in list */
754 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
755 errmsg("invalid list syntax for \"listen_addresses\"")));
760 char *curhost = (char *) lfirst(l);
762 if (strcmp(curhost, "*") == 0)
763 status = StreamServerPort(AF_UNSPEC, NULL,
764 (unsigned short) PostPortNumber,
766 ListenSocket, MAXLISTEN);
768 status = StreamServerPort(AF_UNSPEC, curhost,
769 (unsigned short) PostPortNumber,
771 ListenSocket, MAXLISTEN);
772 if (status == STATUS_OK)
776 (errmsg("could not create listen socket for \"%s\"",
780 if (!success && list_length(elemlist))
782 (errmsg("could not create any TCP/IP sockets")));
789 /* Register for Bonjour only if we opened TCP socket(s) */
790 if (ListenSocket[0] != -1 && bonjour_name != NULL)
792 DNSServiceRegistrationCreate(bonjour_name,
795 htons(PostPortNumber),
797 (DNSServiceRegistrationReply) reg_reply,
802 #ifdef HAVE_UNIX_SOCKETS
803 status = StreamServerPort(AF_UNIX, NULL,
804 (unsigned short) PostPortNumber,
806 ListenSocket, MAXLISTEN);
807 if (status != STATUS_OK)
809 (errmsg("could not create Unix-domain socket")));
813 * check that we have some socket to listen on
815 if (ListenSocket[0] == -1)
817 (errmsg("no socket created for listening")));
820 * Set up shared memory and semaphores.
822 reset_shared(PostPortNumber);
825 * Estimate number of openable files. This must happen after setting up
826 * semaphores, because on some platforms semaphores count as open files.
831 * Load configuration files for client authentication.
837 * Initialize the list of active backends.
839 BackendList = DLNewList();
844 * Initialize the child pid/HANDLE arrays for signal handling.
846 win32_childPIDArray = (pid_t *)
847 malloc(mul_size(NUM_BACKENDARRAY_ELEMS, sizeof(pid_t)));
848 win32_childHNDArray = (HANDLE *)
849 malloc(mul_size(NUM_BACKENDARRAY_ELEMS, sizeof(HANDLE)));
850 if (!win32_childPIDArray || !win32_childHNDArray)
852 (errcode(ERRCODE_OUT_OF_MEMORY),
853 errmsg("out of memory")));
856 * Set up a handle that child processes can use to check whether the
857 * postmaster is still running.
859 if (DuplicateHandle(GetCurrentProcess(),
865 DUPLICATE_SAME_ACCESS) == 0)
867 (errmsg_internal("could not duplicate postmaster handle: error code %d",
868 (int) GetLastError())));
872 * Record postmaster options. We delay this till now to avoid recording
873 * bogus options (eg, NBuffers too high for available memory).
875 if (!CreateOptsFile(argc, argv, my_exec_path))
879 write_nondefault_variables(PGC_POSTMASTER);
883 * Write the external PID file if requested
885 if (external_pid_file)
887 FILE *fpidfile = fopen(external_pid_file, "w");
891 fprintf(fpidfile, "%d\n", MyProcPid);
893 /* Should we remove the pid file on postmaster exit? */
896 write_stderr("%s: could not write external PID file \"%s\": %s\n",
897 progname, external_pid_file, strerror(errno));
901 * Set up signal handlers for the postmaster process.
903 * CAUTION: when changing this list, check for side-effects on the signal
904 * handling setup of child processes. See tcop/postgres.c,
905 * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/autovacuum.c,
906 * postmaster/pgarch.c, postmaster/pgstat.c, and postmaster/syslogger.c.
909 PG_SETMASK(&BlockSig);
911 pqsignal(SIGHUP, SIGHUP_handler); /* reread config file and have
912 * children do same */
913 pqsignal(SIGINT, pmdie); /* send SIGTERM and shut down */
914 pqsignal(SIGQUIT, pmdie); /* send SIGQUIT and die */
915 pqsignal(SIGTERM, pmdie); /* wait for children and shut down */
916 pqsignal(SIGALRM, SIG_IGN); /* ignored */
917 pqsignal(SIGPIPE, SIG_IGN); /* ignored */
918 pqsignal(SIGUSR1, sigusr1_handler); /* message from child process */
919 pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
920 pqsignal(SIGCHLD, reaper); /* handle child termination */
921 pqsignal(SIGTTIN, SIG_IGN); /* ignored */
922 pqsignal(SIGTTOU, SIG_IGN); /* ignored */
923 /* ignore SIGXFSZ, so that ulimit violations work like disk full */
925 pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
929 * If enabled, start up syslogger collection subprocess
931 SysLoggerPID = SysLogger_Start();
934 * Reset whereToSendOutput from DestDebug (its starting state) to
935 * DestNone. This stops ereport from sending log messages to stderr unless
936 * Log_destination permits. We don't do this until the postmaster is
937 * fully launched, since startup failures may as well be reported to
940 whereToSendOutput = DestNone;
943 * Initialize stats collection subsystem (this does NOT start the
944 * collector process!)
949 * Initialize the autovacuum subsystem (again, no process start yet)
954 * Remember postmaster startup time
956 PgStartTime = GetCurrentTimestamp();
959 * We're ready to rock and roll...
961 StartupPID = StartupDataBase();
963 status = ServerLoop();
966 * ServerLoop probably shouldn't ever return, but if it does, close down.
968 ExitPostmaster(status != STATUS_OK);
970 return 0; /* not reached */
975 * Validate the proposed data directory
980 char path[MAXPGPATH];
982 struct stat stat_buf;
986 if (stat(DataDir, &stat_buf) != 0)
990 (errcode_for_file_access(),
991 errmsg("data directory \"%s\" does not exist",
995 (errcode_for_file_access(),
996 errmsg("could not read permissions of directory \"%s\": %m",
1001 * Check that the directory belongs to my userid; if not, reject.
1003 * This check is an essential part of the interlock that prevents two
1004 * postmasters from starting in the same directory (see CreateLockFile()).
1005 * Do not remove or weaken it.
1007 * XXX can we safely enable this check on Windows?
1009 #if !defined(WIN32) && !defined(__CYGWIN__)
1010 if (stat_buf.st_uid != geteuid())
1012 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1013 errmsg("data directory \"%s\" has wrong ownership",
1015 errhint("The server must be started by the user that owns the data directory.")));
1019 * Check if the directory has group or world access. If so, reject.
1021 * It would be possible to allow weaker constraints (for example, allow
1022 * group access) but we cannot make a general assumption that that is
1023 * okay; for example there are platforms where nearly all users
1024 * customarily belong to the same group. Perhaps this test should be
1027 * XXX temporarily suppress check when on Windows, because there may not
1028 * be proper support for Unix-y file permissions. Need to think of a
1029 * reasonable check to apply on Windows.
1031 #if !defined(WIN32) && !defined(__CYGWIN__)
1032 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
1034 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1035 errmsg("data directory \"%s\" has group or world access",
1037 errdetail("Permissions should be u=rwx (0700).")));
1040 /* Look for PG_VERSION before looking for pg_control */
1041 ValidatePgVersion(DataDir);
1043 snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1045 fp = AllocateFile(path, PG_BINARY_R);
1048 write_stderr("%s: could not find the database system\n"
1049 "Expected to find it in the directory \"%s\",\n"
1050 "but could not open file \"%s\": %s\n",
1051 progname, DataDir, path, strerror(errno));
1061 * empty callback function for DNSServiceRegistrationCreate()
1064 reg_reply(DNSServiceRegistrationReplyErrorType errorCode, void *context)
1068 #endif /* USE_BONJOUR */
1072 * Fork away from the controlling terminal (-S option)
1081 pid = fork_process();
1082 if (pid == (pid_t) -1)
1084 write_stderr("%s: could not fork background process: %s\n",
1085 progname, strerror(errno));
1090 /* Parent should just exit, without doing any atexit cleanup */
1094 MyProcPid = PostmasterPid = getpid(); /* reset PID vars to child */
1096 /* GH: If there's no setsid(), we hopefully don't need silent mode.
1097 * Until there's a better solution.
1102 write_stderr("%s: could not dissociate from controlling TTY: %s\n",
1103 progname, strerror(errno));
1107 i = open(NULL_DEV, O_RDWR, 0);
1114 elog(FATAL, "SilentMode not supported under WIN32");
1120 * Main idle loop of postmaster
1129 struct timeval earlier,
1132 gettimeofday(&earlier, NULL);
1133 last_touch_time = time(NULL);
1135 nSockets = initMasks(&readmask);
1141 struct timeval timeout;
1146 * Wait for something to happen.
1148 * We wait at most one minute, or the minimum autovacuum delay, to
1149 * ensure that the other background tasks handled below get done even
1150 * when no requests are arriving.
1152 memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
1154 timeout.tv_sec = Min(60, autovacuum_naptime);
1155 timeout.tv_usec = 0;
1157 PG_SETMASK(&UnBlockSig);
1159 selres = select(nSockets, &rmask, NULL, NULL, &timeout);
1162 * Block all signals until we wait again. (This makes it safe for our
1163 * signal handlers to do nontrivial work.)
1165 PG_SETMASK(&BlockSig);
1169 if (errno != EINTR && errno != EWOULDBLOCK)
1172 (errcode_for_socket_access(),
1173 errmsg("select() failed in postmaster: %m")));
1174 return STATUS_ERROR;
1179 * New connection pending on any of our sockets? If so, fork a child
1180 * process to deal with it.
1185 * Select a random seed at the time of first receiving a request.
1187 while (random_seed == 0)
1189 gettimeofday(&later, NULL);
1192 * We are not sure how much precision is in tv_usec, so we
1193 * swap the high and low 16 bits of 'later' and XOR them with
1194 * 'earlier'. On the off chance that the result is 0, we loop
1197 random_seed = earlier.tv_usec ^
1198 ((later.tv_usec << 16) |
1199 ((later.tv_usec >> 16) & 0xffff));
1202 for (i = 0; i < MAXLISTEN; i++)
1204 if (ListenSocket[i] == -1)
1206 if (FD_ISSET(ListenSocket[i], &rmask))
1208 port = ConnCreate(ListenSocket[i]);
1211 BackendStartup(port);
1214 * We no longer need the open socket or port structure
1217 StreamClose(port->sock);
1224 /* If we have lost the system logger, try to start a new one */
1225 if (SysLoggerPID == 0 && Redirect_stderr)
1226 SysLoggerPID = SysLogger_Start();
1229 * If no background writer process is running, and we are not in a
1230 * state that prevents it, start one. It doesn't matter if this
1231 * fails, we'll just try again later.
1233 if (BgWriterPID == 0 && StartupPID == 0 && !FatalError)
1235 BgWriterPID = StartBackgroundWriter();
1236 /* If shutdown is pending, set it going */
1237 if (Shutdown > NoShutdown && BgWriterPID != 0)
1238 signal_child(BgWriterPID, SIGUSR2);
1242 * Start a new autovacuum process, if there isn't one running already.
1243 * (It'll die relatively quickly.) We check that it's not started too
1244 * frequently in autovac_start.
1246 if ((AutoVacuumingActive() || force_autovac) && AutoVacPID == 0 &&
1247 StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
1249 AutoVacPID = autovac_start();
1250 if (AutoVacPID != 0)
1251 force_autovac = false; /* signal successfully processed */
1254 /* If we have lost the archiver, try to start a new one */
1255 if (XLogArchivingActive() && PgArchPID == 0 &&
1256 StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
1257 PgArchPID = pgarch_start();
1259 /* If we have lost the stats collector, try to start a new one */
1260 if (PgStatPID == 0 &&
1261 StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
1262 PgStatPID = pgstat_start();
1265 * Touch the socket and lock file every 58 minutes, to ensure that
1266 * they are not removed by overzealous /tmp-cleaning tasks. We assume
1267 * no one runs cleaners with cutoff times of less than an hour ...
1270 if (now - last_touch_time >= 58 * SECS_PER_MINUTE)
1273 TouchSocketLockFile();
1274 last_touch_time = now;
1281 * Initialise the masks for select() for the ports we are listening on.
1282 * Return the number of sockets to listen on.
1285 initMasks(fd_set *rmask)
1292 for (i = 0; i < MAXLISTEN; i++)
1294 int fd = ListenSocket[i];
1308 * Read the startup packet and do something according to it.
1310 * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
1311 * not return at all.
1313 * (Note that ereport(FATAL) stuff is sent to the client, so only use it
1314 * if that's what you want. Return STATUS_ERROR if you don't want to
1315 * send anything to the client, which would typically be appropriate
1316 * if we detect a communications failure.)
1319 ProcessStartupPacket(Port *port, bool SSLdone)
1323 ProtocolVersion proto;
1324 MemoryContext oldcontext;
1326 if (pq_getbytes((char *) &len, 4) == EOF)
1329 * EOF after SSLdone probably means the client didn't like our
1330 * response to NEGOTIATE_SSL_CODE. That's not an error condition, so
1331 * don't clutter the log with a complaint.
1335 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1336 errmsg("incomplete startup packet")));
1337 return STATUS_ERROR;
1343 if (len < (int32) sizeof(ProtocolVersion) ||
1344 len > MAX_STARTUP_PACKET_LENGTH)
1347 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1348 errmsg("invalid length of startup packet")));
1349 return STATUS_ERROR;
1353 * Allocate at least the size of an old-style startup packet, plus one
1354 * extra byte, and make sure all are zeroes. This ensures we will have
1355 * null termination of all strings, in both fixed- and variable-length
1358 if (len <= (int32) sizeof(StartupPacket))
1359 buf = palloc0(sizeof(StartupPacket) + 1);
1361 buf = palloc0(len + 1);
1363 if (pq_getbytes(buf, len) == EOF)
1366 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1367 errmsg("incomplete startup packet")));
1368 return STATUS_ERROR;
1372 * The first field is either a protocol version number or a special
1375 port->proto = proto = ntohl(*((ProtocolVersion *) buf));
1377 if (proto == CANCEL_REQUEST_CODE)
1379 processCancelRequest(port, buf);
1380 return 127; /* XXX */
1383 if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
1388 /* No SSL when disabled or on Unix sockets */
1389 if (!EnableSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
1392 SSLok = 'S'; /* Support for SSL */
1394 SSLok = 'N'; /* No support for SSL */
1398 if (send(port->sock, &SSLok, 1, 0) != 1)
1401 goto retry1; /* if interrupted, just retry */
1403 (errcode_for_socket_access(),
1404 errmsg("failed to send SSL negotiation response: %m")));
1405 return STATUS_ERROR; /* close the connection */
1409 if (SSLok == 'S' && secure_open_server(port) == -1)
1410 return STATUS_ERROR;
1412 /* regular startup packet, cancel, etc packet should follow... */
1413 /* but not another SSL negotiation request */
1414 return ProcessStartupPacket(port, true);
1417 /* Could add additional special packet types here */
1420 * Set FrontendProtocol now so that ereport() knows what format to send if
1421 * we fail during startup.
1423 FrontendProtocol = proto;
1425 /* Check we can handle the protocol the frontend is using. */
1427 if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
1428 PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
1429 (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
1430 PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
1432 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1433 errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
1434 PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
1435 PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST),
1436 PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST),
1437 PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))));
1440 * Now fetch parameters out of startup packet and save them into the Port
1441 * structure. All data structures attached to the Port struct must be
1442 * allocated in TopMemoryContext so that they won't disappear when we pass
1443 * them to PostgresMain (see BackendRun). We need not worry about leaking
1444 * this storage on failure, since we aren't in the postmaster process
1447 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1449 if (PG_PROTOCOL_MAJOR(proto) >= 3)
1451 int32 offset = sizeof(ProtocolVersion);
1454 * Scan packet body for name/option pairs. We can assume any string
1455 * beginning within the packet body is null-terminated, thanks to
1456 * zeroing extra byte above.
1458 port->guc_options = NIL;
1460 while (offset < len)
1462 char *nameptr = ((char *) buf) + offset;
1466 if (*nameptr == '\0')
1467 break; /* found packet terminator */
1468 valoffset = offset + strlen(nameptr) + 1;
1469 if (valoffset >= len)
1470 break; /* missing value, will complain below */
1471 valptr = ((char *) buf) + valoffset;
1473 if (strcmp(nameptr, "database") == 0)
1474 port->database_name = pstrdup(valptr);
1475 else if (strcmp(nameptr, "user") == 0)
1476 port->user_name = pstrdup(valptr);
1477 else if (strcmp(nameptr, "options") == 0)
1478 port->cmdline_options = pstrdup(valptr);
1481 /* Assume it's a generic GUC option */
1482 port->guc_options = lappend(port->guc_options,
1484 port->guc_options = lappend(port->guc_options,
1487 offset = valoffset + strlen(valptr) + 1;
1491 * If we didn't find a packet terminator exactly at the end of the
1492 * given packet length, complain.
1494 if (offset != len - 1)
1496 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1497 errmsg("invalid startup packet layout: expected terminator as last byte")));
1502 * Get the parameters from the old-style, fixed-width-fields startup
1503 * packet as C strings. The packet destination was cleared first so a
1504 * short packet has zeros silently added. We have to be prepared to
1505 * truncate the pstrdup result for oversize fields, though.
1507 StartupPacket *packet = (StartupPacket *) buf;
1509 port->database_name = pstrdup(packet->database);
1510 if (strlen(port->database_name) > sizeof(packet->database))
1511 port->database_name[sizeof(packet->database)] = '\0';
1512 port->user_name = pstrdup(packet->user);
1513 if (strlen(port->user_name) > sizeof(packet->user))
1514 port->user_name[sizeof(packet->user)] = '\0';
1515 port->cmdline_options = pstrdup(packet->options);
1516 if (strlen(port->cmdline_options) > sizeof(packet->options))
1517 port->cmdline_options[sizeof(packet->options)] = '\0';
1518 port->guc_options = NIL;
1521 /* Check a user name was given. */
1522 if (port->user_name == NULL || port->user_name[0] == '\0')
1524 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1525 errmsg("no PostgreSQL user name specified in startup packet")));
1527 /* The database defaults to the user name. */
1528 if (port->database_name == NULL || port->database_name[0] == '\0')
1529 port->database_name = pstrdup(port->user_name);
1531 if (Db_user_namespace)
1534 * If user@, it is a global user, remove '@'. We only want to do this
1535 * if there is an '@' at the end and no earlier in the user string or
1536 * they may fake as a local user of another database attaching to this
1539 if (strchr(port->user_name, '@') ==
1540 port->user_name + strlen(port->user_name) - 1)
1541 *strchr(port->user_name, '@') = '\0';
1544 /* Append '@' and dbname */
1547 db_user = palloc(strlen(port->user_name) +
1548 strlen(port->database_name) + 2);
1549 sprintf(db_user, "%s@%s", port->user_name, port->database_name);
1550 port->user_name = db_user;
1555 * Truncate given database and user names to length of a Postgres name.
1556 * This avoids lookup failures when overlength names are given.
1558 if (strlen(port->database_name) >= NAMEDATALEN)
1559 port->database_name[NAMEDATALEN - 1] = '\0';
1560 if (strlen(port->user_name) >= NAMEDATALEN)
1561 port->user_name[NAMEDATALEN - 1] = '\0';
1564 * Done putting stuff in TopMemoryContext.
1566 MemoryContextSwitchTo(oldcontext);
1569 * If we're going to reject the connection due to database state, say so
1570 * now instead of wasting cycles on an authentication exchange. (This also
1571 * allows a pg_ping utility to be written.)
1573 switch (port->canAcceptConnections)
1577 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1578 errmsg("the database system is starting up")));
1582 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1583 errmsg("the database system is shutting down")));
1587 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1588 errmsg("the database system is in recovery mode")));
1592 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
1593 errmsg("sorry, too many clients already")));
1605 * The client has sent a cancel request packet, not a normal
1606 * start-a-new-connection packet. Perform the necessary processing.
1607 * Nothing is sent back to the client.
1610 processCancelRequest(Port *port, void *pkt)
1612 CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
1614 long cancelAuthCode;
1617 #ifndef EXEC_BACKEND
1623 backendPID = (int) ntohl(canc->backendPID);
1624 cancelAuthCode = (long) ntohl(canc->cancelAuthCode);
1627 * See if we have a matching backend. In the EXEC_BACKEND case, we can no
1628 * longer access the postmaster's own backend list, and must rely on the
1629 * duplicate array in shared memory.
1631 #ifndef EXEC_BACKEND
1632 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
1634 bp = (Backend *) DLE_VAL(curr);
1636 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
1638 bp = (Backend *) &ShmemBackendArray[i];
1640 if (bp->pid == backendPID)
1642 if (bp->cancel_key == cancelAuthCode)
1644 /* Found a match; signal that backend to cancel current op */
1646 (errmsg_internal("processing cancel request: sending SIGINT to process %d",
1648 signal_child(bp->pid, SIGINT);
1651 /* Right PID, wrong key: no way, Jose */
1653 (errmsg_internal("bad key in cancel request for process %d",
1659 /* No matching backend */
1661 (errmsg_internal("bad pid in cancel request for process %d",
1666 * canAcceptConnections --- check to see if database state allows connections.
1668 static enum CAC_state
1669 canAcceptConnections(void)
1671 /* Can't start backends when in startup/shutdown/recovery state. */
1672 if (Shutdown > NoShutdown)
1673 return CAC_SHUTDOWN;
1677 return CAC_RECOVERY;
1680 * Don't start too many children.
1682 * We allow more connections than we can have backends here because some
1683 * might still be authenticating; they might fail auth, or some existing
1684 * backend might exit before the auth cycle is completed. The exact
1685 * MaxBackends limit is enforced when a new backend tries to join the
1686 * shared-inval backend array.
1688 if (CountChildren() >= 2 * MaxBackends)
1696 * ConnCreate -- create a local connection data structure
1699 ConnCreate(int serverFd)
1703 if (!(port = (Port *) calloc(1, sizeof(Port))))
1706 (errcode(ERRCODE_OUT_OF_MEMORY),
1707 errmsg("out of memory")));
1711 if (StreamConnection(serverFd, port) != STATUS_OK)
1713 StreamClose(port->sock);
1720 * Precompute password salt values to use for this connection. It's
1721 * slightly annoying to do this long in advance of knowing whether
1722 * we'll need 'em or not, but we must do the random() calls before we
1723 * fork, not after. Else the postmaster's random sequence won't get
1724 * advanced, and all backends would end up using the same salt...
1726 RandomSalt(port->cryptSalt, port->md5Salt);
1734 * ConnFree -- free a local connection data structure
1737 ConnFree(Port *conn)
1747 * ClosePostmasterPorts -- close all the postmaster's open sockets
1749 * This is called during child process startup to release file descriptors
1750 * that are not needed by that child process. The postmaster still has
1751 * them open, of course.
1753 * Note: we pass am_syslogger as a boolean because we don't want to set
1754 * the global variable yet when this is called.
1757 ClosePostmasterPorts(bool am_syslogger)
1761 /* Close the listen sockets */
1762 for (i = 0; i < MAXLISTEN; i++)
1764 if (ListenSocket[i] != -1)
1766 StreamClose(ListenSocket[i]);
1767 ListenSocket[i] = -1;
1771 /* If using syslogger, close the read side of the pipe */
1775 if (syslogPipe[0] >= 0)
1776 close(syslogPipe[0]);
1780 CloseHandle(syslogPipe[0]);
1788 * reset_shared -- reset shared memory and semaphores
1791 reset_shared(int port)
1794 * Create or re-create shared memory and semaphores.
1796 * Note: in each "cycle of life" we will normally assign the same IPC keys
1797 * (if using SysV shmem and/or semas), since the port number is used to
1798 * determine IPC keys. This helps ensure that we will clean up dead IPC
1799 * objects if the postmaster crashes and is restarted.
1801 CreateSharedMemoryAndSemaphores(false, port);
1806 * SIGHUP -- reread config files, and tell children to do same
1809 SIGHUP_handler(SIGNAL_ARGS)
1811 int save_errno = errno;
1813 PG_SETMASK(&BlockSig);
1815 if (Shutdown <= SmartShutdown)
1818 (errmsg("received SIGHUP, reloading configuration files")));
1819 ProcessConfigFile(PGC_SIGHUP);
1820 SignalChildren(SIGHUP);
1821 if (BgWriterPID != 0)
1822 signal_child(BgWriterPID, SIGHUP);
1823 if (AutoVacPID != 0)
1824 signal_child(AutoVacPID, SIGHUP);
1826 signal_child(PgArchPID, SIGHUP);
1827 if (SysLoggerPID != 0)
1828 signal_child(SysLoggerPID, SIGHUP);
1829 /* PgStatPID does not currently need SIGHUP */
1831 /* Reload authentication config files too */
1836 /* Update the starting-point file for future children */
1837 write_nondefault_variables(PGC_SIGHUP);
1841 PG_SETMASK(&UnBlockSig);
1848 * pmdie -- signal handler for processing various postmaster signals.
1853 int save_errno = errno;
1855 PG_SETMASK(&BlockSig);
1858 (errmsg_internal("postmaster received signal %d",
1859 postgres_signal_arg)));
1861 switch (postgres_signal_arg)
1868 * Wait for children to end their work, then shut down.
1870 if (Shutdown >= SmartShutdown)
1872 Shutdown = SmartShutdown;
1874 (errmsg("received smart shutdown request")));
1877 * We won't wait out an autovacuum iteration ...
1879 if (AutoVacPID != 0)
1881 /* Use statement cancel to shut it down */
1882 signal_child(AutoVacPID, SIGINT);
1883 break; /* let reaper() handle this */
1886 if (DLGetHead(BackendList))
1887 break; /* let reaper() handle this */
1890 * No children left. Begin shutdown of data base system.
1892 if (StartupPID != 0 || FatalError)
1893 break; /* let reaper() handle this */
1894 /* Start the bgwriter if not running */
1895 if (BgWriterPID == 0)
1896 BgWriterPID = StartBackgroundWriter();
1897 /* And tell it to shut down */
1898 if (BgWriterPID != 0)
1899 signal_child(BgWriterPID, SIGUSR2);
1900 /* Tell pgarch to shut down too; nothing left for it to do */
1902 signal_child(PgArchPID, SIGQUIT);
1903 /* Tell pgstat to shut down too; nothing left for it to do */
1905 signal_child(PgStatPID, SIGQUIT);
1913 * Abort all children with SIGTERM (rollback active transactions
1914 * and exit) and shut down when they are gone.
1916 if (Shutdown >= FastShutdown)
1918 Shutdown = FastShutdown;
1920 (errmsg("received fast shutdown request")));
1922 if (DLGetHead(BackendList) || AutoVacPID != 0)
1927 (errmsg("aborting any active transactions")));
1928 SignalChildren(SIGTERM);
1929 if (AutoVacPID != 0)
1930 signal_child(AutoVacPID, SIGTERM);
1931 /* reaper() does the rest */
1937 * No children left. Begin shutdown of data base system.
1939 * Note: if we previously got SIGTERM then we may send SIGUSR2 to
1940 * the bgwriter a second time here. This should be harmless.
1942 if (StartupPID != 0)
1944 signal_child(StartupPID, SIGTERM);
1945 break; /* let reaper() do the rest */
1948 break; /* let reaper() handle this case */
1949 /* Start the bgwriter if not running */
1950 if (BgWriterPID == 0)
1951 BgWriterPID = StartBackgroundWriter();
1952 /* And tell it to shut down */
1953 if (BgWriterPID != 0)
1954 signal_child(BgWriterPID, SIGUSR2);
1955 /* Tell pgarch to shut down too; nothing left for it to do */
1957 signal_child(PgArchPID, SIGQUIT);
1958 /* Tell pgstat to shut down too; nothing left for it to do */
1960 signal_child(PgStatPID, SIGQUIT);
1966 * Immediate Shutdown:
1968 * abort all children with SIGQUIT and exit without attempt to
1969 * properly shut down data base system.
1972 (errmsg("received immediate shutdown request")));
1973 if (StartupPID != 0)
1974 signal_child(StartupPID, SIGQUIT);
1975 if (BgWriterPID != 0)
1976 signal_child(BgWriterPID, SIGQUIT);
1977 if (AutoVacPID != 0)
1978 signal_child(AutoVacPID, SIGQUIT);
1980 signal_child(PgArchPID, SIGQUIT);
1982 signal_child(PgStatPID, SIGQUIT);
1983 if (DLGetHead(BackendList))
1984 SignalChildren(SIGQUIT);
1989 PG_SETMASK(&UnBlockSig);
1995 * Reaper -- signal handler to cleanup after a backend (child) dies.
2000 int save_errno = errno;
2003 int status; /* backend exit status */
2006 union wait status; /* backend exit status */
2010 int pid; /* process id of dead backend */
2012 PG_SETMASK(&BlockSig);
2015 (errmsg_internal("reaping dead processes")));
2017 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
2019 exitstatus = status;
2022 while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
2024 exitstatus = status.w_status;
2026 while ((pid = win32_waitpid(&exitstatus)) > 0)
2029 * We need to do this here, and not in CleanupBackend, since this is
2030 * to be called on all children when we are done with them. Could move
2031 * to LogChildExit, but that seems like asking for future trouble...
2033 win32_RemoveChild(pid);
2035 #endif /* HAVE_WAITPID */
2038 * Check if this child was a startup process.
2040 if (StartupPID != 0 && pid == StartupPID)
2043 /* Note: FATAL exit of startup is treated as catastrophic */
2044 if (!EXIT_STATUS_0(exitstatus))
2046 LogChildExit(LOG, _("startup process"),
2049 (errmsg("aborting startup due to startup process failure")));
2054 * Startup succeeded - we are done with system startup or
2060 * Load the flat authorization file into postmaster's cache. The
2061 * startup process has recomputed this from the database contents,
2062 * so we wait till it finishes before loading it.
2067 * Crank up the background writer. It doesn't matter if this
2068 * fails, we'll just try again later.
2070 Assert(BgWriterPID == 0);
2071 BgWriterPID = StartBackgroundWriter();
2074 * Go to shutdown mode if a shutdown request was pending.
2075 * Otherwise, try to start the archiver and stats collector too.
2076 * (We could, but don't, try to start autovacuum here.)
2078 if (Shutdown > NoShutdown && BgWriterPID != 0)
2079 signal_child(BgWriterPID, SIGUSR2);
2080 else if (Shutdown == NoShutdown)
2082 if (XLogArchivingActive() && PgArchPID == 0)
2083 PgArchPID = pgarch_start();
2085 PgStatPID = pgstat_start();
2092 * Was it the bgwriter?
2094 if (BgWriterPID != 0 && pid == BgWriterPID)
2097 if (EXIT_STATUS_0(exitstatus) &&
2098 Shutdown > NoShutdown && !FatalError &&
2099 !DLGetHead(BackendList) && AutoVacPID == 0)
2102 * Normal postmaster exit is here: we've seen normal exit of
2103 * the bgwriter after it's been told to shut down. We expect
2104 * that it wrote a shutdown checkpoint. (If for some reason
2105 * it didn't, recovery will occur on next postmaster start.)
2107 * Note: we do not wait around for exit of the archiver or
2108 * stats processes. They've been sent SIGQUIT by this point,
2109 * and in any case contain logic to commit hara-kiri if they
2110 * notice the postmaster is gone.
2116 * Any unexpected exit of the bgwriter (including FATAL exit)
2117 * is treated as a crash.
2119 HandleChildCrash(pid, exitstatus,
2120 _("background writer process"));
2123 * If the bgwriter crashed while trying to write the shutdown
2124 * checkpoint, we may as well just stop here; any recovery
2125 * required will happen on next postmaster start.
2127 if (Shutdown > NoShutdown &&
2128 !DLGetHead(BackendList) && AutoVacPID == 0)
2131 (errmsg("abnormal database system shutdown")));
2135 /* Else, proceed as in normal crash recovery */
2140 * Was it the autovacuum process? Normal or FATAL exit can be
2141 * ignored; we'll start a new one at the next iteration of the
2142 * postmaster's main loop, if necessary. Any other exit condition
2143 * is treated as a crash.
2145 if (AutoVacPID != 0 && pid == AutoVacPID)
2149 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2150 HandleChildCrash(pid, exitstatus,
2151 _("autovacuum process"));
2156 * Was it the archiver? If so, just try to start a new one; no need
2157 * to force reset of the rest of the system. (If fail, we'll try
2158 * again in future cycles of the main loop.)
2160 if (PgArchPID != 0 && pid == PgArchPID)
2163 if (!EXIT_STATUS_0(exitstatus))
2164 LogChildExit(LOG, _("archiver process"),
2166 if (XLogArchivingActive() &&
2167 StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
2168 PgArchPID = pgarch_start();
2173 * Was it the statistics collector? If so, just try to start a new
2174 * one; no need to force reset of the rest of the system. (If fail,
2175 * we'll try again in future cycles of the main loop.)
2177 if (PgStatPID != 0 && pid == PgStatPID)
2180 if (!EXIT_STATUS_0(exitstatus))
2181 LogChildExit(LOG, _("statistics collector process"),
2183 if (StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
2184 PgStatPID = pgstat_start();
2188 /* Was it the system logger? try to start a new one */
2189 if (SysLoggerPID != 0 && pid == SysLoggerPID)
2192 /* for safety's sake, launch new logger *first* */
2193 SysLoggerPID = SysLogger_Start();
2194 if (!EXIT_STATUS_0(exitstatus))
2195 LogChildExit(LOG, _("system logger process"),
2201 * Else do standard backend child cleanup.
2203 CleanupBackend(pid, exitstatus);
2204 } /* loop over pending child-death reports */
2209 * Wait for all important children to exit, then reset shmem and
2210 * StartupDataBase. (We can ignore the archiver and stats processes
2211 * here since they are not connected to shmem.)
2213 if (DLGetHead(BackendList) || StartupPID != 0 || BgWriterPID != 0 ||
2217 (errmsg("all server processes terminated; reinitializing")));
2220 reset_shared(PostPortNumber);
2222 StartupPID = StartupDataBase();
2227 if (Shutdown > NoShutdown)
2229 if (DLGetHead(BackendList) || StartupPID != 0 || AutoVacPID != 0)
2231 /* Start the bgwriter if not running */
2232 if (BgWriterPID == 0)
2233 BgWriterPID = StartBackgroundWriter();
2234 /* And tell it to shut down */
2235 if (BgWriterPID != 0)
2236 signal_child(BgWriterPID, SIGUSR2);
2237 /* Tell pgarch to shut down too; nothing left for it to do */
2239 signal_child(PgArchPID, SIGQUIT);
2240 /* Tell pgstat to shut down too; nothing left for it to do */
2242 signal_child(PgStatPID, SIGQUIT);
2246 PG_SETMASK(&UnBlockSig);
2253 * CleanupBackend -- cleanup after terminated backend.
2255 * Remove all local state associated with backend.
2258 CleanupBackend(int pid,
2259 int exitstatus) /* child's exit status. */
2263 LogChildExit(DEBUG2, _("server process"), pid, exitstatus);
2266 * If a backend dies in an ugly way then we must signal all other backends
2267 * to quickdie. If exit status is zero (normal) or one (FATAL exit), we
2268 * assume everything is all right and simply remove the backend from the
2269 * active backend list.
2271 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2273 HandleChildCrash(pid, exitstatus, _("server process"));
2277 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2279 Backend *bp = (Backend *) DLE_VAL(curr);
2287 ShmemBackendArrayRemove(pid);
2295 * HandleChildCrash -- cleanup after failed backend, bgwriter, or autovacuum.
2297 * The objectives here are to clean up our local state about the child
2298 * process, and to signal all other remaining children to quickdie.
2301 HandleChildCrash(int pid, int exitstatus, const char *procname)
2308 * Make log entry unless there was a previous crash (if so, nonzero exit
2309 * status is to be expected in SIGQUIT response; don't clutter log)
2313 LogChildExit(LOG, procname, pid, exitstatus);
2315 (errmsg("terminating any other active server processes")));
2318 /* Process regular backends */
2319 for (curr = DLGetHead(BackendList); curr; curr = next)
2321 next = DLGetSucc(curr);
2322 bp = (Backend *) DLE_VAL(curr);
2326 * Found entry for freshly-dead backend, so remove it.
2332 ShmemBackendArrayRemove(pid);
2334 /* Keep looping so we can signal remaining backends */
2339 * This backend is still alive. Unless we did so already, tell it
2340 * to commit hara-kiri.
2342 * SIGQUIT is the special signal that says exit without proc_exit
2343 * and let the user know what's going on. But if SendStop is set
2344 * (-s on command line), then we send SIGSTOP instead, so that we
2345 * can get core dumps from all backends by hand.
2350 (errmsg_internal("sending %s to process %d",
2351 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2353 signal_child(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
2358 /* Take care of the bgwriter too */
2359 if (pid == BgWriterPID)
2361 else if (BgWriterPID != 0 && !FatalError)
2364 (errmsg_internal("sending %s to process %d",
2365 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2366 (int) BgWriterPID)));
2367 signal_child(BgWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
2370 /* Take care of the autovacuum daemon too */
2371 if (pid == AutoVacPID)
2373 else if (AutoVacPID != 0 && !FatalError)
2376 (errmsg_internal("sending %s to process %d",
2377 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2378 (int) AutoVacPID)));
2379 signal_child(AutoVacPID, (SendStop ? SIGSTOP : SIGQUIT));
2382 /* Force a power-cycle of the pgarch process too */
2383 /* (Shouldn't be necessary, but just for luck) */
2384 if (PgArchPID != 0 && !FatalError)
2387 (errmsg_internal("sending %s to process %d",
2390 signal_child(PgArchPID, SIGQUIT);
2393 /* Force a power-cycle of the pgstat process too */
2394 /* (Shouldn't be necessary, but just for luck) */
2395 if (PgStatPID != 0 && !FatalError)
2398 (errmsg_internal("sending %s to process %d",
2401 signal_child(PgStatPID, SIGQUIT);
2404 /* We do NOT restart the syslogger */
2410 * Log the death of a child process.
2413 LogChildExit(int lev, const char *procname, int pid, int exitstatus)
2415 if (WIFEXITED(exitstatus))
2419 translator: %s is a noun phrase describing a child process, such as
2421 (errmsg("%s (PID %d) exited with exit code %d",
2422 procname, pid, WEXITSTATUS(exitstatus))));
2423 else if (WIFSIGNALED(exitstatus))
2428 translator: %s is a noun phrase describing a child process, such as
2430 (errmsg("%s (PID %d) was terminated by exception %X",
2431 procname, pid, WTERMSIG(exitstatus)),
2432 errhint("See C include file \"ntstatus.h\" for a description of the hex value.")));
2433 #elif defined(HAVE_DECL_SYS_SIGLIST)
2437 translator: %s is a noun phrase describing a child process, such as
2439 (errmsg("%s (PID %d) was terminated by signal: %s (%d)",
2440 procname, pid, WTERMSIG(exitstatus) < NSIG ?
2441 sys_siglist[WTERMSIG(exitstatus)] : "unknown signal",
2442 WTERMSIG(exitstatus))));
2447 translator: %s is a noun phrase describing a child process, such as
2449 (errmsg("%s (PID %d) was terminated by signal %d",
2450 procname, pid, WTERMSIG(exitstatus))));
2456 translator: %s is a noun phrase describing a child process, such as
2458 (errmsg("%s (PID %d) exited with unexpected status %d",
2459 procname, pid, exitstatus)));
2463 * Send a signal to a postmaster child process
2465 * On systems that have setsid(), each child process sets itself up as a
2466 * process group leader. For signals that are generally interpreted in the
2467 * appropriate fashion, we signal the entire process group not just the
2468 * direct child process. This allows us to, for example, SIGQUIT a blocked
2469 * archive_recovery script, or SIGINT a script being run by a backend via
2472 * There is a race condition for recently-forked children: they might not
2473 * have executed setsid() yet. So we signal the child directly as well as
2474 * the group. We assume such a child will handle the signal before trying
2475 * to spawn any grandchild processes. We also assume that signaling the
2476 * child twice will not cause any problems.
2479 signal_child(pid_t pid, int signal)
2481 if (kill(pid, signal) < 0)
2482 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
2490 if (kill(-pid, signal) < 0)
2491 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) (-pid), signal);
2500 * Send a signal to all backend children (but NOT special children)
2503 SignalChildren(int signal)
2507 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2509 Backend *bp = (Backend *) DLE_VAL(curr);
2512 (errmsg_internal("sending signal %d to process %d",
2513 signal, (int) bp->pid)));
2514 signal_child(bp->pid, signal);
2519 * BackendStartup -- start backend process
2521 * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
2524 BackendStartup(Port *port)
2526 Backend *bn; /* for backend cleanup */
2530 * Compute the cancel key that will be assigned to this backend. The
2531 * backend will have its own copy in the forked-off process' value of
2532 * MyCancelKey, so that it can transmit the key to the frontend.
2534 MyCancelKey = PostmasterRandom();
2537 * Make room for backend data structure. Better before the fork() so we
2538 * can handle failure cleanly.
2540 bn = (Backend *) malloc(sizeof(Backend));
2544 (errcode(ERRCODE_OUT_OF_MEMORY),
2545 errmsg("out of memory")));
2546 return STATUS_ERROR;
2549 /* Pass down canAcceptConnections state (kluge for EXEC_BACKEND case) */
2550 port->canAcceptConnections = canAcceptConnections();
2553 pid = backend_forkexec(port);
2554 #else /* !EXEC_BACKEND */
2555 pid = fork_process();
2556 if (pid == 0) /* child */
2561 * Let's clean up ourselves as the postmaster child, and close the
2562 * postmaster's listen sockets. (In EXEC_BACKEND case this is all
2563 * done in SubPostmasterMain.)
2565 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
2567 MyProcPid = getpid(); /* reset MyProcPid */
2569 /* We don't want the postmaster's proc_exit() handlers */
2572 /* Close the postmaster's sockets */
2573 ClosePostmasterPorts(false);
2575 /* Perform additional initialization and client authentication */
2576 BackendInitialize(port);
2578 /* And run the backend */
2579 proc_exit(BackendRun(port));
2581 #endif /* EXEC_BACKEND */
2585 /* in parent, fork failed */
2586 int save_errno = errno;
2591 (errmsg("could not fork new process for connection: %m")));
2592 report_fork_failure_to_client(port, save_errno);
2593 return STATUS_ERROR;
2596 /* in parent, successful fork */
2598 (errmsg_internal("forked new backend, pid=%d socket=%d",
2599 (int) pid, port->sock)));
2602 * Everything's been successful, it's safe to add this backend to our list
2606 bn->cancel_key = MyCancelKey;
2607 DLAddHead(BackendList, DLNewElem(bn));
2609 ShmemBackendArrayAdd(bn);
2616 * Try to report backend fork() failure to client before we close the
2617 * connection. Since we do not care to risk blocking the postmaster on
2618 * this connection, we set the connection to non-blocking and try only once.
2620 * This is grungy special-purpose code; we cannot use backend libpq since
2621 * it's not up and running.
2624 report_fork_failure_to_client(Port *port, int errnum)
2629 /* Format the error message packet (always V2 protocol) */
2630 snprintf(buffer, sizeof(buffer), "E%s%s\n",
2631 _("could not fork new process for connection: "),
2634 /* Set port to non-blocking. Don't do send() if this fails */
2635 if (!pg_set_noblock(port->sock))
2638 /* We'll retry after EINTR, but ignore all other failures */
2641 rc = send(port->sock, buffer, strlen(buffer) + 1, 0);
2642 } while (rc < 0 && errno == EINTR);
2647 * split_opts -- split a string of options and append it to an argv array
2649 * NB: the string is destructively modified!
2651 * Since no current POSTGRES arguments require any quoting characters,
2652 * we can use the simple-minded tactic of assuming each set of space-
2653 * delimited characters is a separate argv element.
2655 * If you don't like that, well, we *used* to pass the whole option string
2656 * as ONE argument to execl(), which was even less intelligent...
2659 split_opts(char **argv, int *argcp, char *s)
2663 while (isspace((unsigned char) *s))
2667 argv[(*argcp)++] = s;
2668 while (*s && !isspace((unsigned char) *s))
2677 * BackendInitialize -- initialize an interactive (postmaster-child)
2678 * backend process, and perform client authentication.
2680 * returns: nothing. Will not return at all if there's any failure.
2682 * Note: this code does not depend on having any access to shared memory.
2683 * In the EXEC_BACKEND case, we are physically attached to shared memory
2684 * but have not yet set up most of our local pointers to shmem structures.
2687 BackendInitialize(Port *port)
2690 char remote_host[NI_MAXHOST];
2691 char remote_port[NI_MAXSERV];
2692 char remote_ps_data[NI_MAXHOST];
2694 /* Save port etc. for ps status */
2698 * PreAuthDelay is a debugging aid for investigating problems in the
2699 * authentication cycle: it can be set in postgresql.conf to allow time to
2700 * attach to the newly-forked backend with a debugger. (See also the -W
2701 * backend switch, which we allow clients to pass through PGOPTIONS, but
2702 * it is not honored until after authentication.)
2704 if (PreAuthDelay > 0)
2705 pg_usleep(PreAuthDelay * 1000000L);
2707 ClientAuthInProgress = true; /* limit visibility of log messages */
2709 /* save process start time */
2710 port->SessionStartTime = GetCurrentTimestamp();
2711 port->session_start = timestamptz_to_time_t(port->SessionStartTime);
2713 /* set these to empty in case they are needed before we set them up */
2714 port->remote_host = "";
2715 port->remote_port = "";
2718 * Initialize libpq and enable reporting of ereport errors to the client.
2719 * Must do this now because authentication uses libpq to send messages.
2721 pq_init(); /* initialize libpq to talk to client */
2722 whereToSendOutput = DestRemote; /* now safe to ereport to client */
2725 * If possible, make this process a group leader, so that the postmaster
2726 * can signal any child processes too. (We do this now on the off chance
2727 * that something might spawn a child process during authentication.)
2731 elog(FATAL, "setsid() failed: %m");
2735 * We arrange for a simple exit(1) if we receive SIGTERM or SIGQUIT during
2736 * any client authentication related communication. Otherwise the
2737 * postmaster cannot shutdown the database FAST or IMMED cleanly if a
2738 * buggy client blocks a backend during authentication.
2740 pqsignal(SIGTERM, authdie);
2741 pqsignal(SIGQUIT, authdie);
2742 pqsignal(SIGALRM, authdie);
2743 PG_SETMASK(&AuthBlockSig);
2746 * Get the remote host name and port for logging and status display.
2748 remote_host[0] = '\0';
2749 remote_port[0] = '\0';
2750 if (pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2751 remote_host, sizeof(remote_host),
2752 remote_port, sizeof(remote_port),
2753 (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV))
2755 int ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2756 remote_host, sizeof(remote_host),
2757 remote_port, sizeof(remote_port),
2758 NI_NUMERICHOST | NI_NUMERICSERV);
2762 (errmsg_internal("pg_getnameinfo_all() failed: %s",
2763 gai_strerror(ret))));
2765 snprintf(remote_ps_data, sizeof(remote_ps_data),
2766 remote_port[0] == '\0' ? "%s" : "%s(%s)",
2767 remote_host, remote_port);
2769 if (Log_connections)
2771 (errmsg("connection received: host=%s%s%s",
2772 remote_host, remote_port[0] ? " port=" : "",
2776 * save remote_host and remote_port in port structure
2778 port->remote_host = strdup(remote_host);
2779 port->remote_port = strdup(remote_port);
2782 * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
2783 * etcetera from the postmaster, and have to load them ourselves. Build
2784 * the PostmasterContext (which didn't exist before, in this process) to
2787 * FIXME: [fork/exec] Ugh. Is there a way around this overhead?
2790 Assert(PostmasterContext == NULL);
2791 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
2793 ALLOCSET_DEFAULT_MINSIZE,
2794 ALLOCSET_DEFAULT_INITSIZE,
2795 ALLOCSET_DEFAULT_MAXSIZE);
2796 MemoryContextSwitchTo(PostmasterContext);
2804 * Ready to begin client interaction. We will give up and exit(0) after a
2805 * time delay, so that a broken client can't hog a connection
2806 * indefinitely. PreAuthDelay doesn't count against the time limit.
2808 if (!enable_sig_alarm(AuthenticationTimeout * 1000, false))
2809 elog(FATAL, "could not set timer for authorization timeout");
2812 * Receive the startup packet (which might turn out to be a cancel request
2815 status = ProcessStartupPacket(port, false);
2817 if (status != STATUS_OK)
2821 * Now that we have the user and database name, we can set the process
2822 * title for ps. It's good to do this as early as possible in startup.
2824 init_ps_display(port->user_name, port->database_name, remote_ps_data,
2825 update_process_title ? "authentication" : "");
2828 * Now perform authentication exchange.
2830 ClientAuthentication(port); /* might not return, if failure */
2833 * Done with authentication. Disable timeout, and prevent SIGTERM/SIGQUIT
2834 * again until backend startup is complete.
2836 if (!disable_sig_alarm(false))
2837 elog(FATAL, "could not disable timer for authorization timeout");
2838 PG_SETMASK(&BlockSig);
2840 if (Log_connections)
2842 (errmsg("connection authorized: user=%s database=%s",
2843 port->user_name, port->database_name)));
2848 * BackendRun -- set up the backend's argument list and invoke PostgresMain()
2851 * Shouldn't return at all.
2852 * If PostgresMain() fails, return status.
2855 BackendRun(Port *port)
2866 * Don't want backend to be able to see the postmaster random number
2867 * generator state. We have to clobber the static random_seed *and* start
2868 * a new random sequence in the random() library function.
2871 /* slightly hacky way to get integer microseconds part of timestamptz */
2872 TimestampDifference(0, port->SessionStartTime, &secs, &usecs);
2873 srandom((unsigned int) (MyProcPid ^ usecs));
2876 * Now, build the argv vector that will be given to PostgresMain.
2878 * The layout of the command line is
2879 * postgres [secure switches] -y databasename [insecure switches]
2880 * where the switches after -y come from the client request.
2882 * The maximum possible number of commandline arguments that could come
2883 * from ExtraOptions or port->cmdline_options is (strlen + 1) / 2; see
2887 maxac = 10; /* for fixed args supplied below */
2888 maxac += (strlen(ExtraOptions) + 1) / 2;
2889 if (port->cmdline_options)
2890 maxac += (strlen(port->cmdline_options) + 1) / 2;
2892 av = (char **) MemoryContextAlloc(TopMemoryContext,
2893 maxac * sizeof(char *));
2896 av[ac++] = "postgres";
2899 * Pass any backend switches specified with -o in the postmaster's own
2900 * command line. We assume these are secure. (It's OK to mangle
2901 * ExtraOptions now, since we're safely inside a subprocess.)
2903 split_opts(av, &ac, ExtraOptions);
2905 /* Tell the backend what protocol the frontend is using. */
2906 snprintf(protobuf, sizeof(protobuf), "-v%u", port->proto);
2907 av[ac++] = protobuf;
2910 * Tell the backend it is being called from the postmaster, and which
2911 * database to use. -y marks the end of secure switches.
2914 av[ac++] = port->database_name;
2917 * Pass the (insecure) option switches from the connection request. (It's
2918 * OK to mangle port->cmdline_options now.)
2920 if (port->cmdline_options)
2921 split_opts(av, &ac, port->cmdline_options);
2928 * Release postmaster's working memory context so that backend can recycle
2929 * the space. Note this does not trash *MyProcPort, because ConnCreate()
2930 * allocated that space with malloc() ... else we'd need to copy the Port
2931 * data here. Also, subsidiary data such as the username isn't lost
2932 * either; see ProcessStartupPacket().
2934 MemoryContextSwitchTo(TopMemoryContext);
2935 MemoryContextDelete(PostmasterContext);
2936 PostmasterContext = NULL;
2939 * Debug: print arguments being passed to backend
2942 (errmsg_internal("%s child[%d]: starting with (",
2943 progname, (int) getpid())));
2944 for (i = 0; i < ac; ++i)
2946 (errmsg_internal("\t%s", av[i])));
2948 (errmsg_internal(")")));
2950 ClientAuthInProgress = false; /* client_min_messages is active now */
2952 return (PostgresMain(ac, av, port->user_name));
2959 * postmaster_forkexec -- fork and exec a postmaster subprocess
2961 * The caller must have set up the argv array already, except for argv[2]
2962 * which will be filled with the name of the temp variable file.
2964 * Returns the child process PID, or -1 on fork failure (a suitable error
2965 * message has been logged on failure).
2967 * All uses of this routine will dispatch to SubPostmasterMain in the
2971 postmaster_forkexec(int argc, char *argv[])
2975 /* This entry point passes dummy values for the Port variables */
2976 memset(&port, 0, sizeof(port));
2977 return internal_forkexec(argc, argv, &port);
2981 * backend_forkexec -- fork/exec off a backend process
2983 * returns the pid of the fork/exec'd process, or -1 on failure
2986 backend_forkexec(Port *port)
2991 av[ac++] = "postgres";
2992 av[ac++] = "--forkbackend";
2993 av[ac++] = NULL; /* filled in by internal_forkexec */
2996 Assert(ac < lengthof(av));
2998 return internal_forkexec(ac, av, port);
3004 * internal_forkexec non-win32 implementation
3006 * - writes out backend variables to the parameter file
3007 * - fork():s, and then exec():s the child process
3010 internal_forkexec(int argc, char *argv[], Port *port)
3012 static unsigned long tmpBackendFileNum = 0;
3014 char tmpfilename[MAXPGPATH];
3015 BackendParameters param;
3018 if (!save_backend_variables(¶m, port))
3019 return -1; /* log made by save_backend_variables */
3021 /* Calculate name for temp file */
3022 snprintf(tmpfilename, MAXPGPATH, "%s/%s.backend_var.%d.%lu",
3023 PG_TEMP_FILES_DIR, PG_TEMP_FILE_PREFIX,
3024 MyProcPid, ++tmpBackendFileNum);
3027 fp = AllocateFile(tmpfilename, PG_BINARY_W);
3030 /* As in OpenTemporaryFile, try to make the temp-file directory */
3031 mkdir(PG_TEMP_FILES_DIR, S_IRWXU);
3033 fp = AllocateFile(tmpfilename, PG_BINARY_W);
3037 (errcode_for_file_access(),
3038 errmsg("could not create file \"%s\": %m",
3044 if (fwrite(¶m, sizeof(param), 1, fp) != 1)
3047 (errcode_for_file_access(),
3048 errmsg("could not write to file \"%s\": %m", tmpfilename)));
3057 (errcode_for_file_access(),
3058 errmsg("could not write to file \"%s\": %m", tmpfilename)));
3062 /* Make sure caller set up argv properly */
3064 Assert(argv[argc] == NULL);
3065 Assert(strncmp(argv[1], "--fork", 6) == 0);
3066 Assert(argv[2] == NULL);
3068 /* Insert temp file name after --fork argument */
3069 argv[2] = tmpfilename;
3071 /* Fire off execv in child */
3072 if ((pid = fork_process()) == 0)
3074 if (execv(postgres_exec_path, argv) < 0)
3077 (errmsg("could not execute server process \"%s\": %m",
3078 postgres_exec_path)));
3079 /* We're already in the child process here, can't return */
3084 return pid; /* Parent returns pid, or -1 on fork failure */
3089 * internal_forkexec win32 implementation
3091 * - starts backend using CreateProcess(), in suspended state
3092 * - writes out backend variables to the parameter file
3093 * - during this, duplicates handles and sockets required for
3094 * inheritance into the new process
3095 * - resumes execution of the new process once the backend parameter
3099 internal_forkexec(int argc, char *argv[], Port *port)
3102 PROCESS_INFORMATION pi;
3105 char cmdLine[MAXPGPATH * 2];
3106 HANDLE childHandleCopy;
3107 HANDLE waiterThread;
3109 BackendParameters *param;
3110 SECURITY_ATTRIBUTES sa;
3111 char paramHandleStr[32];
3113 /* Make sure caller set up argv properly */
3115 Assert(argv[argc] == NULL);
3116 Assert(strncmp(argv[1], "--fork", 6) == 0);
3117 Assert(argv[2] == NULL);
3119 /* Verify that there is room in the child list */
3120 if (win32_numChildren >= NUM_BACKENDARRAY_ELEMS)
3122 elog(LOG, "no room for child entry in backend list");
3123 /* Report same error as for a fork failure on Unix */
3128 /* Set up shared memory for parameter passing */
3129 ZeroMemory(&sa, sizeof(sa));
3130 sa.nLength = sizeof(sa);
3131 sa.bInheritHandle = TRUE;
3132 paramHandle = CreateFileMapping(INVALID_HANDLE_VALUE,
3136 sizeof(BackendParameters),
3138 if (paramHandle == INVALID_HANDLE_VALUE)
3140 elog(LOG, "could not create backend parameter file mapping: error code %d",
3141 (int) GetLastError());
3145 param = MapViewOfFile(paramHandle, FILE_MAP_WRITE, 0, 0, sizeof(BackendParameters));
3148 elog(LOG, "could not map backend parameter memory: error code %d",
3149 (int) GetLastError());
3150 CloseHandle(paramHandle);
3154 /* Insert temp file name after --fork argument */
3155 sprintf(paramHandleStr, "%lu", (DWORD) paramHandle);
3156 argv[2] = paramHandleStr;
3158 /* Format the cmd line */
3159 cmdLine[sizeof(cmdLine) - 1] = '\0';
3160 cmdLine[sizeof(cmdLine) - 2] = '\0';
3161 snprintf(cmdLine, sizeof(cmdLine) - 1, "\"%s\"", postgres_exec_path);
3163 while (argv[++i] != NULL)
3165 j = strlen(cmdLine);
3166 snprintf(cmdLine + j, sizeof(cmdLine) - 1 - j, " \"%s\"", argv[i]);
3168 if (cmdLine[sizeof(cmdLine) - 2] != '\0')
3170 elog(LOG, "subprocess command line too long");
3174 memset(&pi, 0, sizeof(pi));
3175 memset(&si, 0, sizeof(si));
3179 * Create the subprocess in a suspended state. This will be resumed later,
3180 * once we have written out the parameter file.
3182 if (!CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, CREATE_SUSPENDED,
3183 NULL, NULL, &si, &pi))
3185 elog(LOG, "CreateProcess call failed: %m (error code %d)",
3186 (int) GetLastError());
3190 if (!save_backend_variables(param, port, pi.hProcess, pi.dwProcessId))
3193 * log made by save_backend_variables, but we have to clean up the
3194 * mess with the half-started process
3196 if (!TerminateProcess(pi.hProcess, 255))
3198 (errmsg_internal("could not terminate unstarted process: error code %d",
3199 (int) GetLastError())));
3200 CloseHandle(pi.hProcess);
3201 CloseHandle(pi.hThread);
3202 return -1; /* log made by save_backend_variables */
3205 /* Drop the shared memory that is now inherited to the backend */
3206 if (!UnmapViewOfFile(param))
3207 elog(LOG, "could not unmap view of backend parameter file: error code %d",
3208 (int) GetLastError());
3209 if (!CloseHandle(paramHandle))
3210 elog(LOG, "could not close handle to backend parameter file: error code %d",
3211 (int) GetLastError());
3214 * Now that the backend variables are written out, we start the child
3215 * thread so it can start initializing while we set up the rest of the
3218 if (ResumeThread(pi.hThread) == -1)
3220 if (!TerminateProcess(pi.hProcess, 255))
3223 (errmsg_internal("could not terminate unstartable process: error code %d",
3224 (int) GetLastError())));
3225 CloseHandle(pi.hProcess);
3226 CloseHandle(pi.hThread);
3229 CloseHandle(pi.hProcess);
3230 CloseHandle(pi.hThread);
3232 (errmsg_internal("could not resume thread of unstarted process: error code %d",
3233 (int) GetLastError())));
3237 if (!IsUnderPostmaster)
3239 /* We are the Postmaster creating a child... */
3240 win32_AddChild(pi.dwProcessId, pi.hProcess);
3243 /* Set up the thread to handle the SIGCHLD for this process */
3244 if (DuplicateHandle(GetCurrentProcess(),
3246 GetCurrentProcess(),
3250 DUPLICATE_SAME_ACCESS) == 0)
3252 (errmsg_internal("could not duplicate child handle: error code %d",
3253 (int) GetLastError())));
3255 waiterThread = CreateThread(NULL, 64 * 1024, win32_sigchld_waiter,
3256 (LPVOID) childHandleCopy, 0, NULL);
3259 (errmsg_internal("could not create sigchld waiter thread: error code %d",
3260 (int) GetLastError())));
3261 CloseHandle(waiterThread);
3263 if (IsUnderPostmaster)
3264 CloseHandle(pi.hProcess);
3265 CloseHandle(pi.hThread);
3267 return pi.dwProcessId;
3273 * SubPostmasterMain -- Get the fork/exec'd process into a state equivalent
3274 * to what it would be if we'd simply forked on Unix, and then
3275 * dispatch to the appropriate place.
3277 * The first two command line arguments are expected to be "--forkFOO"
3278 * (where FOO indicates which postmaster child we are to become), and
3279 * the name of a variables file that we can read to load data that would
3280 * have been inherited by fork() on Unix. Remaining arguments go to the
3281 * subprocess FooMain() routine.
3284 SubPostmasterMain(int argc, char *argv[])
3288 /* Do this sooner rather than later... */
3289 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
3291 MyProcPid = getpid(); /* reset MyProcPid */
3293 /* Lose the postmaster's on-exit routines (really a no-op) */
3296 /* In EXEC_BACKEND case we will not have inherited these settings */
3297 IsPostmasterEnvironment = true;
3298 whereToSendOutput = DestNone;
3300 /* Setup essential subsystems (to ensure elog() behaves sanely) */
3301 MemoryContextInit();
3302 InitializeGUCOptions();
3304 /* Read in the variables file */
3305 memset(&port, 0, sizeof(Port));
3306 read_backend_variables(argv[2], &port);
3308 /* Check we got appropriate args */
3310 elog(FATAL, "invalid subpostmaster invocation");
3313 * If appropriate, physically re-attach to shared memory segment. We want
3314 * to do this before going any further to ensure that we can attach at the
3315 * same address the postmaster used.
3317 if (strcmp(argv[1], "--forkbackend") == 0 ||
3318 strcmp(argv[1], "--forkautovac") == 0 ||
3319 strcmp(argv[1], "--forkboot") == 0)
3320 PGSharedMemoryReAttach();
3322 /* autovacuum needs this set before calling InitProcess */
3323 if (strcmp(argv[1], "--forkautovac") == 0)
3327 * Start our win32 signal implementation. This has to be done after we
3328 * read the backend variables, because we need to pick up the signal pipe
3329 * from the parent process.
3332 pgwin32_signal_initialize();
3335 /* In EXEC_BACKEND case we will not have inherited these settings */
3337 PG_SETMASK(&BlockSig);
3339 /* Read in remaining GUC variables */
3340 read_nondefault_variables();
3342 /* Run backend or appropriate child */
3343 if (strcmp(argv[1], "--forkbackend") == 0)
3345 Assert(argc == 3); /* shouldn't be any more args */
3347 /* Close the postmaster's sockets */
3348 ClosePostmasterPorts(false);
3351 * Need to reinitialize the SSL library in the backend, since the
3352 * context structures contain function pointers and cannot be passed
3353 * through the parameter file.
3357 secure_initialize();
3361 * Perform additional initialization and client authentication.
3363 * We want to do this before InitProcess() for a couple of reasons: 1.
3364 * so that we aren't eating up a PGPROC slot while waiting on the
3365 * client. 2. so that if InitProcess() fails due to being out of
3366 * PGPROC slots, we have already initialized libpq and are able to
3367 * report the error to the client.
3369 BackendInitialize(&port);
3371 /* Restore basic shared memory pointers */
3372 InitShmemAccess(UsedShmemSegAddr);
3374 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3378 * Attach process to shared data structures. If testing EXEC_BACKEND
3379 * on Linux, you must run this as root before starting the postmaster:
3381 * echo 0 >/proc/sys/kernel/randomize_va_space
3383 * This prevents a randomized stack base address that causes child
3384 * shared memory to be at a different address than the parent, making
3385 * it impossible to attached to shared memory. Return the value to
3386 * '1' when finished.
3388 CreateSharedMemoryAndSemaphores(false, 0);
3390 /* And run the backend */
3391 proc_exit(BackendRun(&port));
3393 if (strcmp(argv[1], "--forkboot") == 0)
3395 /* Close the postmaster's sockets */
3396 ClosePostmasterPorts(false);
3398 /* Restore basic shared memory pointers */
3399 InitShmemAccess(UsedShmemSegAddr);
3401 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3404 /* Attach process to shared data structures */
3405 CreateSharedMemoryAndSemaphores(false, 0);
3407 BootstrapMain(argc - 2, argv + 2);
3410 if (strcmp(argv[1], "--forkautovac") == 0)
3412 /* Close the postmaster's sockets */
3413 ClosePostmasterPorts(false);
3415 /* Restore basic shared memory pointers */
3416 InitShmemAccess(UsedShmemSegAddr);
3418 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3421 /* Attach process to shared data structures */
3422 CreateSharedMemoryAndSemaphores(false, 0);
3424 AutoVacMain(argc - 2, argv + 2);
3427 if (strcmp(argv[1], "--forkarch") == 0)
3429 /* Close the postmaster's sockets */
3430 ClosePostmasterPorts(false);
3432 /* Do not want to attach to shared memory */
3434 PgArchiverMain(argc, argv);
3437 if (strcmp(argv[1], "--forkcol") == 0)
3439 /* Close the postmaster's sockets */
3440 ClosePostmasterPorts(false);
3442 /* Do not want to attach to shared memory */
3444 PgstatCollectorMain(argc, argv);
3447 if (strcmp(argv[1], "--forklog") == 0)
3449 /* Close the postmaster's sockets */
3450 ClosePostmasterPorts(true);
3452 /* Do not want to attach to shared memory */
3454 SysLoggerMain(argc, argv);
3458 return 1; /* shouldn't get here */
3460 #endif /* EXEC_BACKEND */
3464 * ExitPostmaster -- cleanup
3466 * Do NOT call exit() directly --- always go through here!
3469 ExitPostmaster(int status)
3471 /* should cleanup shared memory and kill all backends */
3474 * Not sure of the semantics here. When the Postmaster dies, should the
3475 * backends all be killed? probably not.
3477 * MUST -- vadim 05-10-1999
3484 * sigusr1_handler - handle signal conditions from child processes
3487 sigusr1_handler(SIGNAL_ARGS)
3489 int save_errno = errno;
3491 PG_SETMASK(&BlockSig);
3493 if (CheckPostmasterSignal(PMSIGNAL_PASSWORD_CHANGE))
3496 * Authorization file has changed.
3501 if (CheckPostmasterSignal(PMSIGNAL_WAKEN_CHILDREN))
3504 * Send SIGUSR1 to all children (triggers CatchupInterruptHandler).
3505 * See storage/ipc/sinval[adt].c for the use of this.
3507 if (Shutdown <= SmartShutdown)
3509 SignalChildren(SIGUSR1);
3510 if (AutoVacPID != 0)
3511 signal_child(AutoVacPID, SIGUSR1);
3515 if (CheckPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER) &&
3516 PgArchPID != 0 && Shutdown == NoShutdown)
3519 * Send SIGUSR1 to archiver process, to wake it up and begin archiving
3520 * next transaction log file.
3522 signal_child(PgArchPID, SIGUSR1);
3525 if (CheckPostmasterSignal(PMSIGNAL_ROTATE_LOGFILE) &&
3528 /* Tell syslogger to rotate logfile */
3529 signal_child(SysLoggerPID, SIGUSR1);
3532 if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC))
3535 * Start one iteration of the autovacuum daemon, even if autovacuuming
3536 * is nominally not enabled. This is so we can have an active defense
3537 * against transaction ID wraparound. We set a flag for the main loop
3538 * to do it rather than trying to do it here --- this is because the
3539 * autovac process itself may send the signal, and we want to handle
3540 * that by launching another iteration as soon as the current one
3543 force_autovac = true;
3546 PG_SETMASK(&UnBlockSig);
3553 * Dummy signal handler
3555 * We use this for signals that we don't actually use in the postmaster,
3556 * but we do use in backends. If we were to SIG_IGN such signals in the
3557 * postmaster, then a newly started backend might drop a signal that arrives
3558 * before it's able to reconfigure its signal processing. (See notes in
3562 dummy_handler(SIGNAL_ARGS)
3568 * CharRemap: given an int in range 0..61, produce textual encoding of it
3569 * per crypt(3) conventions.
3593 RandomSalt(char *cryptSalt, char *md5Salt)
3595 long rand = PostmasterRandom();
3597 cryptSalt[0] = CharRemap(rand % 62);
3598 cryptSalt[1] = CharRemap(rand / 62);
3601 * It's okay to reuse the first random value for one of the MD5 salt
3602 * bytes, since only one of the two salts will be sent to the client.
3603 * After that we need to compute more random bits.
3605 * We use % 255, sacrificing one possible byte value, so as to ensure that
3606 * all bits of the random() value participate in the result. While at it,
3607 * add one to avoid generating any null bytes.
3609 md5Salt[0] = (rand % 255) + 1;
3610 rand = PostmasterRandom();
3611 md5Salt[1] = (rand % 255) + 1;
3612 rand = PostmasterRandom();
3613 md5Salt[2] = (rand % 255) + 1;
3614 rand = PostmasterRandom();
3615 md5Salt[3] = (rand % 255) + 1;
3622 PostmasterRandom(void)
3624 static bool initialized = false;
3628 Assert(random_seed != 0);
3629 srandom(random_seed);
3637 * Count up number of child processes (regular backends only)
3645 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
3652 * StartChildProcess -- start a non-backend child process for the postmaster
3654 * xlop determines what kind of child will be started. All child types
3655 * initially go to BootstrapMain, which will handle common setup.
3657 * Return value of StartChildProcess is subprocess' PID, or 0 if failed
3658 * to start subprocess.
3661 StartChildProcess(int xlop)
3669 * Set up command-line arguments for subprocess
3671 av[ac++] = "postgres";
3674 av[ac++] = "--forkboot";
3675 av[ac++] = NULL; /* filled in by postmaster_forkexec */
3678 snprintf(xlbuf, sizeof(xlbuf), "-x%d", xlop);
3682 av[ac++] = "template1";
3685 Assert(ac < lengthof(av));
3688 pid = postmaster_forkexec(ac, av);
3689 #else /* !EXEC_BACKEND */
3690 pid = fork_process();
3692 if (pid == 0) /* child */
3694 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
3696 /* Close the postmaster's sockets */
3697 ClosePostmasterPorts(false);
3699 /* Lose the postmaster's on-exit routines and port connections */
3702 /* Release postmaster's working memory context */
3703 MemoryContextSwitchTo(TopMemoryContext);
3704 MemoryContextDelete(PostmasterContext);
3705 PostmasterContext = NULL;
3707 BootstrapMain(ac, av);
3710 #endif /* EXEC_BACKEND */
3714 /* in parent, fork failed */
3715 int save_errno = errno;
3720 case BS_XLOG_STARTUP:
3722 (errmsg("could not fork startup process: %m")));
3724 case BS_XLOG_BGWRITER:
3726 (errmsg("could not fork background writer process: %m")));
3730 (errmsg("could not fork process: %m")));
3735 * fork failure is fatal during startup, but there's no need to choke
3736 * immediately if starting other child types fails.
3738 if (xlop == BS_XLOG_STARTUP)
3744 * in parent, successful fork
3751 * Create the opts file
3754 CreateOptsFile(int argc, char *argv[], char *fullprogname)
3759 #define OPTS_FILE "postmaster.opts"
3761 if ((fp = fopen(OPTS_FILE, "w")) == NULL)
3763 elog(LOG, "could not create file \"%s\": %m", OPTS_FILE);
3767 fprintf(fp, "%s", fullprogname);
3768 for (i = 1; i < argc; i++)
3769 fprintf(fp, " %s%s%s", SYSTEMQUOTE, argv[i], SYSTEMQUOTE);
3774 elog(LOG, "could not write file \"%s\": %m", OPTS_FILE);
3785 * The following need to be available to the save/restore_backend_variables
3788 extern slock_t *ShmemLock;
3789 extern LWLock *LWLockArray;
3790 extern slock_t *ProcStructLock;
3791 extern PROC_HDR *ProcGlobal;
3792 extern PGPROC *DummyProcs;
3793 extern int pgStatSock;
3796 #define write_inheritable_socket(dest, src, childpid) (*(dest) = (src))
3797 #define read_inheritable_socket(dest, src) (*(dest) = *(src))
3799 static void write_duplicated_handle(HANDLE * dest, HANDLE src, HANDLE child);
3800 static void write_inheritable_socket(InheritableSocket * dest, SOCKET src,
3802 static void read_inheritable_socket(SOCKET * dest, InheritableSocket * src);
3806 /* Save critical backend variables into the BackendParameters struct */
3809 save_backend_variables(BackendParameters * param, Port *port)
3812 save_backend_variables(BackendParameters * param, Port *port,
3813 HANDLE childProcess, pid_t childPid)
3816 memcpy(¶m->port, port, sizeof(Port));
3817 write_inheritable_socket(¶m->portsocket, port->sock, childPid);
3819 StrNCpy(param->DataDir, DataDir, MAXPGPATH);
3821 memcpy(¶m->ListenSocket, &ListenSocket, sizeof(ListenSocket));
3823 param->MyCancelKey = MyCancelKey;
3825 param->UsedShmemSegID = UsedShmemSegID;
3826 param->UsedShmemSegAddr = UsedShmemSegAddr;
3828 param->ShmemLock = ShmemLock;
3829 param->ShmemVariableCache = ShmemVariableCache;
3830 param->ShmemBackendArray = ShmemBackendArray;
3832 param->LWLockArray = LWLockArray;
3833 param->ProcStructLock = ProcStructLock;
3834 param->ProcGlobal = ProcGlobal;
3835 param->DummyProcs = DummyProcs;
3836 write_inheritable_socket(¶m->pgStatSock, pgStatSock, childPid);
3838 param->PostmasterPid = PostmasterPid;
3839 param->PgStartTime = PgStartTime;
3842 param->PostmasterHandle = PostmasterHandle;
3843 write_duplicated_handle(¶m->initial_signal_pipe,
3844 pgwin32_create_signal_listener(childPid),
3848 memcpy(¶m->syslogPipe, &syslogPipe, sizeof(syslogPipe));
3850 StrNCpy(param->my_exec_path, my_exec_path, MAXPGPATH);
3852 StrNCpy(param->pkglib_path, pkglib_path, MAXPGPATH);
3854 StrNCpy(param->ExtraOptions, ExtraOptions, MAXPGPATH);
3856 StrNCpy(param->lc_collate, setlocale(LC_COLLATE, NULL), LOCALE_NAME_BUFLEN);
3857 StrNCpy(param->lc_ctype, setlocale(LC_CTYPE, NULL), LOCALE_NAME_BUFLEN);
3865 * Duplicate a handle for usage in a child process, and write the child
3866 * process instance of the handle to the parameter file.
3869 write_duplicated_handle(HANDLE * dest, HANDLE src, HANDLE childProcess)
3871 HANDLE hChild = INVALID_HANDLE_VALUE;
3873 if (!DuplicateHandle(GetCurrentProcess(),
3879 DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS))
3881 (errmsg_internal("could not duplicate handle to be written to backend parameter file: error code %d",
3882 (int) GetLastError())));
3888 * Duplicate a socket for usage in a child process, and write the resulting
3889 * structure to the parameter file.
3890 * This is required because a number of LSPs (Layered Service Providers) very
3891 * common on Windows (antivirus, firewalls, download managers etc) break
3892 * straight socket inheritance.
3895 write_inheritable_socket(InheritableSocket * dest, SOCKET src, pid_t childpid)
3897 dest->origsocket = src;
3898 if (src != 0 && src != -1)
3901 if (WSADuplicateSocket(src, childpid, &dest->wsainfo) != 0)
3903 (errmsg("could not duplicate socket %d for use in backend: error code %d",
3904 src, WSAGetLastError())));
3909 * Read a duplicate socket structure back, and get the socket descriptor.
3912 read_inheritable_socket(SOCKET * dest, InheritableSocket * src)
3916 if (src->origsocket == -1 || src->origsocket == 0)
3918 /* Not a real socket! */
3919 *dest = src->origsocket;
3923 /* Actual socket, so create from structure */
3924 s = WSASocket(FROM_PROTOCOL_INFO,
3930 if (s == INVALID_SOCKET)
3932 write_stderr("could not create inherited socket: error code %d\n",
3939 * To make sure we don't get two references to the same socket, close
3940 * the original one. (This would happen when inheritance actually
3943 closesocket(src->origsocket);
3949 read_backend_variables(char *id, Port *port)
3951 BackendParameters param;
3954 /* Non-win32 implementation reads from file */
3958 fp = AllocateFile(id, PG_BINARY_R);
3961 write_stderr("could not read from backend variables file \"%s\": %s\n",
3962 id, strerror(errno));
3966 if (fread(¶m, sizeof(param), 1, fp) != 1)
3968 write_stderr("could not read from backend variables file \"%s\": %s\n",
3969 id, strerror(errno));
3975 if (unlink(id) != 0)
3977 write_stderr("could not remove file \"%s\": %s\n",
3978 id, strerror(errno));
3982 /* Win32 version uses mapped file */
3984 BackendParameters *paramp;
3986 paramHandle = (HANDLE) atol(id);
3987 paramp = MapViewOfFile(paramHandle, FILE_MAP_READ, 0, 0, 0);
3990 write_stderr("could not map view of backend variables: error code %d\n",
3991 (int) GetLastError());
3995 memcpy(¶m, paramp, sizeof(BackendParameters));
3997 if (!UnmapViewOfFile(paramp))
3999 write_stderr("could not unmap view of backend variables: error code %d\n",
4000 (int) GetLastError());
4004 if (!CloseHandle(paramHandle))
4006 write_stderr("could not close handle to backend parameter variables: error code %d\n",
4007 (int) GetLastError());
4012 restore_backend_variables(¶m, port);
4015 /* Restore critical backend variables from the BackendParameters struct */
4017 restore_backend_variables(BackendParameters * param, Port *port)
4019 memcpy(port, ¶m->port, sizeof(Port));
4020 read_inheritable_socket(&port->sock, ¶m->portsocket);
4022 SetDataDir(param->DataDir);
4024 memcpy(&ListenSocket, ¶m->ListenSocket, sizeof(ListenSocket));
4026 MyCancelKey = param->MyCancelKey;
4028 UsedShmemSegID = param->UsedShmemSegID;
4029 UsedShmemSegAddr = param->UsedShmemSegAddr;
4031 ShmemLock = param->ShmemLock;
4032 ShmemVariableCache = param->ShmemVariableCache;
4033 ShmemBackendArray = param->ShmemBackendArray;
4035 LWLockArray = param->LWLockArray;
4036 ProcStructLock = param->ProcStructLock;
4037 ProcGlobal = param->ProcGlobal;
4038 DummyProcs = param->DummyProcs;
4039 read_inheritable_socket(&pgStatSock, ¶m->pgStatSock);
4041 PostmasterPid = param->PostmasterPid;
4042 PgStartTime = param->PgStartTime;
4045 PostmasterHandle = param->PostmasterHandle;
4046 pgwin32_initial_signal_pipe = param->initial_signal_pipe;
4049 memcpy(&syslogPipe, ¶m->syslogPipe, sizeof(syslogPipe));
4051 StrNCpy(my_exec_path, param->my_exec_path, MAXPGPATH);
4053 StrNCpy(pkglib_path, param->pkglib_path, MAXPGPATH);
4055 StrNCpy(ExtraOptions, param->ExtraOptions, MAXPGPATH);
4057 setlocale(LC_COLLATE, param->lc_collate);
4058 setlocale(LC_CTYPE, param->lc_ctype);
4063 ShmemBackendArraySize(void)
4065 return mul_size(NUM_BACKENDARRAY_ELEMS, sizeof(Backend));
4069 ShmemBackendArrayAllocation(void)
4071 Size size = ShmemBackendArraySize();
4073 ShmemBackendArray = (Backend *) ShmemAlloc(size);
4074 /* Mark all slots as empty */
4075 memset(ShmemBackendArray, 0, size);
4079 ShmemBackendArrayAdd(Backend *bn)
4083 /* Find an empty slot */
4084 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
4086 if (ShmemBackendArray[i].pid == 0)
4088 ShmemBackendArray[i] = *bn;
4094 (errmsg_internal("no free slots in shmem backend array")));
4098 ShmemBackendArrayRemove(pid_t pid)
4102 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
4104 if (ShmemBackendArray[i].pid == pid)
4106 /* Mark the slot as empty */
4107 ShmemBackendArray[i].pid = 0;
4113 (errmsg_internal("could not find backend entry with pid %d",
4116 #endif /* EXEC_BACKEND */
4122 * Note: The following three functions must not be interrupted (eg. by
4123 * signals). As the Postgres Win32 signalling architecture (currently)
4124 * requires polling, or APC checking functions which aren't used here, this
4127 * We keep two separate arrays, instead of a single array of pid/HANDLE
4128 * structs, to avoid having to re-create a handle array for
4129 * WaitForMultipleObjects on each call to win32_waitpid.
4133 win32_AddChild(pid_t pid, HANDLE handle)
4135 Assert(win32_childPIDArray && win32_childHNDArray);
4136 if (win32_numChildren < NUM_BACKENDARRAY_ELEMS)
4138 win32_childPIDArray[win32_numChildren] = pid;
4139 win32_childHNDArray[win32_numChildren] = handle;
4140 ++win32_numChildren;
4144 (errmsg_internal("no room for child entry with pid %lu",
4145 (unsigned long) pid)));
4149 win32_RemoveChild(pid_t pid)
4153 Assert(win32_childPIDArray && win32_childHNDArray);
4155 for (i = 0; i < win32_numChildren; i++)
4157 if (win32_childPIDArray[i] == pid)
4159 CloseHandle(win32_childHNDArray[i]);
4161 /* Swap last entry into the "removed" one */
4162 --win32_numChildren;
4163 win32_childPIDArray[i] = win32_childPIDArray[win32_numChildren];
4164 win32_childHNDArray[i] = win32_childHNDArray[win32_numChildren];
4170 (errmsg_internal("could not find child entry with pid %lu",
4171 (unsigned long) pid)));
4175 win32_waitpid(int *exitstatus)
4178 * Note: Do NOT use WaitForMultipleObjectsEx, as we don't want to run
4184 unsigned long offset;
4186 Assert(win32_childPIDArray && win32_childHNDArray);
4187 elog(DEBUG3, "waiting on %lu children", win32_numChildren);
4189 for (offset = 0; offset < win32_numChildren; offset += MAXIMUM_WAIT_OBJECTS)
4191 unsigned long num = Min(MAXIMUM_WAIT_OBJECTS, win32_numChildren - offset);
4193 ret = WaitForMultipleObjects(num, &win32_childHNDArray[offset], FALSE, 0);
4198 (errmsg_internal("failed to wait on %lu of %lu children: error code %d",
4199 num, win32_numChildren, (int) GetLastError())));
4203 /* No children (in this chunk) have finished */
4209 * Get the exit code, and return the PID of, the respective
4212 index = offset + ret - WAIT_OBJECT_0;
4213 Assert(index >= 0 && index < win32_numChildren);
4214 if (!GetExitCodeProcess(win32_childHNDArray[index], &exitCode))
4217 * If we get this far, this should never happen, but, then
4218 * again... No choice other than to assume a catastrophic
4222 (errmsg_internal("failed to get exit code for child %lu",
4223 (unsigned long) win32_childPIDArray[index])));
4225 *exitstatus = (int) exitCode;
4226 return win32_childPIDArray[index];
4230 /* No children have finished */
4235 * Note! Code below executes on separate threads, one for
4236 * each child process created
4239 win32_sigchld_waiter(LPVOID param)
4241 HANDLE procHandle = (HANDLE) param;
4243 DWORD r = WaitForSingleObject(procHandle, INFINITE);
4245 if (r == WAIT_OBJECT_0)
4246 pg_queue_signal(SIGCHLD);
4248 write_stderr("could not wait on child process handle: error code %d\n",
4249 (int) GetLastError());
4250 CloseHandle(procHandle);