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.525 2007/02/16 17:06:59 tgl Exp $
45 * The Postmaster sets up shared memory data structures
49 * The Postmaster shares memory with the backends but should avoid
50 * touching shared memory, so as not to become stuck if a crashing
51 * backend screws up locks or shared memory. Likewise, the Postmaster
52 * should never block on messages from frontend clients.
55 * The Postmaster cleans up after backends if they have an emergency
56 * exit and/or core dump.
59 * Use write_stderr() only for reporting "interactive" errors
60 * (essentially, bogus arguments on the command line). Once the
61 * postmaster is launched, use ereport(). In particular, don't use
62 * write_stderr() for anything that occurs after pmdaemonize.
64 *-------------------------------------------------------------------------
75 #include <sys/socket.h>
77 #include <sys/param.h>
78 #include <netinet/in.h>
79 #include <arpa/inet.h>
83 #ifdef HAVE_SYS_SELECT_H
84 #include <sys/select.h>
92 #include <DNSServiceDiscovery/DNSServiceDiscovery.h>
95 #include "access/transam.h"
96 #include "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, bgwriter and autovacuum launcher
133 * tasks are not in this list. Autovacuum worker processes are on it.
137 pid_t pid; /* process id of backend */
138 long cancel_key; /* cancel key for cancels for this backend */
139 bool is_autovacuum; /* is it an autovacuum process */
142 static Dllist *BackendList;
146 * Number of entries in the backend table. Twice the number of backends,
147 * plus four other subprocesses (stats, bgwriter, autovac, logger).
149 #define NUM_BACKENDARRAY_ELEMS (2*MaxBackends + 4)
150 static Backend *ShmemBackendArray;
153 /* The socket number we are listening for connections on */
156 char *ListenAddresses;
159 * ReservedBackends is the number of backends reserved for superuser use.
160 * This number is taken out of the pool size given by MaxBackends so
161 * number of backend slots available to non-superusers is
162 * (MaxBackends - ReservedBackends). Note what this really means is
163 * "if there are <= ReservedBackends connections available, only superusers
164 * can make new connections" --- pre-existing superuser connections don't
165 * count against the limit.
167 int ReservedBackends;
169 /* The socket(s) we're listening to. */
171 static int ListenSocket[MAXLISTEN];
174 * Set by the -o option
176 static char ExtraOptions[MAXPGPATH];
179 * These globals control the behavior of the postmaster in case some
180 * backend dumps core. Normally, it kills all peers of the dead backend
181 * and reinitializes shared memory. By specifying -s or -n, we can have
182 * the postmaster stop (rather than kill) peers and not reinitialize
183 * shared data structures.
185 static bool Reinit = true;
186 static int SendStop = false;
188 /* still more option variables */
189 bool EnableSSL = false;
190 bool SilentMode = false; /* silent mode (-S) */
192 int PreAuthDelay = 0;
193 int AuthenticationTimeout = 60;
195 bool log_hostname; /* for ps display and logging */
196 bool Log_connections = false;
197 bool Db_user_namespace = false;
201 /* PIDs of special child processes; 0 when not running */
202 static pid_t StartupPID = 0,
207 pid_t SysLoggerPID = 0; /* Needs to be accessed from elog.c */
209 /* Startup/shutdown state */
211 #define SmartShutdown 1
212 #define FastShutdown 2
214 static int Shutdown = NoShutdown;
216 static bool FatalError = false; /* T if recovering from backend crash */
218 bool ClientAuthInProgress = false; /* T during new-client
221 /* received START_AUTOVAC_LAUNCHER signal */
222 static bool start_autovac_launcher = false;
225 * State for assigning random salts and cancel keys.
226 * Also, the global MyCancelKey passes the cancel key assigned to a given
227 * backend from the postmaster to that backend (via fork).
229 static unsigned int random_seed = 0;
235 #ifdef HAVE_INT_OPTRESET
240 * postmaster.c - function prototypes
242 static void checkDataDir(void);
245 static void reg_reply(DNSServiceRegistrationReplyErrorType errorCode,
248 static void pmdaemonize(void);
249 static Port *ConnCreate(int serverFd);
250 static void ConnFree(Port *port);
251 static void reset_shared(int port);
252 static void SIGHUP_handler(SIGNAL_ARGS);
253 static void pmdie(SIGNAL_ARGS);
254 static void reaper(SIGNAL_ARGS);
255 static void sigusr1_handler(SIGNAL_ARGS);
256 static void dummy_handler(SIGNAL_ARGS);
257 static void CleanupBackend(int pid, int exitstatus);
258 static void HandleChildCrash(int pid, int exitstatus, const char *procname);
259 static void LogChildExit(int lev, const char *procname,
260 int pid, int exitstatus);
261 static void BackendInitialize(Port *port);
262 static int BackendRun(Port *port);
263 static void ExitPostmaster(int status);
264 static int ServerLoop(void);
265 static int BackendStartup(Port *port);
266 static int ProcessStartupPacket(Port *port, bool SSLdone);
267 static void processCancelRequest(Port *port, void *pkt);
268 static int initMasks(fd_set *rmask);
269 static void report_fork_failure_to_client(Port *port, int errnum);
270 static enum CAC_state canAcceptConnections(void);
271 static long PostmasterRandom(void);
272 static void RandomSalt(char *cryptSalt, char *md5Salt);
273 static void signal_child(pid_t pid, int signal);
274 static void SignalChildren(int signal);
275 static void SignalSomeChildren(int signal, bool only_autovac);
276 static int CountChildren(void);
277 static bool CreateOptsFile(int argc, char *argv[], char *fullprogname);
278 static pid_t StartChildProcess(int xlop);
279 static void StartAutovacuumWorker(void);
284 static void win32_AddChild(pid_t pid, HANDLE handle);
285 static void win32_RemoveChild(pid_t pid);
286 static pid_t win32_waitpid(int *exitstatus);
287 static DWORD WINAPI win32_sigchld_waiter(LPVOID param);
289 static pid_t *win32_childPIDArray;
290 static HANDLE *win32_childHNDArray;
291 static unsigned long win32_numChildren = 0;
293 HANDLE PostmasterHandle;
296 static pid_t backend_forkexec(Port *port);
297 static pid_t internal_forkexec(int argc, char *argv[], Port *port);
299 /* Type for a socket that can be inherited to a client process */
303 SOCKET origsocket; /* Original socket value, or -1 if not a
305 WSAPROTOCOL_INFO wsainfo;
308 typedef int InheritableSocket;
311 typedef struct LWLock LWLock; /* ugly kluge */
314 * Structure contains all variables passed to exec:ed backends
319 InheritableSocket portsocket;
320 char DataDir[MAXPGPATH];
321 int ListenSocket[MAXLISTEN];
323 unsigned long UsedShmemSegID;
324 void *UsedShmemSegAddr;
326 VariableCache ShmemVariableCache;
327 Backend *ShmemBackendArray;
329 slock_t *ProcStructLock;
330 PROC_HDR *ProcGlobal;
332 InheritableSocket pgStatSock;
334 TimestampTz PgStartTime;
336 HANDLE PostmasterHandle;
337 HANDLE initial_signal_pipe;
338 HANDLE syslogPipe[2];
342 char my_exec_path[MAXPGPATH];
343 char pkglib_path[MAXPGPATH];
344 char ExtraOptions[MAXPGPATH];
345 char lc_collate[LOCALE_NAME_BUFLEN];
346 char lc_ctype[LOCALE_NAME_BUFLEN];
349 static void read_backend_variables(char *id, Port *port);
350 static void restore_backend_variables(BackendParameters * param, Port *port);
353 static bool save_backend_variables(BackendParameters * param, Port *port);
355 static bool save_backend_variables(BackendParameters * param, Port *port,
356 HANDLE childProcess, pid_t childPid);
359 static void ShmemBackendArrayAdd(Backend *bn);
360 static void ShmemBackendArrayRemove(pid_t pid);
361 #endif /* EXEC_BACKEND */
363 #define StartupDataBase() StartChildProcess(BS_XLOG_STARTUP)
364 #define StartBackgroundWriter() StartChildProcess(BS_XLOG_BGWRITER)
366 /* Macros to check exit status of a child process */
367 #define EXIT_STATUS_0(st) ((st) == 0)
368 #define EXIT_STATUS_1(st) (WIFEXITED(st) && WEXITSTATUS(st) == 1)
372 * Postmaster main entry point
375 PostmasterMain(int argc, char *argv[])
379 char *userDoption = NULL;
382 MyProcPid = PostmasterPid = getpid();
384 IsPostmasterEnvironment = true;
387 * for security, no dir or file created can be group or other accessible
389 umask((mode_t) 0077);
392 * Fire up essential subsystems: memory management
397 * By default, palloc() requests in the postmaster will be allocated in
398 * the PostmasterContext, which is space that can be recycled by backends.
399 * Allocated data that needs to be available to backends should be
400 * allocated in TopMemoryContext.
402 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
404 ALLOCSET_DEFAULT_MINSIZE,
405 ALLOCSET_DEFAULT_INITSIZE,
406 ALLOCSET_DEFAULT_MAXSIZE);
407 MemoryContextSwitchTo(PostmasterContext);
409 if (find_my_exec(argv[0], my_exec_path) < 0)
410 elog(FATAL, "%s: could not locate my own executable path",
413 get_pkglib_path(my_exec_path, pkglib_path);
418 InitializeGUCOptions();
423 * Parse command-line options. CAUTION: keep this in sync with
424 * tcop/postgres.c (the option sets should not conflict)
425 * and with the common help() function in main/main.c.
427 while ((opt = getopt(argc, argv, "A:B:c:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:W:-:")) != -1)
432 SetConfigOption("debug_assertions", optarg, PGC_POSTMASTER, PGC_S_ARGV);
436 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
440 userDoption = optarg;
444 set_debug_options(atoi(optarg), PGC_POSTMASTER, PGC_S_ARGV);
448 SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
452 SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
456 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
460 if (!set_plan_disabling_options(optarg, PGC_POSTMASTER, PGC_S_ARGV))
462 write_stderr("%s: invalid argument for option -f: \"%s\"\n",
469 SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
473 SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
477 /* only used by interactive backend */
481 SetConfigOption("unix_socket_directory", optarg, PGC_POSTMASTER, PGC_S_ARGV);
485 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
489 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
493 /* Don't reinit shared mem after abnormal exit */
498 SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
502 /* Other options to pass to the backend on the command line */
503 snprintf(ExtraOptions + strlen(ExtraOptions),
504 sizeof(ExtraOptions) - strlen(ExtraOptions),
509 SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
513 SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
517 /* only used by single-user backend */
521 SetConfigOption("work_mem", optarg, PGC_POSTMASTER, PGC_S_ARGV);
525 SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
531 * In the event that some backend dumps core, send SIGSTOP,
532 * rather than SIGQUIT, to all its peers. This lets the wily
533 * post_hacker collect core dumps from everyone.
540 const char *tmp = get_stats_option_name(optarg);
544 SetConfigOption(tmp, "true", PGC_POSTMASTER, PGC_S_ARGV);
548 write_stderr("%s: invalid argument for option -t: \"%s\"\n",
556 SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
565 ParseLongOption(optarg, &name, &value);
570 (errcode(ERRCODE_SYNTAX_ERROR),
571 errmsg("--%s requires a value",
575 (errcode(ERRCODE_SYNTAX_ERROR),
576 errmsg("-c %s requires a value",
580 SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
588 write_stderr("Try \"%s --help\" for more information.\n",
595 * Postmaster accepts no non-option switch arguments.
599 write_stderr("%s: invalid argument: \"%s\"\n",
600 progname, argv[optind]);
601 write_stderr("Try \"%s --help\" for more information.\n",
607 /* Locate executable backend before we change working directory */
608 if (find_other_exec(argv[0], "postgres", PG_VERSIONSTR,
609 postgres_exec_path) < 0)
611 (errmsg("%s: could not locate matching postgres executable",
616 * Locate the proper configuration files and data directory, and read
617 * postgresql.conf for the first time.
619 if (!SelectConfigFiles(userDoption, progname))
622 /* Verify that DataDir looks reasonable */
625 /* And switch working directory into it */
629 * Check for invalid combinations of GUC settings.
631 if (NBuffers < 2 * MaxBackends || NBuffers < 16)
634 * Do not accept -B so small that backends are likely to starve for
635 * lack of buffers. The specific choices here are somewhat arbitrary.
637 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);
641 if (ReservedBackends >= MaxBackends)
643 write_stderr("%s: superuser_reserved_connections must be less than max_connections\n", progname);
648 * Other one-time internal sanity checks can go here, if they are fast.
649 * (Put any slow processing further down, after postmaster.pid creation.)
651 if (!CheckDateTokenTables())
653 write_stderr("%s: invalid datetoken tables, please fix\n", progname);
658 * Now that we are done processing the postmaster arguments, reset
659 * getopt(3) library so that it will work correctly in subprocesses.
662 #ifdef HAVE_INT_OPTRESET
663 optreset = 1; /* some systems need this too */
666 /* For debugging: display postmaster environment */
668 extern char **environ;
672 (errmsg_internal("%s: PostmasterMain: initial environ dump:",
675 (errmsg_internal("-----------------------------------------")));
676 for (p = environ; *p; ++p)
678 (errmsg_internal("\t%s", *p)));
680 (errmsg_internal("-----------------------------------------")));
684 * Fork away from controlling terminal, if -S specified.
686 * Must do this before we grab any interlock files, else the interlocks
687 * will show the wrong PID.
693 * Create lockfile for data directory.
695 * We want to do this before we try to grab the input sockets, because the
696 * data directory interlock is more reliable than the socket-file
697 * interlock (thanks to whoever decided to put socket files in /tmp :-().
698 * For the same reason, it's best to grab the TCP socket(s) before the
701 CreateDataDirLockFile(true);
704 * If timezone is not set, determine what the OS uses. (In theory this
705 * should be done during GUC initialization, but because it can take as
706 * much as several seconds, we delay it until after we've created the
707 * postmaster.pid file. This prevents problems with boot scripts that
708 * expect the pidfile to appear quickly. Also, we avoid problems with
709 * trying to locate the timezone files too early in initialization.)
711 pg_timezone_initialize();
714 * Likewise, init timezone_abbreviations if not already set.
716 pg_timezone_abbrev_initialize();
719 * Initialize SSL library, if specified.
727 * process any libraries that should be preloaded at postmaster start
729 process_shared_preload_libraries();
732 * Remove old temporary files. At this point there can be no other
733 * Postgres processes running in this directory, so this should be safe.
738 * Establish input sockets.
740 for (i = 0; i < MAXLISTEN; i++)
741 ListenSocket[i] = -1;
750 /* Need a modifiable copy of ListenAddresses */
751 rawstring = pstrdup(ListenAddresses);
753 /* Parse string into list of identifiers */
754 if (!SplitIdentifierString(rawstring, ',', &elemlist))
756 /* syntax error in list */
758 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
759 errmsg("invalid list syntax for \"listen_addresses\"")));
764 char *curhost = (char *) lfirst(l);
766 if (strcmp(curhost, "*") == 0)
767 status = StreamServerPort(AF_UNSPEC, NULL,
768 (unsigned short) PostPortNumber,
770 ListenSocket, MAXLISTEN);
772 status = StreamServerPort(AF_UNSPEC, curhost,
773 (unsigned short) PostPortNumber,
775 ListenSocket, MAXLISTEN);
776 if (status == STATUS_OK)
780 (errmsg("could not create listen socket for \"%s\"",
784 if (!success && list_length(elemlist))
786 (errmsg("could not create any TCP/IP sockets")));
793 /* Register for Bonjour only if we opened TCP socket(s) */
794 if (ListenSocket[0] != -1 && bonjour_name != NULL)
796 DNSServiceRegistrationCreate(bonjour_name,
799 htons(PostPortNumber),
801 (DNSServiceRegistrationReply) reg_reply,
806 #ifdef HAVE_UNIX_SOCKETS
807 status = StreamServerPort(AF_UNIX, NULL,
808 (unsigned short) PostPortNumber,
810 ListenSocket, MAXLISTEN);
811 if (status != STATUS_OK)
813 (errmsg("could not create Unix-domain socket")));
817 * check that we have some socket to listen on
819 if (ListenSocket[0] == -1)
821 (errmsg("no socket created for listening")));
824 * Set up shared memory and semaphores.
826 reset_shared(PostPortNumber);
829 * Estimate number of openable files. This must happen after setting up
830 * semaphores, because on some platforms semaphores count as open files.
835 * Load configuration files for client authentication.
841 * Initialize the list of active backends.
843 BackendList = DLNewList();
848 * Initialize the child pid/HANDLE arrays for signal handling.
850 win32_childPIDArray = (pid_t *)
851 malloc(mul_size(NUM_BACKENDARRAY_ELEMS, sizeof(pid_t)));
852 win32_childHNDArray = (HANDLE *)
853 malloc(mul_size(NUM_BACKENDARRAY_ELEMS, sizeof(HANDLE)));
854 if (!win32_childPIDArray || !win32_childHNDArray)
856 (errcode(ERRCODE_OUT_OF_MEMORY),
857 errmsg("out of memory")));
860 * Set up a handle that child processes can use to check whether the
861 * postmaster is still running.
863 if (DuplicateHandle(GetCurrentProcess(),
869 DUPLICATE_SAME_ACCESS) == 0)
871 (errmsg_internal("could not duplicate postmaster handle: error code %d",
872 (int) GetLastError())));
876 * Record postmaster options. We delay this till now to avoid recording
877 * bogus options (eg, NBuffers too high for available memory).
879 if (!CreateOptsFile(argc, argv, my_exec_path))
883 write_nondefault_variables(PGC_POSTMASTER);
887 * Write the external PID file if requested
889 if (external_pid_file)
891 FILE *fpidfile = fopen(external_pid_file, "w");
895 fprintf(fpidfile, "%d\n", MyProcPid);
897 /* Should we remove the pid file on postmaster exit? */
900 write_stderr("%s: could not write external PID file \"%s\": %s\n",
901 progname, external_pid_file, strerror(errno));
905 * Set up signal handlers for the postmaster process.
907 * CAUTION: when changing this list, check for side-effects on the signal
908 * handling setup of child processes. See tcop/postgres.c,
909 * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/autovacuum.c,
910 * postmaster/pgarch.c, postmaster/pgstat.c, and postmaster/syslogger.c.
913 PG_SETMASK(&BlockSig);
915 pqsignal(SIGHUP, SIGHUP_handler); /* reread config file and have
916 * children do same */
917 pqsignal(SIGINT, pmdie); /* send SIGTERM and shut down */
918 pqsignal(SIGQUIT, pmdie); /* send SIGQUIT and die */
919 pqsignal(SIGTERM, pmdie); /* wait for children and shut down */
920 pqsignal(SIGALRM, SIG_IGN); /* ignored */
921 pqsignal(SIGPIPE, SIG_IGN); /* ignored */
922 pqsignal(SIGUSR1, sigusr1_handler); /* message from child process */
923 pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
924 pqsignal(SIGCHLD, reaper); /* handle child termination */
925 pqsignal(SIGTTIN, SIG_IGN); /* ignored */
926 pqsignal(SIGTTOU, SIG_IGN); /* ignored */
927 /* ignore SIGXFSZ, so that ulimit violations work like disk full */
929 pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
933 * If enabled, start up syslogger collection subprocess
935 SysLoggerPID = SysLogger_Start();
938 * Reset whereToSendOutput from DestDebug (its starting state) to
939 * DestNone. This stops ereport from sending log messages to stderr unless
940 * Log_destination permits. We don't do this until the postmaster is
941 * fully launched, since startup failures may as well be reported to
944 whereToSendOutput = DestNone;
947 * Initialize stats collection subsystem (this does NOT start the
948 * collector process!)
953 * Initialize the autovacuum subsystem (again, no process start yet)
958 * Remember postmaster startup time
960 PgStartTime = GetCurrentTimestamp();
963 * We're ready to rock and roll...
965 StartupPID = StartupDataBase();
967 status = ServerLoop();
970 * ServerLoop probably shouldn't ever return, but if it does, close down.
972 ExitPostmaster(status != STATUS_OK);
974 return 0; /* not reached */
979 * Validate the proposed data directory
984 char path[MAXPGPATH];
986 struct stat stat_buf;
990 if (stat(DataDir, &stat_buf) != 0)
994 (errcode_for_file_access(),
995 errmsg("data directory \"%s\" does not exist",
999 (errcode_for_file_access(),
1000 errmsg("could not read permissions of directory \"%s\": %m",
1005 * Check that the directory belongs to my userid; if not, reject.
1007 * This check is an essential part of the interlock that prevents two
1008 * postmasters from starting in the same directory (see CreateLockFile()).
1009 * Do not remove or weaken it.
1011 * XXX can we safely enable this check on Windows?
1013 #if !defined(WIN32) && !defined(__CYGWIN__)
1014 if (stat_buf.st_uid != geteuid())
1016 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1017 errmsg("data directory \"%s\" has wrong ownership",
1019 errhint("The server must be started by the user that owns the data directory.")));
1023 * Check if the directory has group or world access. If so, reject.
1025 * It would be possible to allow weaker constraints (for example, allow
1026 * group access) but we cannot make a general assumption that that is
1027 * okay; for example there are platforms where nearly all users
1028 * customarily belong to the same group. Perhaps this test should be
1031 * XXX temporarily suppress check when on Windows, because there may not
1032 * be proper support for Unix-y file permissions. Need to think of a
1033 * reasonable check to apply on Windows.
1035 #if !defined(WIN32) && !defined(__CYGWIN__)
1036 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
1038 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1039 errmsg("data directory \"%s\" has group or world access",
1041 errdetail("Permissions should be u=rwx (0700).")));
1044 /* Look for PG_VERSION before looking for pg_control */
1045 ValidatePgVersion(DataDir);
1047 snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1049 fp = AllocateFile(path, PG_BINARY_R);
1052 write_stderr("%s: could not find the database system\n"
1053 "Expected to find it in the directory \"%s\",\n"
1054 "but could not open file \"%s\": %s\n",
1055 progname, DataDir, path, strerror(errno));
1065 * empty callback function for DNSServiceRegistrationCreate()
1068 reg_reply(DNSServiceRegistrationReplyErrorType errorCode, void *context)
1072 #endif /* USE_BONJOUR */
1076 * Fork away from the controlling terminal (-S option)
1085 pid = fork_process();
1086 if (pid == (pid_t) -1)
1088 write_stderr("%s: could not fork background process: %s\n",
1089 progname, strerror(errno));
1094 /* Parent should just exit, without doing any atexit cleanup */
1098 MyProcPid = PostmasterPid = getpid(); /* reset PID vars to child */
1100 /* GH: If there's no setsid(), we hopefully don't need silent mode.
1101 * Until there's a better solution.
1106 write_stderr("%s: could not dissociate from controlling TTY: %s\n",
1107 progname, strerror(errno));
1111 i = open(NULL_DEV, O_RDWR, 0);
1118 elog(FATAL, "SilentMode not supported under WIN32");
1124 * Main idle loop of postmaster
1133 struct timeval earlier,
1136 gettimeofday(&earlier, NULL);
1137 last_touch_time = time(NULL);
1139 nSockets = initMasks(&readmask);
1145 struct timeval timeout;
1150 * Wait for something to happen.
1152 * We wait at most one minute, to ensure that the other background
1153 * tasks handled below get done even when no requests are arriving.
1155 memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
1157 timeout.tv_sec = 60;
1158 timeout.tv_usec = 0;
1160 PG_SETMASK(&UnBlockSig);
1162 selres = select(nSockets, &rmask, NULL, NULL, &timeout);
1165 * Block all signals until we wait again. (This makes it safe for our
1166 * signal handlers to do nontrivial work.)
1168 PG_SETMASK(&BlockSig);
1172 if (errno != EINTR && errno != EWOULDBLOCK)
1175 (errcode_for_socket_access(),
1176 errmsg("select() failed in postmaster: %m")));
1177 return STATUS_ERROR;
1182 * New connection pending on any of our sockets? If so, fork a child
1183 * process to deal with it.
1188 * Select a random seed at the time of first receiving a request.
1190 while (random_seed == 0)
1192 gettimeofday(&later, NULL);
1195 * We are not sure how much precision is in tv_usec, so we
1196 * swap the high and low 16 bits of 'later' and XOR them with
1197 * 'earlier'. On the off chance that the result is 0, we loop
1200 random_seed = earlier.tv_usec ^
1201 ((later.tv_usec << 16) |
1202 ((later.tv_usec >> 16) & 0xffff));
1205 for (i = 0; i < MAXLISTEN; i++)
1207 if (ListenSocket[i] == -1)
1209 if (FD_ISSET(ListenSocket[i], &rmask))
1211 port = ConnCreate(ListenSocket[i]);
1214 BackendStartup(port);
1217 * We no longer need the open socket or port structure
1220 StreamClose(port->sock);
1227 /* If we have lost the system logger, try to start a new one */
1228 if (SysLoggerPID == 0 && Redirect_stderr)
1229 SysLoggerPID = SysLogger_Start();
1232 * If no background writer process is running, and we are not in a
1233 * state that prevents it, start one. It doesn't matter if this
1234 * fails, we'll just try again later.
1236 if (BgWriterPID == 0 && StartupPID == 0 && !FatalError)
1238 BgWriterPID = StartBackgroundWriter();
1239 /* If shutdown is pending, set it going */
1240 if (Shutdown > NoShutdown && BgWriterPID != 0)
1241 signal_child(BgWriterPID, SIGUSR2);
1244 /* If we have lost the autovacuum launcher, try to start a new one */
1245 if ((AutoVacuumingActive() || start_autovac_launcher) && AutoVacPID == 0 &&
1246 StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
1248 AutoVacPID = StartAutoVacLauncher();
1249 if (AutoVacPID != 0)
1250 start_autovac_launcher = false; /* signal successfully processed */
1253 /* If we have lost the archiver, try to start a new one */
1254 if (XLogArchivingActive() && PgArchPID == 0 &&
1255 StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
1256 PgArchPID = pgarch_start();
1258 /* If we have lost the stats collector, try to start a new one */
1259 if (PgStatPID == 0 &&
1260 StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
1261 PgStatPID = pgstat_start();
1264 * Touch the socket and lock file every 58 minutes, to ensure that
1265 * they are not removed by overzealous /tmp-cleaning tasks. We assume
1266 * no one runs cleaners with cutoff times of less than an hour ...
1269 if (now - last_touch_time >= 58 * SECS_PER_MINUTE)
1272 TouchSocketLockFile();
1273 last_touch_time = now;
1280 * Initialise the masks for select() for the ports we are listening on.
1281 * Return the number of sockets to listen on.
1284 initMasks(fd_set *rmask)
1291 for (i = 0; i < MAXLISTEN; i++)
1293 int fd = ListenSocket[i];
1307 * Read the startup packet and do something according to it.
1309 * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
1310 * not return at all.
1312 * (Note that ereport(FATAL) stuff is sent to the client, so only use it
1313 * if that's what you want. Return STATUS_ERROR if you don't want to
1314 * send anything to the client, which would typically be appropriate
1315 * if we detect a communications failure.)
1318 ProcessStartupPacket(Port *port, bool SSLdone)
1322 ProtocolVersion proto;
1323 MemoryContext oldcontext;
1325 if (pq_getbytes((char *) &len, 4) == EOF)
1328 * EOF after SSLdone probably means the client didn't like our
1329 * response to NEGOTIATE_SSL_CODE. That's not an error condition, so
1330 * don't clutter the log with a complaint.
1334 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1335 errmsg("incomplete startup packet")));
1336 return STATUS_ERROR;
1342 if (len < (int32) sizeof(ProtocolVersion) ||
1343 len > MAX_STARTUP_PACKET_LENGTH)
1346 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1347 errmsg("invalid length of startup packet")));
1348 return STATUS_ERROR;
1352 * Allocate at least the size of an old-style startup packet, plus one
1353 * extra byte, and make sure all are zeroes. This ensures we will have
1354 * null termination of all strings, in both fixed- and variable-length
1357 if (len <= (int32) sizeof(StartupPacket))
1358 buf = palloc0(sizeof(StartupPacket) + 1);
1360 buf = palloc0(len + 1);
1362 if (pq_getbytes(buf, len) == EOF)
1365 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1366 errmsg("incomplete startup packet")));
1367 return STATUS_ERROR;
1371 * The first field is either a protocol version number or a special
1374 port->proto = proto = ntohl(*((ProtocolVersion *) buf));
1376 if (proto == CANCEL_REQUEST_CODE)
1378 processCancelRequest(port, buf);
1379 return 127; /* XXX */
1382 if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
1387 /* No SSL when disabled or on Unix sockets */
1388 if (!EnableSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
1391 SSLok = 'S'; /* Support for SSL */
1393 SSLok = 'N'; /* No support for SSL */
1397 if (send(port->sock, &SSLok, 1, 0) != 1)
1400 goto retry1; /* if interrupted, just retry */
1402 (errcode_for_socket_access(),
1403 errmsg("failed to send SSL negotiation response: %m")));
1404 return STATUS_ERROR; /* close the connection */
1408 if (SSLok == 'S' && secure_open_server(port) == -1)
1409 return STATUS_ERROR;
1411 /* regular startup packet, cancel, etc packet should follow... */
1412 /* but not another SSL negotiation request */
1413 return ProcessStartupPacket(port, true);
1416 /* Could add additional special packet types here */
1419 * Set FrontendProtocol now so that ereport() knows what format to send if
1420 * we fail during startup.
1422 FrontendProtocol = proto;
1424 /* Check we can handle the protocol the frontend is using. */
1426 if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
1427 PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
1428 (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
1429 PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
1431 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1432 errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
1433 PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
1434 PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST),
1435 PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST),
1436 PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))));
1439 * Now fetch parameters out of startup packet and save them into the Port
1440 * structure. All data structures attached to the Port struct must be
1441 * allocated in TopMemoryContext so that they won't disappear when we pass
1442 * them to PostgresMain (see BackendRun). We need not worry about leaking
1443 * this storage on failure, since we aren't in the postmaster process
1446 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1448 if (PG_PROTOCOL_MAJOR(proto) >= 3)
1450 int32 offset = sizeof(ProtocolVersion);
1453 * Scan packet body for name/option pairs. We can assume any string
1454 * beginning within the packet body is null-terminated, thanks to
1455 * zeroing extra byte above.
1457 port->guc_options = NIL;
1459 while (offset < len)
1461 char *nameptr = ((char *) buf) + offset;
1465 if (*nameptr == '\0')
1466 break; /* found packet terminator */
1467 valoffset = offset + strlen(nameptr) + 1;
1468 if (valoffset >= len)
1469 break; /* missing value, will complain below */
1470 valptr = ((char *) buf) + valoffset;
1472 if (strcmp(nameptr, "database") == 0)
1473 port->database_name = pstrdup(valptr);
1474 else if (strcmp(nameptr, "user") == 0)
1475 port->user_name = pstrdup(valptr);
1476 else if (strcmp(nameptr, "options") == 0)
1477 port->cmdline_options = pstrdup(valptr);
1480 /* Assume it's a generic GUC option */
1481 port->guc_options = lappend(port->guc_options,
1483 port->guc_options = lappend(port->guc_options,
1486 offset = valoffset + strlen(valptr) + 1;
1490 * If we didn't find a packet terminator exactly at the end of the
1491 * given packet length, complain.
1493 if (offset != len - 1)
1495 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1496 errmsg("invalid startup packet layout: expected terminator as last byte")));
1501 * Get the parameters from the old-style, fixed-width-fields startup
1502 * packet as C strings. The packet destination was cleared first so a
1503 * short packet has zeros silently added. We have to be prepared to
1504 * truncate the pstrdup result for oversize fields, though.
1506 StartupPacket *packet = (StartupPacket *) buf;
1508 port->database_name = pstrdup(packet->database);
1509 if (strlen(port->database_name) > sizeof(packet->database))
1510 port->database_name[sizeof(packet->database)] = '\0';
1511 port->user_name = pstrdup(packet->user);
1512 if (strlen(port->user_name) > sizeof(packet->user))
1513 port->user_name[sizeof(packet->user)] = '\0';
1514 port->cmdline_options = pstrdup(packet->options);
1515 if (strlen(port->cmdline_options) > sizeof(packet->options))
1516 port->cmdline_options[sizeof(packet->options)] = '\0';
1517 port->guc_options = NIL;
1520 /* Check a user name was given. */
1521 if (port->user_name == NULL || port->user_name[0] == '\0')
1523 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1524 errmsg("no PostgreSQL user name specified in startup packet")));
1526 /* The database defaults to the user name. */
1527 if (port->database_name == NULL || port->database_name[0] == '\0')
1528 port->database_name = pstrdup(port->user_name);
1530 if (Db_user_namespace)
1533 * If user@, it is a global user, remove '@'. We only want to do this
1534 * if there is an '@' at the end and no earlier in the user string or
1535 * they may fake as a local user of another database attaching to this
1538 if (strchr(port->user_name, '@') ==
1539 port->user_name + strlen(port->user_name) - 1)
1540 *strchr(port->user_name, '@') = '\0';
1543 /* Append '@' and dbname */
1546 db_user = palloc(strlen(port->user_name) +
1547 strlen(port->database_name) + 2);
1548 sprintf(db_user, "%s@%s", port->user_name, port->database_name);
1549 port->user_name = db_user;
1554 * Truncate given database and user names to length of a Postgres name.
1555 * This avoids lookup failures when overlength names are given.
1557 if (strlen(port->database_name) >= NAMEDATALEN)
1558 port->database_name[NAMEDATALEN - 1] = '\0';
1559 if (strlen(port->user_name) >= NAMEDATALEN)
1560 port->user_name[NAMEDATALEN - 1] = '\0';
1563 * Done putting stuff in TopMemoryContext.
1565 MemoryContextSwitchTo(oldcontext);
1568 * If we're going to reject the connection due to database state, say so
1569 * now instead of wasting cycles on an authentication exchange. (This also
1570 * allows a pg_ping utility to be written.)
1572 switch (port->canAcceptConnections)
1576 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1577 errmsg("the database system is starting up")));
1581 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1582 errmsg("the database system is shutting down")));
1586 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1587 errmsg("the database system is in recovery mode")));
1591 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
1592 errmsg("sorry, too many clients already")));
1604 * The client has sent a cancel request packet, not a normal
1605 * start-a-new-connection packet. Perform the necessary processing.
1606 * Nothing is sent back to the client.
1609 processCancelRequest(Port *port, void *pkt)
1611 CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
1613 long cancelAuthCode;
1616 #ifndef EXEC_BACKEND
1622 backendPID = (int) ntohl(canc->backendPID);
1623 cancelAuthCode = (long) ntohl(canc->cancelAuthCode);
1626 * See if we have a matching backend. In the EXEC_BACKEND case, we can no
1627 * longer access the postmaster's own backend list, and must rely on the
1628 * duplicate array in shared memory.
1630 #ifndef EXEC_BACKEND
1631 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
1633 bp = (Backend *) DLE_VAL(curr);
1635 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
1637 bp = (Backend *) &ShmemBackendArray[i];
1639 if (bp->pid == backendPID)
1641 if (bp->cancel_key == cancelAuthCode)
1643 /* Found a match; signal that backend to cancel current op */
1645 (errmsg_internal("processing cancel request: sending SIGINT to process %d",
1647 signal_child(bp->pid, SIGINT);
1650 /* Right PID, wrong key: no way, Jose */
1652 (errmsg_internal("bad key in cancel request for process %d",
1658 /* No matching backend */
1660 (errmsg_internal("bad pid in cancel request for process %d",
1665 * canAcceptConnections --- check to see if database state allows connections.
1667 static enum CAC_state
1668 canAcceptConnections(void)
1670 /* Can't start backends when in startup/shutdown/recovery state. */
1671 if (Shutdown > NoShutdown)
1672 return CAC_SHUTDOWN;
1676 return CAC_RECOVERY;
1679 * Don't start too many children.
1681 * We allow more connections than we can have backends here because some
1682 * might still be authenticating; they might fail auth, or some existing
1683 * backend might exit before the auth cycle is completed. The exact
1684 * MaxBackends limit is enforced when a new backend tries to join the
1685 * shared-inval backend array.
1687 if (CountChildren() >= 2 * MaxBackends)
1695 * ConnCreate -- create a local connection data structure
1698 ConnCreate(int serverFd)
1702 if (!(port = (Port *) calloc(1, sizeof(Port))))
1705 (errcode(ERRCODE_OUT_OF_MEMORY),
1706 errmsg("out of memory")));
1710 if (StreamConnection(serverFd, port) != STATUS_OK)
1712 if (port->sock >= 0)
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")));
1876 /* autovacuum workers are shut down immediately */
1877 if (DLGetHead(BackendList))
1878 SignalSomeChildren(SIGINT, true);
1880 if (DLGetHead(BackendList))
1881 break; /* let reaper() handle this */
1884 * No children left. Begin shutdown of data base system.
1886 if (StartupPID != 0 || FatalError)
1887 break; /* let reaper() handle this */
1888 /* Start the bgwriter if not running */
1889 if (BgWriterPID == 0)
1890 BgWriterPID = StartBackgroundWriter();
1891 /* And tell it to shut down */
1892 if (BgWriterPID != 0)
1893 signal_child(BgWriterPID, SIGUSR2);
1894 /* Tell pgarch to shut down too; nothing left for it to do */
1896 signal_child(PgArchPID, SIGQUIT);
1897 /* Tell pgstat to shut down too; nothing left for it to do */
1899 signal_child(PgStatPID, SIGQUIT);
1900 /* Tell autovac launcher to shut down too */
1901 if (AutoVacPID != 0)
1902 signal_child(AutoVacPID, SIGTERM);
1910 * Abort all children with SIGTERM (rollback active transactions
1911 * and exit) and shut down when they are gone.
1913 if (Shutdown >= FastShutdown)
1915 Shutdown = FastShutdown;
1917 (errmsg("received fast shutdown request")));
1919 if (DLGetHead(BackendList))
1924 (errmsg("aborting any active transactions")));
1925 SignalChildren(SIGTERM);
1926 /* reaper() does the rest */
1932 * No children left. Begin shutdown of data base system.
1934 * Note: if we previously got SIGTERM then we may send SIGUSR2 to
1935 * the bgwriter a second time here. This should be harmless.
1937 if (StartupPID != 0)
1939 signal_child(StartupPID, SIGTERM);
1940 break; /* let reaper() do the rest */
1943 break; /* let reaper() handle this case */
1944 /* Start the bgwriter if not running */
1945 if (BgWriterPID == 0)
1946 BgWriterPID = StartBackgroundWriter();
1947 /* And tell it to shut down */
1948 if (BgWriterPID != 0)
1949 signal_child(BgWriterPID, SIGUSR2);
1950 /* Tell pgarch to shut down too; nothing left for it to do */
1952 signal_child(PgArchPID, SIGQUIT);
1953 /* Tell pgstat to shut down too; nothing left for it to do */
1955 signal_child(PgStatPID, SIGQUIT);
1956 /* Tell autovac launcher to shut down too */
1957 if (AutoVacPID != 0)
1958 signal_child(AutoVacPID, SIGTERM);
1964 * Immediate Shutdown:
1966 * abort all children with SIGQUIT and exit without attempt to
1967 * properly shut down data base system.
1970 (errmsg("received immediate shutdown request")));
1971 if (StartupPID != 0)
1972 signal_child(StartupPID, SIGQUIT);
1973 if (BgWriterPID != 0)
1974 signal_child(BgWriterPID, SIGQUIT);
1975 if (AutoVacPID != 0)
1976 signal_child(AutoVacPID, SIGQUIT);
1978 signal_child(PgArchPID, SIGQUIT);
1980 signal_child(PgStatPID, SIGQUIT);
1981 if (DLGetHead(BackendList))
1982 SignalChildren(SIGQUIT);
1987 PG_SETMASK(&UnBlockSig);
1993 * Reaper -- signal handler to cleanup after a backend (child) dies.
1998 int save_errno = errno;
2001 int status; /* backend exit status */
2004 union wait status; /* backend exit status */
2008 int pid; /* process id of dead backend */
2010 PG_SETMASK(&BlockSig);
2013 (errmsg_internal("reaping dead processes")));
2015 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
2017 exitstatus = status;
2020 while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
2022 exitstatus = status.w_status;
2024 while ((pid = win32_waitpid(&exitstatus)) > 0)
2027 * We need to do this here, and not in CleanupBackend, since this is
2028 * to be called on all children when we are done with them. Could move
2029 * to LogChildExit, but that seems like asking for future trouble...
2031 win32_RemoveChild(pid);
2033 #endif /* HAVE_WAITPID */
2036 * Check if this child was a startup process.
2038 if (StartupPID != 0 && pid == StartupPID)
2041 /* Note: FATAL exit of startup is treated as catastrophic */
2042 if (!EXIT_STATUS_0(exitstatus))
2044 LogChildExit(LOG, _("startup process"),
2047 (errmsg("aborting startup due to startup process failure")));
2052 * Startup succeeded - we are done with system startup or
2058 * Load the flat authorization file into postmaster's cache. The
2059 * startup process has recomputed this from the database contents,
2060 * so we wait till it finishes before loading it.
2065 * Crank up the background writer. It doesn't matter if this
2066 * fails, we'll just try again later.
2068 Assert(BgWriterPID == 0);
2069 BgWriterPID = StartBackgroundWriter();
2072 * Go to shutdown mode if a shutdown request was pending.
2073 * Otherwise, try to start the archiver, stats collector and
2074 * autovacuum launcher.
2076 if (Shutdown > NoShutdown && BgWriterPID != 0)
2077 signal_child(BgWriterPID, SIGUSR2);
2078 else if (Shutdown == NoShutdown)
2080 if (XLogArchivingActive() && PgArchPID == 0)
2081 PgArchPID = pgarch_start();
2083 PgStatPID = pgstat_start();
2084 if (AutoVacuumingActive() && AutoVacPID == 0)
2085 AutoVacPID = StartAutoVacLauncher();
2087 /* at this point we are really open for business */
2089 (errmsg("database system is ready to accept connections")));
2096 * Was it the bgwriter?
2098 if (BgWriterPID != 0 && pid == BgWriterPID)
2101 if (EXIT_STATUS_0(exitstatus) &&
2102 Shutdown > NoShutdown && !FatalError &&
2103 !DLGetHead(BackendList) && AutoVacPID == 0)
2106 * Normal postmaster exit is here: we've seen normal exit of
2107 * the bgwriter after it's been told to shut down. We expect
2108 * that it wrote a shutdown checkpoint. (If for some reason
2109 * it didn't, recovery will occur on next postmaster start.)
2111 * Note: we do not wait around for exit of the archiver or
2112 * stats processes. They've been sent SIGQUIT by this point,
2113 * and in any case contain logic to commit hara-kiri if they
2114 * notice the postmaster is gone.
2120 * Any unexpected exit of the bgwriter (including FATAL exit)
2121 * is treated as a crash.
2123 HandleChildCrash(pid, exitstatus,
2124 _("background writer process"));
2127 * If the bgwriter crashed while trying to write the shutdown
2128 * checkpoint, we may as well just stop here; any recovery
2129 * required will happen on next postmaster start.
2131 if (Shutdown > NoShutdown &&
2132 !DLGetHead(BackendList) && AutoVacPID == 0)
2135 (errmsg("abnormal database system shutdown")));
2139 /* Else, proceed as in normal crash recovery */
2144 * Was it the autovacuum launcher? Normal exit can be ignored; we'll
2145 * start a new one at the next iteration of the postmaster's main loop,
2146 * if necessary. Any other exit condition is treated as a crash.
2148 if (AutoVacPID != 0 && pid == AutoVacPID)
2151 if (!EXIT_STATUS_0(exitstatus))
2152 HandleChildCrash(pid, exitstatus,
2153 _("autovacuum launcher process"));
2158 * Was it the archiver? If so, just try to start a new one; no need
2159 * to force reset of the rest of the system. (If fail, we'll try
2160 * again in future cycles of the main loop.)
2162 if (PgArchPID != 0 && pid == PgArchPID)
2165 if (!EXIT_STATUS_0(exitstatus))
2166 LogChildExit(LOG, _("archiver process"),
2168 if (XLogArchivingActive() &&
2169 StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
2170 PgArchPID = pgarch_start();
2175 * Was it the statistics collector? If so, just try to start a new
2176 * one; no need to force reset of the rest of the system. (If fail,
2177 * we'll try again in future cycles of the main loop.)
2179 if (PgStatPID != 0 && pid == PgStatPID)
2182 if (!EXIT_STATUS_0(exitstatus))
2183 LogChildExit(LOG, _("statistics collector process"),
2185 if (StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
2186 PgStatPID = pgstat_start();
2190 /* Was it the system logger? try to start a new one */
2191 if (SysLoggerPID != 0 && pid == SysLoggerPID)
2194 /* for safety's sake, launch new logger *first* */
2195 SysLoggerPID = SysLogger_Start();
2196 if (!EXIT_STATUS_0(exitstatus))
2197 LogChildExit(LOG, _("system logger process"),
2203 * Else do standard backend child cleanup.
2205 CleanupBackend(pid, exitstatus);
2206 } /* loop over pending child-death reports */
2211 * Wait for all important children to exit, then reset shmem and
2212 * StartupDataBase. (We can ignore the archiver and stats processes
2213 * here since they are not connected to shmem.)
2215 if (DLGetHead(BackendList) || StartupPID != 0 || BgWriterPID != 0 ||
2219 (errmsg("all server processes terminated; reinitializing")));
2222 reset_shared(PostPortNumber);
2224 StartupPID = StartupDataBase();
2229 if (Shutdown > NoShutdown)
2231 if (DLGetHead(BackendList) || StartupPID != 0)
2233 /* Start the bgwriter if not running */
2234 if (BgWriterPID == 0)
2235 BgWriterPID = StartBackgroundWriter();
2236 /* And tell it to shut down */
2237 if (BgWriterPID != 0)
2238 signal_child(BgWriterPID, SIGUSR2);
2239 /* Tell pgarch to shut down too; nothing left for it to do */
2241 signal_child(PgArchPID, SIGQUIT);
2242 /* Tell pgstat to shut down too; nothing left for it to do */
2244 signal_child(PgStatPID, SIGQUIT);
2245 /* Tell autovac launcher to shut down too */
2246 if (AutoVacPID != 0)
2247 signal_child(AutoVacPID, SIGTERM);
2251 PG_SETMASK(&UnBlockSig);
2258 * CleanupBackend -- cleanup after terminated backend.
2260 * Remove all local state associated with backend.
2263 CleanupBackend(int pid,
2264 int exitstatus) /* child's exit status. */
2268 LogChildExit(DEBUG2, _("server process"), pid, exitstatus);
2271 * If a backend dies in an ugly way then we must signal all other backends
2272 * to quickdie. If exit status is zero (normal) or one (FATAL exit), we
2273 * assume everything is all right and simply remove the backend from the
2274 * active backend list.
2276 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2278 HandleChildCrash(pid, exitstatus, _("server process"));
2282 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2284 Backend *bp = (Backend *) DLE_VAL(curr);
2292 ShmemBackendArrayRemove(pid);
2300 * HandleChildCrash -- cleanup after failed backend, bgwriter, or autovacuum.
2302 * The objectives here are to clean up our local state about the child
2303 * process, and to signal all other remaining children to quickdie.
2306 HandleChildCrash(int pid, int exitstatus, const char *procname)
2313 * Make log entry unless there was a previous crash (if so, nonzero exit
2314 * status is to be expected in SIGQUIT response; don't clutter log)
2318 LogChildExit(LOG, procname, pid, exitstatus);
2320 (errmsg("terminating any other active server processes")));
2323 /* Process regular backends */
2324 for (curr = DLGetHead(BackendList); curr; curr = next)
2326 next = DLGetSucc(curr);
2327 bp = (Backend *) DLE_VAL(curr);
2331 * Found entry for freshly-dead backend, so remove it.
2337 ShmemBackendArrayRemove(pid);
2339 /* Keep looping so we can signal remaining backends */
2344 * This backend is still alive. Unless we did so already, tell it
2345 * to commit hara-kiri.
2347 * SIGQUIT is the special signal that says exit without proc_exit
2348 * and let the user know what's going on. But if SendStop is set
2349 * (-s on command line), then we send SIGSTOP instead, so that we
2350 * can get core dumps from all backends by hand.
2355 (errmsg_internal("sending %s to process %d",
2356 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2358 signal_child(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
2363 /* Take care of the bgwriter too */
2364 if (pid == BgWriterPID)
2366 else if (BgWriterPID != 0 && !FatalError)
2369 (errmsg_internal("sending %s to process %d",
2370 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2371 (int) BgWriterPID)));
2372 signal_child(BgWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
2375 /* Take care of the autovacuum launcher too */
2376 if (pid == AutoVacPID)
2378 else if (AutoVacPID != 0 && !FatalError)
2381 (errmsg_internal("sending %s to process %d",
2382 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2383 (int) AutoVacPID)));
2384 signal_child(AutoVacPID, (SendStop ? SIGSTOP : SIGQUIT));
2387 /* Force a power-cycle of the pgarch process too */
2388 /* (Shouldn't be necessary, but just for luck) */
2389 if (PgArchPID != 0 && !FatalError)
2392 (errmsg_internal("sending %s to process %d",
2395 signal_child(PgArchPID, SIGQUIT);
2398 /* Force a power-cycle of the pgstat process too */
2399 /* (Shouldn't be necessary, but just for luck) */
2400 if (PgStatPID != 0 && !FatalError)
2403 (errmsg_internal("sending %s to process %d",
2406 signal_child(PgStatPID, SIGQUIT);
2409 /* We do NOT restart the syslogger */
2415 * Log the death of a child process.
2418 LogChildExit(int lev, const char *procname, int pid, int exitstatus)
2420 if (WIFEXITED(exitstatus))
2424 translator: %s is a noun phrase describing a child process, such as
2426 (errmsg("%s (PID %d) exited with exit code %d",
2427 procname, pid, WEXITSTATUS(exitstatus))));
2428 else if (WIFSIGNALED(exitstatus))
2433 translator: %s is a noun phrase describing a child process, such as
2435 (errmsg("%s (PID %d) was terminated by exception 0x%X",
2436 procname, pid, WTERMSIG(exitstatus)),
2437 errhint("See C include file \"ntstatus.h\" for a description of the hex value.")));
2438 #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST
2442 translator: %s is a noun phrase describing a child process, such as
2444 (errmsg("%s (PID %d) was terminated by signal %d: %s",
2445 procname, pid, WTERMSIG(exitstatus),
2446 WTERMSIG(exitstatus) < NSIG ?
2447 sys_siglist[WTERMSIG(exitstatus)] : "(unknown)")));
2452 translator: %s is a noun phrase describing a child process, such as
2454 (errmsg("%s (PID %d) was terminated by signal %d",
2455 procname, pid, WTERMSIG(exitstatus))));
2461 translator: %s is a noun phrase describing a child process, such as
2463 (errmsg("%s (PID %d) exited with unrecognized status %d",
2464 procname, pid, exitstatus)));
2468 * Send a signal to a postmaster child process
2470 * On systems that have setsid(), each child process sets itself up as a
2471 * process group leader. For signals that are generally interpreted in the
2472 * appropriate fashion, we signal the entire process group not just the
2473 * direct child process. This allows us to, for example, SIGQUIT a blocked
2474 * archive_recovery script, or SIGINT a script being run by a backend via
2477 * There is a race condition for recently-forked children: they might not
2478 * have executed setsid() yet. So we signal the child directly as well as
2479 * the group. We assume such a child will handle the signal before trying
2480 * to spawn any grandchild processes. We also assume that signaling the
2481 * child twice will not cause any problems.
2484 signal_child(pid_t pid, int signal)
2486 if (kill(pid, signal) < 0)
2487 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
2495 if (kill(-pid, signal) < 0)
2496 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) (-pid), signal);
2505 * Send a signal to all backend children, including autovacuum workers (but NOT
2506 * special children).
2509 SignalChildren(int signal)
2511 SignalSomeChildren(signal, false);
2515 * Send a signal to all backend children, including autovacuum workers (but NOT
2516 * special children). If only_autovac is TRUE, only the autovacuum worker
2517 * processes are signalled.
2520 SignalSomeChildren(int signal, bool only_autovac)
2524 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2526 Backend *bp = (Backend *) DLE_VAL(curr);
2528 if (only_autovac && !bp->is_autovacuum)
2532 (errmsg_internal("sending signal %d to process %d",
2533 signal, (int) bp->pid)));
2534 signal_child(bp->pid, signal);
2539 * BackendStartup -- start backend process
2541 * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
2543 * Note: if you change this code, also consider StartAutovacuumWorker.
2546 BackendStartup(Port *port)
2548 Backend *bn; /* for backend cleanup */
2552 * Compute the cancel key that will be assigned to this backend. The
2553 * backend will have its own copy in the forked-off process' value of
2554 * MyCancelKey, so that it can transmit the key to the frontend.
2556 MyCancelKey = PostmasterRandom();
2559 * Make room for backend data structure. Better before the fork() so we
2560 * can handle failure cleanly.
2562 bn = (Backend *) malloc(sizeof(Backend));
2566 (errcode(ERRCODE_OUT_OF_MEMORY),
2567 errmsg("out of memory")));
2568 return STATUS_ERROR;
2571 /* Pass down canAcceptConnections state (kluge for EXEC_BACKEND case) */
2572 port->canAcceptConnections = canAcceptConnections();
2575 pid = backend_forkexec(port);
2576 #else /* !EXEC_BACKEND */
2577 pid = fork_process();
2578 if (pid == 0) /* child */
2583 * Let's clean up ourselves as the postmaster child, and close the
2584 * postmaster's listen sockets. (In EXEC_BACKEND case this is all
2585 * done in SubPostmasterMain.)
2587 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
2589 MyProcPid = getpid(); /* reset MyProcPid */
2591 /* We don't want the postmaster's proc_exit() handlers */
2594 /* Close the postmaster's sockets */
2595 ClosePostmasterPorts(false);
2597 /* Perform additional initialization and client authentication */
2598 BackendInitialize(port);
2600 /* And run the backend */
2601 proc_exit(BackendRun(port));
2603 #endif /* EXEC_BACKEND */
2607 /* in parent, fork failed */
2608 int save_errno = errno;
2613 (errmsg("could not fork new process for connection: %m")));
2614 report_fork_failure_to_client(port, save_errno);
2615 return STATUS_ERROR;
2618 /* in parent, successful fork */
2620 (errmsg_internal("forked new backend, pid=%d socket=%d",
2621 (int) pid, port->sock)));
2624 * Everything's been successful, it's safe to add this backend to our list
2628 bn->cancel_key = MyCancelKey;
2629 DLAddHead(BackendList, DLNewElem(bn));
2631 ShmemBackendArrayAdd(bn);
2638 * Try to report backend fork() failure to client before we close the
2639 * connection. Since we do not care to risk blocking the postmaster on
2640 * this connection, we set the connection to non-blocking and try only once.
2642 * This is grungy special-purpose code; we cannot use backend libpq since
2643 * it's not up and running.
2646 report_fork_failure_to_client(Port *port, int errnum)
2651 /* Format the error message packet (always V2 protocol) */
2652 snprintf(buffer, sizeof(buffer), "E%s%s\n",
2653 _("could not fork new process for connection: "),
2656 /* Set port to non-blocking. Don't do send() if this fails */
2657 if (!pg_set_noblock(port->sock))
2660 /* We'll retry after EINTR, but ignore all other failures */
2663 rc = send(port->sock, buffer, strlen(buffer) + 1, 0);
2664 } while (rc < 0 && errno == EINTR);
2669 * split_opts -- split a string of options and append it to an argv array
2671 * NB: the string is destructively modified!
2673 * Since no current POSTGRES arguments require any quoting characters,
2674 * we can use the simple-minded tactic of assuming each set of space-
2675 * delimited characters is a separate argv element.
2677 * If you don't like that, well, we *used* to pass the whole option string
2678 * as ONE argument to execl(), which was even less intelligent...
2681 split_opts(char **argv, int *argcp, char *s)
2685 while (isspace((unsigned char) *s))
2689 argv[(*argcp)++] = s;
2690 while (*s && !isspace((unsigned char) *s))
2699 * BackendInitialize -- initialize an interactive (postmaster-child)
2700 * backend process, and perform client authentication.
2702 * returns: nothing. Will not return at all if there's any failure.
2704 * Note: this code does not depend on having any access to shared memory.
2705 * In the EXEC_BACKEND case, we are physically attached to shared memory
2706 * but have not yet set up most of our local pointers to shmem structures.
2709 BackendInitialize(Port *port)
2712 char remote_host[NI_MAXHOST];
2713 char remote_port[NI_MAXSERV];
2714 char remote_ps_data[NI_MAXHOST];
2716 /* Save port etc. for ps status */
2720 * PreAuthDelay is a debugging aid for investigating problems in the
2721 * authentication cycle: it can be set in postgresql.conf to allow time to
2722 * attach to the newly-forked backend with a debugger. (See also the -W
2723 * backend switch, which we allow clients to pass through PGOPTIONS, but
2724 * it is not honored until after authentication.)
2726 if (PreAuthDelay > 0)
2727 pg_usleep(PreAuthDelay * 1000000L);
2729 ClientAuthInProgress = true; /* limit visibility of log messages */
2731 /* save process start time */
2732 port->SessionStartTime = GetCurrentTimestamp();
2733 port->session_start = timestamptz_to_time_t(port->SessionStartTime);
2735 /* set these to empty in case they are needed before we set them up */
2736 port->remote_host = "";
2737 port->remote_port = "";
2740 * Initialize libpq and enable reporting of ereport errors to the client.
2741 * Must do this now because authentication uses libpq to send messages.
2743 pq_init(); /* initialize libpq to talk to client */
2744 whereToSendOutput = DestRemote; /* now safe to ereport to client */
2747 * If possible, make this process a group leader, so that the postmaster
2748 * can signal any child processes too. (We do this now on the off chance
2749 * that something might spawn a child process during authentication.)
2753 elog(FATAL, "setsid() failed: %m");
2757 * We arrange for a simple exit(1) if we receive SIGTERM or SIGQUIT during
2758 * any client authentication related communication. Otherwise the
2759 * postmaster cannot shutdown the database FAST or IMMED cleanly if a
2760 * buggy client blocks a backend during authentication.
2762 pqsignal(SIGTERM, authdie);
2763 pqsignal(SIGQUIT, authdie);
2764 pqsignal(SIGALRM, authdie);
2765 PG_SETMASK(&AuthBlockSig);
2768 * Get the remote host name and port for logging and status display.
2770 remote_host[0] = '\0';
2771 remote_port[0] = '\0';
2772 if (pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2773 remote_host, sizeof(remote_host),
2774 remote_port, sizeof(remote_port),
2775 (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV))
2777 int ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2778 remote_host, sizeof(remote_host),
2779 remote_port, sizeof(remote_port),
2780 NI_NUMERICHOST | NI_NUMERICSERV);
2784 (errmsg_internal("pg_getnameinfo_all() failed: %s",
2785 gai_strerror(ret))));
2787 snprintf(remote_ps_data, sizeof(remote_ps_data),
2788 remote_port[0] == '\0' ? "%s" : "%s(%s)",
2789 remote_host, remote_port);
2791 if (Log_connections)
2793 (errmsg("connection received: host=%s%s%s",
2794 remote_host, remote_port[0] ? " port=" : "",
2798 * save remote_host and remote_port in port structure
2800 port->remote_host = strdup(remote_host);
2801 port->remote_port = strdup(remote_port);
2804 * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
2805 * etcetera from the postmaster, and have to load them ourselves. Build
2806 * the PostmasterContext (which didn't exist before, in this process) to
2809 * FIXME: [fork/exec] Ugh. Is there a way around this overhead?
2812 Assert(PostmasterContext == NULL);
2813 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
2815 ALLOCSET_DEFAULT_MINSIZE,
2816 ALLOCSET_DEFAULT_INITSIZE,
2817 ALLOCSET_DEFAULT_MAXSIZE);
2818 MemoryContextSwitchTo(PostmasterContext);
2826 * Ready to begin client interaction. We will give up and exit(0) after a
2827 * time delay, so that a broken client can't hog a connection
2828 * indefinitely. PreAuthDelay doesn't count against the time limit.
2830 if (!enable_sig_alarm(AuthenticationTimeout * 1000, false))
2831 elog(FATAL, "could not set timer for authorization timeout");
2834 * Receive the startup packet (which might turn out to be a cancel request
2837 status = ProcessStartupPacket(port, false);
2839 if (status != STATUS_OK)
2843 * Now that we have the user and database name, we can set the process
2844 * title for ps. It's good to do this as early as possible in startup.
2846 init_ps_display(port->user_name, port->database_name, remote_ps_data,
2847 update_process_title ? "authentication" : "");
2850 * Now perform authentication exchange.
2852 ClientAuthentication(port); /* might not return, if failure */
2855 * Done with authentication. Disable timeout, and prevent SIGTERM/SIGQUIT
2856 * again until backend startup is complete.
2858 if (!disable_sig_alarm(false))
2859 elog(FATAL, "could not disable timer for authorization timeout");
2860 PG_SETMASK(&BlockSig);
2862 if (Log_connections)
2864 (errmsg("connection authorized: user=%s database=%s",
2865 port->user_name, port->database_name)));
2870 * BackendRun -- set up the backend's argument list and invoke PostgresMain()
2873 * Shouldn't return at all.
2874 * If PostgresMain() fails, return status.
2877 BackendRun(Port *port)
2888 * Don't want backend to be able to see the postmaster random number
2889 * generator state. We have to clobber the static random_seed *and* start
2890 * a new random sequence in the random() library function.
2893 /* slightly hacky way to get integer microseconds part of timestamptz */
2894 TimestampDifference(0, port->SessionStartTime, &secs, &usecs);
2895 srandom((unsigned int) (MyProcPid ^ usecs));
2898 * Now, build the argv vector that will be given to PostgresMain.
2900 * The layout of the command line is
2901 * postgres [secure switches] -y databasename [insecure switches]
2902 * where the switches after -y come from the client request.
2904 * The maximum possible number of commandline arguments that could come
2905 * from ExtraOptions or port->cmdline_options is (strlen + 1) / 2; see
2909 maxac = 10; /* for fixed args supplied below */
2910 maxac += (strlen(ExtraOptions) + 1) / 2;
2911 if (port->cmdline_options)
2912 maxac += (strlen(port->cmdline_options) + 1) / 2;
2914 av = (char **) MemoryContextAlloc(TopMemoryContext,
2915 maxac * sizeof(char *));
2918 av[ac++] = "postgres";
2921 * Pass any backend switches specified with -o in the postmaster's own
2922 * command line. We assume these are secure. (It's OK to mangle
2923 * ExtraOptions now, since we're safely inside a subprocess.)
2925 split_opts(av, &ac, ExtraOptions);
2927 /* Tell the backend what protocol the frontend is using. */
2928 snprintf(protobuf, sizeof(protobuf), "-v%u", port->proto);
2929 av[ac++] = protobuf;
2932 * Tell the backend it is being called from the postmaster, and which
2933 * database to use. -y marks the end of secure switches.
2936 av[ac++] = port->database_name;
2939 * Pass the (insecure) option switches from the connection request. (It's
2940 * OK to mangle port->cmdline_options now.)
2942 if (port->cmdline_options)
2943 split_opts(av, &ac, port->cmdline_options);
2950 * Release postmaster's working memory context so that backend can recycle
2951 * the space. Note this does not trash *MyProcPort, because ConnCreate()
2952 * allocated that space with malloc() ... else we'd need to copy the Port
2953 * data here. Also, subsidiary data such as the username isn't lost
2954 * either; see ProcessStartupPacket().
2956 MemoryContextSwitchTo(TopMemoryContext);
2957 MemoryContextDelete(PostmasterContext);
2958 PostmasterContext = NULL;
2961 * Debug: print arguments being passed to backend
2964 (errmsg_internal("%s child[%d]: starting with (",
2965 progname, (int) getpid())));
2966 for (i = 0; i < ac; ++i)
2968 (errmsg_internal("\t%s", av[i])));
2970 (errmsg_internal(")")));
2972 ClientAuthInProgress = false; /* client_min_messages is active now */
2974 return (PostgresMain(ac, av, port->user_name));
2981 * postmaster_forkexec -- fork and exec a postmaster subprocess
2983 * The caller must have set up the argv array already, except for argv[2]
2984 * which will be filled with the name of the temp variable file.
2986 * Returns the child process PID, or -1 on fork failure (a suitable error
2987 * message has been logged on failure).
2989 * All uses of this routine will dispatch to SubPostmasterMain in the
2993 postmaster_forkexec(int argc, char *argv[])
2997 /* This entry point passes dummy values for the Port variables */
2998 memset(&port, 0, sizeof(port));
2999 return internal_forkexec(argc, argv, &port);
3003 * backend_forkexec -- fork/exec off a backend process
3005 * returns the pid of the fork/exec'd process, or -1 on failure
3008 backend_forkexec(Port *port)
3013 av[ac++] = "postgres";
3014 av[ac++] = "--forkbackend";
3015 av[ac++] = NULL; /* filled in by internal_forkexec */
3018 Assert(ac < lengthof(av));
3020 return internal_forkexec(ac, av, port);
3026 * internal_forkexec non-win32 implementation
3028 * - writes out backend variables to the parameter file
3029 * - fork():s, and then exec():s the child process
3032 internal_forkexec(int argc, char *argv[], Port *port)
3034 static unsigned long tmpBackendFileNum = 0;
3036 char tmpfilename[MAXPGPATH];
3037 BackendParameters param;
3040 if (!save_backend_variables(¶m, port))
3041 return -1; /* log made by save_backend_variables */
3043 /* Calculate name for temp file */
3044 snprintf(tmpfilename, MAXPGPATH, "%s/%s.backend_var.%d.%lu",
3045 PG_TEMP_FILES_DIR, PG_TEMP_FILE_PREFIX,
3046 MyProcPid, ++tmpBackendFileNum);
3049 fp = AllocateFile(tmpfilename, PG_BINARY_W);
3052 /* As in OpenTemporaryFile, try to make the temp-file directory */
3053 mkdir(PG_TEMP_FILES_DIR, S_IRWXU);
3055 fp = AllocateFile(tmpfilename, PG_BINARY_W);
3059 (errcode_for_file_access(),
3060 errmsg("could not create file \"%s\": %m",
3066 if (fwrite(¶m, sizeof(param), 1, fp) != 1)
3069 (errcode_for_file_access(),
3070 errmsg("could not write to file \"%s\": %m", tmpfilename)));
3079 (errcode_for_file_access(),
3080 errmsg("could not write to file \"%s\": %m", tmpfilename)));
3084 /* Make sure caller set up argv properly */
3086 Assert(argv[argc] == NULL);
3087 Assert(strncmp(argv[1], "--fork", 6) == 0);
3088 Assert(argv[2] == NULL);
3090 /* Insert temp file name after --fork argument */
3091 argv[2] = tmpfilename;
3093 /* Fire off execv in child */
3094 if ((pid = fork_process()) == 0)
3096 if (execv(postgres_exec_path, argv) < 0)
3099 (errmsg("could not execute server process \"%s\": %m",
3100 postgres_exec_path)));
3101 /* We're already in the child process here, can't return */
3106 return pid; /* Parent returns pid, or -1 on fork failure */
3111 * internal_forkexec win32 implementation
3113 * - starts backend using CreateProcess(), in suspended state
3114 * - writes out backend variables to the parameter file
3115 * - during this, duplicates handles and sockets required for
3116 * inheritance into the new process
3117 * - resumes execution of the new process once the backend parameter
3121 internal_forkexec(int argc, char *argv[], Port *port)
3124 PROCESS_INFORMATION pi;
3127 char cmdLine[MAXPGPATH * 2];
3128 HANDLE childHandleCopy;
3129 HANDLE waiterThread;
3131 BackendParameters *param;
3132 SECURITY_ATTRIBUTES sa;
3133 char paramHandleStr[32];
3135 /* Make sure caller set up argv properly */
3137 Assert(argv[argc] == NULL);
3138 Assert(strncmp(argv[1], "--fork", 6) == 0);
3139 Assert(argv[2] == NULL);
3141 /* Verify that there is room in the child list */
3142 if (win32_numChildren >= NUM_BACKENDARRAY_ELEMS)
3144 elog(LOG, "no room for child entry in backend list");
3145 /* Report same error as for a fork failure on Unix */
3150 /* Set up shared memory for parameter passing */
3151 ZeroMemory(&sa, sizeof(sa));
3152 sa.nLength = sizeof(sa);
3153 sa.bInheritHandle = TRUE;
3154 paramHandle = CreateFileMapping(INVALID_HANDLE_VALUE,
3158 sizeof(BackendParameters),
3160 if (paramHandle == INVALID_HANDLE_VALUE)
3162 elog(LOG, "could not create backend parameter file mapping: error code %d",
3163 (int) GetLastError());
3167 param = MapViewOfFile(paramHandle, FILE_MAP_WRITE, 0, 0, sizeof(BackendParameters));
3170 elog(LOG, "could not map backend parameter memory: error code %d",
3171 (int) GetLastError());
3172 CloseHandle(paramHandle);
3176 /* Insert temp file name after --fork argument */
3177 sprintf(paramHandleStr, "%lu", (DWORD) paramHandle);
3178 argv[2] = paramHandleStr;
3180 /* Format the cmd line */
3181 cmdLine[sizeof(cmdLine) - 1] = '\0';
3182 cmdLine[sizeof(cmdLine) - 2] = '\0';
3183 snprintf(cmdLine, sizeof(cmdLine) - 1, "\"%s\"", postgres_exec_path);
3185 while (argv[++i] != NULL)
3187 j = strlen(cmdLine);
3188 snprintf(cmdLine + j, sizeof(cmdLine) - 1 - j, " \"%s\"", argv[i]);
3190 if (cmdLine[sizeof(cmdLine) - 2] != '\0')
3192 elog(LOG, "subprocess command line too long");
3196 memset(&pi, 0, sizeof(pi));
3197 memset(&si, 0, sizeof(si));
3201 * Create the subprocess in a suspended state. This will be resumed later,
3202 * once we have written out the parameter file.
3204 if (!CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, CREATE_SUSPENDED,
3205 NULL, NULL, &si, &pi))
3207 elog(LOG, "CreateProcess call failed: %m (error code %d)",
3208 (int) GetLastError());
3212 if (!save_backend_variables(param, port, pi.hProcess, pi.dwProcessId))
3215 * log made by save_backend_variables, but we have to clean up the
3216 * mess with the half-started process
3218 if (!TerminateProcess(pi.hProcess, 255))
3220 (errmsg_internal("could not terminate unstarted process: error code %d",
3221 (int) GetLastError())));
3222 CloseHandle(pi.hProcess);
3223 CloseHandle(pi.hThread);
3224 return -1; /* log made by save_backend_variables */
3227 /* Drop the shared memory that is now inherited to the backend */
3228 if (!UnmapViewOfFile(param))
3229 elog(LOG, "could not unmap view of backend parameter file: error code %d",
3230 (int) GetLastError());
3231 if (!CloseHandle(paramHandle))
3232 elog(LOG, "could not close handle to backend parameter file: error code %d",
3233 (int) GetLastError());
3236 * Now that the backend variables are written out, we start the child
3237 * thread so it can start initializing while we set up the rest of the
3240 if (ResumeThread(pi.hThread) == -1)
3242 if (!TerminateProcess(pi.hProcess, 255))
3245 (errmsg_internal("could not terminate unstartable process: error code %d",
3246 (int) GetLastError())));
3247 CloseHandle(pi.hProcess);
3248 CloseHandle(pi.hThread);
3251 CloseHandle(pi.hProcess);
3252 CloseHandle(pi.hThread);
3254 (errmsg_internal("could not resume thread of unstarted process: error code %d",
3255 (int) GetLastError())));
3259 if (!IsUnderPostmaster)
3261 /* We are the Postmaster creating a child... */
3262 win32_AddChild(pi.dwProcessId, pi.hProcess);
3265 /* Set up the thread to handle the SIGCHLD for this process */
3266 if (DuplicateHandle(GetCurrentProcess(),
3268 GetCurrentProcess(),
3272 DUPLICATE_SAME_ACCESS) == 0)
3274 (errmsg_internal("could not duplicate child handle: error code %d",
3275 (int) GetLastError())));
3277 waiterThread = CreateThread(NULL, 64 * 1024, win32_sigchld_waiter,
3278 (LPVOID) childHandleCopy, 0, NULL);
3281 (errmsg_internal("could not create sigchld waiter thread: error code %d",
3282 (int) GetLastError())));
3283 CloseHandle(waiterThread);
3285 if (IsUnderPostmaster)
3286 CloseHandle(pi.hProcess);
3287 CloseHandle(pi.hThread);
3289 return pi.dwProcessId;
3295 * SubPostmasterMain -- Get the fork/exec'd process into a state equivalent
3296 * to what it would be if we'd simply forked on Unix, and then
3297 * dispatch to the appropriate place.
3299 * The first two command line arguments are expected to be "--forkFOO"
3300 * (where FOO indicates which postmaster child we are to become), and
3301 * the name of a variables file that we can read to load data that would
3302 * have been inherited by fork() on Unix. Remaining arguments go to the
3303 * subprocess FooMain() routine.
3306 SubPostmasterMain(int argc, char *argv[])
3310 /* Do this sooner rather than later... */
3311 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
3313 MyProcPid = getpid(); /* reset MyProcPid */
3315 /* Lose the postmaster's on-exit routines (really a no-op) */
3318 /* In EXEC_BACKEND case we will not have inherited these settings */
3319 IsPostmasterEnvironment = true;
3320 whereToSendOutput = DestNone;
3322 /* Setup essential subsystems (to ensure elog() behaves sanely) */
3323 MemoryContextInit();
3324 InitializeGUCOptions();
3326 /* Read in the variables file */
3327 memset(&port, 0, sizeof(Port));
3328 read_backend_variables(argv[2], &port);
3330 /* Check we got appropriate args */
3332 elog(FATAL, "invalid subpostmaster invocation");
3335 * If appropriate, physically re-attach to shared memory segment. We want
3336 * to do this before going any further to ensure that we can attach at the
3337 * same address the postmaster used.
3339 if (strcmp(argv[1], "--forkbackend") == 0 ||
3340 strcmp(argv[1], "--forkavlauncher") == 0 ||
3341 strcmp(argv[1], "--forkavworker") == 0 ||
3342 strcmp(argv[1], "--forkboot") == 0)
3343 PGSharedMemoryReAttach();
3345 /* autovacuum needs this set before calling InitProcess */
3346 if (strcmp(argv[1], "--forkavlauncher") == 0)
3347 AutovacuumLauncherIAm();
3348 if (strcmp(argv[1], "--forkavworker") == 0)
3349 AutovacuumWorkerIAm();
3352 * Start our win32 signal implementation. This has to be done after we
3353 * read the backend variables, because we need to pick up the signal pipe
3354 * from the parent process.
3357 pgwin32_signal_initialize();
3360 /* In EXEC_BACKEND case we will not have inherited these settings */
3362 PG_SETMASK(&BlockSig);
3364 /* Read in remaining GUC variables */
3365 read_nondefault_variables();
3367 /* Run backend or appropriate child */
3368 if (strcmp(argv[1], "--forkbackend") == 0)
3370 Assert(argc == 3); /* shouldn't be any more args */
3372 /* Close the postmaster's sockets */
3373 ClosePostmasterPorts(false);
3376 * Need to reinitialize the SSL library in the backend, since the
3377 * context structures contain function pointers and cannot be passed
3378 * through the parameter file.
3382 secure_initialize();
3386 * process any libraries that should be preloaded at postmaster start
3388 * NOTE: we have to re-load the shared_preload_libraries here because
3389 * this backend is not fork()ed so we can't inherit any shared
3390 * libraries / DLL's from our parent (the postmaster).
3392 process_shared_preload_libraries();
3395 * Perform additional initialization and client authentication.
3397 * We want to do this before InitProcess() for a couple of reasons: 1.
3398 * so that we aren't eating up a PGPROC slot while waiting on the
3399 * client. 2. so that if InitProcess() fails due to being out of
3400 * PGPROC slots, we have already initialized libpq and are able to
3401 * report the error to the client.
3403 BackendInitialize(&port);
3405 /* Restore basic shared memory pointers */
3406 InitShmemAccess(UsedShmemSegAddr);
3408 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3412 * Attach process to shared data structures. If testing EXEC_BACKEND
3413 * on Linux, you must run this as root before starting the postmaster:
3415 * echo 0 >/proc/sys/kernel/randomize_va_space
3417 * This prevents a randomized stack base address that causes child
3418 * shared memory to be at a different address than the parent, making
3419 * it impossible to attached to shared memory. Return the value to
3420 * '1' when finished.
3422 CreateSharedMemoryAndSemaphores(false, 0);
3424 /* And run the backend */
3425 proc_exit(BackendRun(&port));
3427 if (strcmp(argv[1], "--forkboot") == 0)
3429 /* Close the postmaster's sockets */
3430 ClosePostmasterPorts(false);
3432 /* Restore basic shared memory pointers */
3433 InitShmemAccess(UsedShmemSegAddr);
3435 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3438 /* Attach process to shared data structures */
3439 CreateSharedMemoryAndSemaphores(false, 0);
3441 BootstrapMain(argc - 2, argv + 2);
3444 if (strcmp(argv[1], "--forkavlauncher") == 0)
3446 /* Close the postmaster's sockets */
3447 ClosePostmasterPorts(false);
3449 /* Restore basic shared memory pointers */
3450 InitShmemAccess(UsedShmemSegAddr);
3452 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3455 /* Attach process to shared data structures */
3456 CreateSharedMemoryAndSemaphores(false, 0);
3458 AutoVacLauncherMain(argc - 2, argv + 2);
3461 if (strcmp(argv[1], "--forkavworker") == 0)
3463 /* Close the postmaster's sockets */
3464 ClosePostmasterPorts(false);
3466 /* Restore basic shared memory pointers */
3467 InitShmemAccess(UsedShmemSegAddr);
3469 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3472 /* Attach process to shared data structures */
3473 CreateSharedMemoryAndSemaphores(false, 0);
3475 AutoVacWorkerMain(argc - 2, argv + 2);
3478 if (strcmp(argv[1], "--forkarch") == 0)
3480 /* Close the postmaster's sockets */
3481 ClosePostmasterPorts(false);
3483 /* Do not want to attach to shared memory */
3485 PgArchiverMain(argc, argv);
3488 if (strcmp(argv[1], "--forkcol") == 0)
3490 /* Close the postmaster's sockets */
3491 ClosePostmasterPorts(false);
3493 /* Do not want to attach to shared memory */
3495 PgstatCollectorMain(argc, argv);
3498 if (strcmp(argv[1], "--forklog") == 0)
3500 /* Close the postmaster's sockets */
3501 ClosePostmasterPorts(true);
3503 /* Do not want to attach to shared memory */
3505 SysLoggerMain(argc, argv);
3509 return 1; /* shouldn't get here */
3511 #endif /* EXEC_BACKEND */
3515 * ExitPostmaster -- cleanup
3517 * Do NOT call exit() directly --- always go through here!
3520 ExitPostmaster(int status)
3522 /* should cleanup shared memory and kill all backends */
3525 * Not sure of the semantics here. When the Postmaster dies, should the
3526 * backends all be killed? probably not.
3528 * MUST -- vadim 05-10-1999
3535 * sigusr1_handler - handle signal conditions from child processes
3538 sigusr1_handler(SIGNAL_ARGS)
3540 int save_errno = errno;
3542 PG_SETMASK(&BlockSig);
3544 if (CheckPostmasterSignal(PMSIGNAL_PASSWORD_CHANGE))
3547 * Authorization file has changed.
3552 if (CheckPostmasterSignal(PMSIGNAL_WAKEN_CHILDREN))
3555 * Send SIGUSR1 to all children (triggers CatchupInterruptHandler).
3556 * See storage/ipc/sinval[adt].c for the use of this.
3558 if (Shutdown <= SmartShutdown)
3559 SignalChildren(SIGUSR1);
3562 if (CheckPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER) &&
3563 PgArchPID != 0 && Shutdown == NoShutdown)
3566 * Send SIGUSR1 to archiver process, to wake it up and begin archiving
3567 * next transaction log file.
3569 signal_child(PgArchPID, SIGUSR1);
3572 if (CheckPostmasterSignal(PMSIGNAL_ROTATE_LOGFILE) &&
3575 /* Tell syslogger to rotate logfile */
3576 signal_child(SysLoggerPID, SIGUSR1);
3579 if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER))
3582 * Start one iteration of the autovacuum daemon, even if autovacuuming
3583 * is nominally not enabled. This is so we can have an active defense
3584 * against transaction ID wraparound. We set a flag for the main loop
3585 * to do it rather than trying to do it here --- this is because the
3586 * autovac process itself may send the signal, and we want to handle
3587 * that by launching another iteration as soon as the current one
3590 start_autovac_launcher = true;
3593 /* The autovacuum launcher wants us to start a worker process. */
3594 if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER))
3595 StartAutovacuumWorker();
3597 PG_SETMASK(&UnBlockSig);
3604 * Dummy signal handler
3606 * We use this for signals that we don't actually use in the postmaster,
3607 * but we do use in backends. If we were to SIG_IGN such signals in the
3608 * postmaster, then a newly started backend might drop a signal that arrives
3609 * before it's able to reconfigure its signal processing. (See notes in
3613 dummy_handler(SIGNAL_ARGS)
3619 * CharRemap: given an int in range 0..61, produce textual encoding of it
3620 * per crypt(3) conventions.
3644 RandomSalt(char *cryptSalt, char *md5Salt)
3646 long rand = PostmasterRandom();
3648 cryptSalt[0] = CharRemap(rand % 62);
3649 cryptSalt[1] = CharRemap(rand / 62);
3652 * It's okay to reuse the first random value for one of the MD5 salt
3653 * bytes, since only one of the two salts will be sent to the client.
3654 * After that we need to compute more random bits.
3656 * We use % 255, sacrificing one possible byte value, so as to ensure that
3657 * all bits of the random() value participate in the result. While at it,
3658 * add one to avoid generating any null bytes.
3660 md5Salt[0] = (rand % 255) + 1;
3661 rand = PostmasterRandom();
3662 md5Salt[1] = (rand % 255) + 1;
3663 rand = PostmasterRandom();
3664 md5Salt[2] = (rand % 255) + 1;
3665 rand = PostmasterRandom();
3666 md5Salt[3] = (rand % 255) + 1;
3673 PostmasterRandom(void)
3675 static bool initialized = false;
3679 Assert(random_seed != 0);
3680 srandom(random_seed);
3688 * Count up number of child processes (regular backends only)
3696 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
3703 * StartChildProcess -- start a non-backend child process for the postmaster
3705 * xlop determines what kind of child will be started. All child types
3706 * initially go to BootstrapMain, which will handle common setup.
3708 * Return value of StartChildProcess is subprocess' PID, or 0 if failed
3709 * to start subprocess.
3712 StartChildProcess(int xlop)
3720 * Set up command-line arguments for subprocess
3722 av[ac++] = "postgres";
3725 av[ac++] = "--forkboot";
3726 av[ac++] = NULL; /* filled in by postmaster_forkexec */
3729 snprintf(xlbuf, sizeof(xlbuf), "-x%d", xlop);
3733 Assert(ac < lengthof(av));
3736 pid = postmaster_forkexec(ac, av);
3737 #else /* !EXEC_BACKEND */
3738 pid = fork_process();
3740 if (pid == 0) /* child */
3742 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
3744 /* Close the postmaster's sockets */
3745 ClosePostmasterPorts(false);
3747 /* Lose the postmaster's on-exit routines and port connections */
3750 /* Release postmaster's working memory context */
3751 MemoryContextSwitchTo(TopMemoryContext);
3752 MemoryContextDelete(PostmasterContext);
3753 PostmasterContext = NULL;
3755 BootstrapMain(ac, av);
3758 #endif /* EXEC_BACKEND */
3762 /* in parent, fork failed */
3763 int save_errno = errno;
3768 case BS_XLOG_STARTUP:
3770 (errmsg("could not fork startup process: %m")));
3772 case BS_XLOG_BGWRITER:
3774 (errmsg("could not fork background writer process: %m")));
3778 (errmsg("could not fork process: %m")));
3783 * fork failure is fatal during startup, but there's no need to choke
3784 * immediately if starting other child types fails.
3786 if (xlop == BS_XLOG_STARTUP)
3792 * in parent, successful fork
3798 * StartAutovacuumWorker
3799 * Start an autovac worker process.
3801 * This function is here because it enters the resulting PID into the
3802 * postmaster's private backends list.
3804 * NB -- this code very roughly matches BackendStartup.
3807 StartAutovacuumWorker(void)
3812 * do nothing if not in condition to run a process. This should not
3813 * actually happen, since the signal is only supposed to be sent by
3814 * autovacuum launcher when it's OK to do it, but test for it just in case.
3816 if (StartupPID != 0 || FatalError || Shutdown != NoShutdown)
3819 bn = (Backend *) malloc(sizeof(Backend));
3823 (errcode(ERRCODE_OUT_OF_MEMORY),
3824 errmsg("out of memory")));
3828 bn->pid = StartAutoVacWorker();
3829 bn->is_autovacuum = true;
3830 /* we don't need a cancel key */
3834 DLAddHead(BackendList, DLNewElem(bn));
3836 ShmemBackendArrayAdd(bn);
3841 /* not much we can do */
3843 (errmsg("could not fork new process for autovacuum: %m")));
3849 * Create the opts file
3852 CreateOptsFile(int argc, char *argv[], char *fullprogname)
3857 #define OPTS_FILE "postmaster.opts"
3859 if ((fp = fopen(OPTS_FILE, "w")) == NULL)
3861 elog(LOG, "could not create file \"%s\": %m", OPTS_FILE);
3865 fprintf(fp, "%s", fullprogname);
3866 for (i = 1; i < argc; i++)
3867 fprintf(fp, " %s%s%s", SYSTEMQUOTE, argv[i], SYSTEMQUOTE);
3872 elog(LOG, "could not write file \"%s\": %m", OPTS_FILE);
3883 * The following need to be available to the save/restore_backend_variables
3886 extern slock_t *ShmemLock;
3887 extern LWLock *LWLockArray;
3888 extern slock_t *ProcStructLock;
3889 extern PROC_HDR *ProcGlobal;
3890 extern PGPROC *DummyProcs;
3891 extern int pgStatSock;
3894 #define write_inheritable_socket(dest, src, childpid) (*(dest) = (src))
3895 #define read_inheritable_socket(dest, src) (*(dest) = *(src))
3897 static void write_duplicated_handle(HANDLE * dest, HANDLE src, HANDLE child);
3898 static void write_inheritable_socket(InheritableSocket * dest, SOCKET src,
3900 static void read_inheritable_socket(SOCKET * dest, InheritableSocket * src);
3904 /* Save critical backend variables into the BackendParameters struct */
3907 save_backend_variables(BackendParameters * param, Port *port)
3910 save_backend_variables(BackendParameters * param, Port *port,
3911 HANDLE childProcess, pid_t childPid)
3914 memcpy(¶m->port, port, sizeof(Port));
3915 write_inheritable_socket(¶m->portsocket, port->sock, childPid);
3917 strlcpy(param->DataDir, DataDir, MAXPGPATH);
3919 memcpy(¶m->ListenSocket, &ListenSocket, sizeof(ListenSocket));
3921 param->MyCancelKey = MyCancelKey;
3923 param->UsedShmemSegID = UsedShmemSegID;
3924 param->UsedShmemSegAddr = UsedShmemSegAddr;
3926 param->ShmemLock = ShmemLock;
3927 param->ShmemVariableCache = ShmemVariableCache;
3928 param->ShmemBackendArray = ShmemBackendArray;
3930 param->LWLockArray = LWLockArray;
3931 param->ProcStructLock = ProcStructLock;
3932 param->ProcGlobal = ProcGlobal;
3933 param->DummyProcs = DummyProcs;
3934 write_inheritable_socket(¶m->pgStatSock, pgStatSock, childPid);
3936 param->PostmasterPid = PostmasterPid;
3937 param->PgStartTime = PgStartTime;
3940 param->PostmasterHandle = PostmasterHandle;
3941 write_duplicated_handle(¶m->initial_signal_pipe,
3942 pgwin32_create_signal_listener(childPid),
3946 memcpy(¶m->syslogPipe, &syslogPipe, sizeof(syslogPipe));
3948 strlcpy(param->my_exec_path, my_exec_path, MAXPGPATH);
3950 strlcpy(param->pkglib_path, pkglib_path, MAXPGPATH);
3952 strlcpy(param->ExtraOptions, ExtraOptions, MAXPGPATH);
3954 strlcpy(param->lc_collate, setlocale(LC_COLLATE, NULL), LOCALE_NAME_BUFLEN);
3955 strlcpy(param->lc_ctype, setlocale(LC_CTYPE, NULL), LOCALE_NAME_BUFLEN);
3963 * Duplicate a handle for usage in a child process, and write the child
3964 * process instance of the handle to the parameter file.
3967 write_duplicated_handle(HANDLE * dest, HANDLE src, HANDLE childProcess)
3969 HANDLE hChild = INVALID_HANDLE_VALUE;
3971 if (!DuplicateHandle(GetCurrentProcess(),
3977 DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS))
3979 (errmsg_internal("could not duplicate handle to be written to backend parameter file: error code %d",
3980 (int) GetLastError())));
3986 * Duplicate a socket for usage in a child process, and write the resulting
3987 * structure to the parameter file.
3988 * This is required because a number of LSPs (Layered Service Providers) very
3989 * common on Windows (antivirus, firewalls, download managers etc) break
3990 * straight socket inheritance.
3993 write_inheritable_socket(InheritableSocket * dest, SOCKET src, pid_t childpid)
3995 dest->origsocket = src;
3996 if (src != 0 && src != -1)
3999 if (WSADuplicateSocket(src, childpid, &dest->wsainfo) != 0)
4001 (errmsg("could not duplicate socket %d for use in backend: error code %d",
4002 src, WSAGetLastError())));
4007 * Read a duplicate socket structure back, and get the socket descriptor.
4010 read_inheritable_socket(SOCKET * dest, InheritableSocket * src)
4014 if (src->origsocket == -1 || src->origsocket == 0)
4016 /* Not a real socket! */
4017 *dest = src->origsocket;
4021 /* Actual socket, so create from structure */
4022 s = WSASocket(FROM_PROTOCOL_INFO,
4028 if (s == INVALID_SOCKET)
4030 write_stderr("could not create inherited socket: error code %d\n",
4037 * To make sure we don't get two references to the same socket, close
4038 * the original one. (This would happen when inheritance actually
4041 closesocket(src->origsocket);
4047 read_backend_variables(char *id, Port *port)
4049 BackendParameters param;
4052 /* Non-win32 implementation reads from file */
4056 fp = AllocateFile(id, PG_BINARY_R);
4059 write_stderr("could not read from backend variables file \"%s\": %s\n",
4060 id, strerror(errno));
4064 if (fread(¶m, sizeof(param), 1, fp) != 1)
4066 write_stderr("could not read from backend variables file \"%s\": %s\n",
4067 id, strerror(errno));
4073 if (unlink(id) != 0)
4075 write_stderr("could not remove file \"%s\": %s\n",
4076 id, strerror(errno));
4080 /* Win32 version uses mapped file */
4082 BackendParameters *paramp;
4084 paramHandle = (HANDLE) atol(id);
4085 paramp = MapViewOfFile(paramHandle, FILE_MAP_READ, 0, 0, 0);
4088 write_stderr("could not map view of backend variables: error code %d\n",
4089 (int) GetLastError());
4093 memcpy(¶m, paramp, sizeof(BackendParameters));
4095 if (!UnmapViewOfFile(paramp))
4097 write_stderr("could not unmap view of backend variables: error code %d\n",
4098 (int) GetLastError());
4102 if (!CloseHandle(paramHandle))
4104 write_stderr("could not close handle to backend parameter variables: error code %d\n",
4105 (int) GetLastError());
4110 restore_backend_variables(¶m, port);
4113 /* Restore critical backend variables from the BackendParameters struct */
4115 restore_backend_variables(BackendParameters * param, Port *port)
4117 memcpy(port, ¶m->port, sizeof(Port));
4118 read_inheritable_socket(&port->sock, ¶m->portsocket);
4120 SetDataDir(param->DataDir);
4122 memcpy(&ListenSocket, ¶m->ListenSocket, sizeof(ListenSocket));
4124 MyCancelKey = param->MyCancelKey;
4126 UsedShmemSegID = param->UsedShmemSegID;
4127 UsedShmemSegAddr = param->UsedShmemSegAddr;
4129 ShmemLock = param->ShmemLock;
4130 ShmemVariableCache = param->ShmemVariableCache;
4131 ShmemBackendArray = param->ShmemBackendArray;
4133 LWLockArray = param->LWLockArray;
4134 ProcStructLock = param->ProcStructLock;
4135 ProcGlobal = param->ProcGlobal;
4136 DummyProcs = param->DummyProcs;
4137 read_inheritable_socket(&pgStatSock, ¶m->pgStatSock);
4139 PostmasterPid = param->PostmasterPid;
4140 PgStartTime = param->PgStartTime;
4143 PostmasterHandle = param->PostmasterHandle;
4144 pgwin32_initial_signal_pipe = param->initial_signal_pipe;
4147 memcpy(&syslogPipe, ¶m->syslogPipe, sizeof(syslogPipe));
4149 strlcpy(my_exec_path, param->my_exec_path, MAXPGPATH);
4151 strlcpy(pkglib_path, param->pkglib_path, MAXPGPATH);
4153 strlcpy(ExtraOptions, param->ExtraOptions, MAXPGPATH);
4155 setlocale(LC_COLLATE, param->lc_collate);
4156 setlocale(LC_CTYPE, param->lc_ctype);
4161 ShmemBackendArraySize(void)
4163 return mul_size(NUM_BACKENDARRAY_ELEMS, sizeof(Backend));
4167 ShmemBackendArrayAllocation(void)
4169 Size size = ShmemBackendArraySize();
4171 ShmemBackendArray = (Backend *) ShmemAlloc(size);
4172 /* Mark all slots as empty */
4173 memset(ShmemBackendArray, 0, size);
4177 ShmemBackendArrayAdd(Backend *bn)
4181 /* Find an empty slot */
4182 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
4184 if (ShmemBackendArray[i].pid == 0)
4186 ShmemBackendArray[i] = *bn;
4192 (errmsg_internal("no free slots in shmem backend array")));
4196 ShmemBackendArrayRemove(pid_t pid)
4200 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
4202 if (ShmemBackendArray[i].pid == pid)
4204 /* Mark the slot as empty */
4205 ShmemBackendArray[i].pid = 0;
4211 (errmsg_internal("could not find backend entry with pid %d",
4214 #endif /* EXEC_BACKEND */
4220 * Note: The following three functions must not be interrupted (eg. by
4221 * signals). As the Postgres Win32 signalling architecture (currently)
4222 * requires polling, or APC checking functions which aren't used here, this
4225 * We keep two separate arrays, instead of a single array of pid/HANDLE
4226 * structs, to avoid having to re-create a handle array for
4227 * WaitForMultipleObjects on each call to win32_waitpid.
4231 win32_AddChild(pid_t pid, HANDLE handle)
4233 Assert(win32_childPIDArray && win32_childHNDArray);
4234 if (win32_numChildren < NUM_BACKENDARRAY_ELEMS)
4236 win32_childPIDArray[win32_numChildren] = pid;
4237 win32_childHNDArray[win32_numChildren] = handle;
4238 ++win32_numChildren;
4242 (errmsg_internal("no room for child entry with pid %lu",
4243 (unsigned long) pid)));
4247 win32_RemoveChild(pid_t pid)
4251 Assert(win32_childPIDArray && win32_childHNDArray);
4253 for (i = 0; i < win32_numChildren; i++)
4255 if (win32_childPIDArray[i] == pid)
4257 CloseHandle(win32_childHNDArray[i]);
4259 /* Swap last entry into the "removed" one */
4260 --win32_numChildren;
4261 win32_childPIDArray[i] = win32_childPIDArray[win32_numChildren];
4262 win32_childHNDArray[i] = win32_childHNDArray[win32_numChildren];
4268 (errmsg_internal("could not find child entry with pid %lu",
4269 (unsigned long) pid)));
4273 win32_waitpid(int *exitstatus)
4276 * Note: Do NOT use WaitForMultipleObjectsEx, as we don't want to run
4282 unsigned long offset;
4284 Assert(win32_childPIDArray && win32_childHNDArray);
4285 elog(DEBUG3, "waiting on %lu children", win32_numChildren);
4287 for (offset = 0; offset < win32_numChildren; offset += MAXIMUM_WAIT_OBJECTS)
4289 unsigned long num = Min(MAXIMUM_WAIT_OBJECTS, win32_numChildren - offset);
4291 ret = WaitForMultipleObjects(num, &win32_childHNDArray[offset], FALSE, 0);
4296 (errmsg_internal("failed to wait on %lu of %lu children: error code %d",
4297 num, win32_numChildren, (int) GetLastError())));
4301 /* No children (in this chunk) have finished */
4307 * Get the exit code, and return the PID of, the respective
4310 index = offset + ret - WAIT_OBJECT_0;
4311 Assert(index >= 0 && index < win32_numChildren);
4312 if (!GetExitCodeProcess(win32_childHNDArray[index], &exitCode))
4315 * If we get this far, this should never happen, but, then
4316 * again... No choice other than to assume a catastrophic
4320 (errmsg_internal("failed to get exit code for child %lu",
4321 (unsigned long) win32_childPIDArray[index])));
4323 *exitstatus = (int) exitCode;
4324 return win32_childPIDArray[index];
4328 /* No children have finished */
4333 * Note! Code below executes on separate threads, one for
4334 * each child process created
4337 win32_sigchld_waiter(LPVOID param)
4339 HANDLE procHandle = (HANDLE) param;
4341 DWORD r = WaitForSingleObject(procHandle, INFINITE);
4343 if (r == WAIT_OBJECT_0)
4344 pg_queue_signal(SIGCHLD);
4346 write_stderr("could not wait on child process handle: error code %d\n",
4347 (int) GetLastError());
4348 CloseHandle(procHandle);