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-2003, 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.401 2004/05/30 03:50:11 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.
58 *-------------------------------------------------------------------------
68 #include <sys/socket.h>
71 #include <sys/param.h>
72 #include <netinet/in.h>
73 #include <arpa/inet.h>
77 #ifdef HAVE_SYS_SELECT_H
78 #include <sys/select.h>
86 #include <DNSServiceDiscovery/DNSServiceDiscovery.h>
89 #include "catalog/pg_database.h"
90 #include "commands/async.h"
91 #include "lib/dllist.h"
92 #include "libpq/auth.h"
93 #include "libpq/crypt.h"
94 #include "libpq/libpq.h"
95 #include "libpq/pqcomm.h"
96 #include "libpq/pqsignal.h"
97 #include "miscadmin.h"
98 #include "nodes/nodes.h"
99 #include "postmaster/postmaster.h"
101 #include "storage/fd.h"
102 #include "storage/ipc.h"
103 #include "storage/pg_shmem.h"
104 #include "storage/pmsignal.h"
105 #include "storage/proc.h"
106 #include "storage/bufmgr.h"
107 #include "access/xlog.h"
108 #include "tcop/tcopprot.h"
109 #include "utils/guc.h"
110 #include "utils/memutils.h"
111 #include "utils/ps_status.h"
112 #include "bootstrap/bootstrap.h"
117 * List of active backends (or child processes anyway; we don't actually
118 * know whether a given child has become a backend or is still in the
119 * authorization phase). This is used mainly to keep track of how many
120 * children we have and send them appropriate signals when necessary.
122 * "Special" children such as the startup and bgwriter tasks are not in
127 pid_t pid; /* process id of backend */
128 long cancel_key; /* cancel key for cancels for this backend */
131 static Dllist *BackendList;
134 #define NUM_BACKENDARRAY_ELEMS (2*MaxBackends)
135 static Backend *ShmemBackendArray;
138 /* The socket number we are listening for connections on */
141 char *ListenAddresses;
144 * ReservedBackends is the number of backends reserved for superuser use.
145 * This number is taken out of the pool size given by MaxBackends so
146 * number of backend slots available to non-superusers is
147 * (MaxBackends - ReservedBackends). Note what this really means is
148 * "if there are <= ReservedBackends connections available, only superusers
149 * can make new connections" --- pre-existing superuser connections don't
150 * count against the limit.
152 int ReservedBackends;
155 static const char *progname = NULL;
157 /* The socket(s) we're listening to. */
159 static int ListenSocket[MAXLISTEN];
162 * Set by the -o option
164 static char ExtraOptions[MAXPGPATH];
167 * These globals control the behavior of the postmaster in case some
168 * backend dumps core. Normally, it kills all peers of the dead backend
169 * and reinitializes shared memory. By specifying -s or -n, we can have
170 * the postmaster stop (rather than kill) peers and not reinitialize
171 * shared data structures.
173 static bool Reinit = true;
174 static int SendStop = false;
176 /* still more option variables */
177 bool EnableSSL = false;
178 bool SilentMode = false; /* silent mode (-S) */
180 int PreAuthDelay = 0;
181 int AuthenticationTimeout = 60;
183 bool log_hostname; /* for ps display and logging */
184 bool Log_connections = false;
185 bool Db_user_namespace = false;
187 char *rendezvous_name;
189 /* list of library:init-function to be preloaded */
190 char *preload_libraries_string = NULL;
192 /* PIDs of special child processes; 0 when not running */
193 static pid_t StartupPID = 0,
196 /* Startup/shutdown state */
198 #define SmartShutdown 1
199 #define FastShutdown 2
201 static int Shutdown = NoShutdown;
203 static bool FatalError = false; /* T if recovering from backend crash */
205 bool ClientAuthInProgress = false; /* T during new-client
209 * State for assigning random salts and cancel keys.
210 * Also, the global MyCancelKey passes the cancel key assigned to a given
211 * backend from the postmaster to that backend (via fork).
213 static unsigned int random_seed = 0;
215 static int debug_flag = 0;
221 #ifdef HAVE_INT_OPTRESET
226 * postmaster.c - function prototypes
228 static void checkDataDir(const char *checkdir);
229 #ifdef USE_RENDEZVOUS
230 static void reg_reply(DNSServiceRegistrationReplyErrorType errorCode,
233 static void pmdaemonize(void);
234 static Port *ConnCreate(int serverFd);
235 static void ConnFree(Port *port);
236 static void reset_shared(unsigned short port);
237 static void SIGHUP_handler(SIGNAL_ARGS);
238 static void pmdie(SIGNAL_ARGS);
239 static void reaper(SIGNAL_ARGS);
240 static void sigusr1_handler(SIGNAL_ARGS);
241 static void dummy_handler(SIGNAL_ARGS);
242 static void CleanupProc(int pid, int exitstatus);
243 static void HandleChildCrash(int pid, int exitstatus);
244 static void LogChildExit(int lev, const char *procname,
245 int pid, int exitstatus);
246 static int BackendRun(Port *port);
247 static void ExitPostmaster(int status);
248 static void usage(const char *);
249 static int ServerLoop(void);
250 static int BackendStartup(Port *port);
251 static int ProcessStartupPacket(Port *port, bool SSLdone);
252 static void processCancelRequest(Port *port, void *pkt);
253 static int initMasks(fd_set *rmask);
254 static void report_fork_failure_to_client(Port *port, int errnum);
255 static enum CAC_state canAcceptConnections(void);
256 static long PostmasterRandom(void);
257 static void RandomSalt(char *cryptSalt, char *md5Salt);
258 static void SignalChildren(int signal);
259 static int CountChildren(void);
260 static bool CreateOptsFile(int argc, char *argv[], char *fullprogname);
261 static pid_t StartChildProcess(int xlop);
263 postmaster_error(const char *fmt,...)
264 /* This lets gcc check the format string for consistency. */
265 __attribute__((format(printf, 1, 2)));
270 static pid_t win32_forkexec(const char *path, char *argv[]);
271 static void win32_AddChild(pid_t pid, HANDLE handle);
272 static void win32_RemoveChild(pid_t pid);
273 static pid_t win32_waitpid(int *exitstatus);
274 static DWORD WINAPI win32_sigchld_waiter(LPVOID param);
276 static pid_t *win32_childPIDArray;
277 static HANDLE *win32_childHNDArray;
278 static unsigned long win32_numChildren = 0;
280 HANDLE PostmasterHandle;
283 static pid_t backend_forkexec(Port *port);
284 static pid_t internal_forkexec(int argc, char *argv[], Port *port);
286 static void read_backend_variables(char *filename, Port *port);
287 static bool write_backend_variables(char *filename, Port *port);
289 static void ShmemBackendArrayAdd(Backend *bn);
290 static void ShmemBackendArrayRemove(pid_t pid);
292 #endif /* EXEC_BACKEND */
294 #define StartupDataBase() StartChildProcess(BS_XLOG_STARTUP)
295 #define StartBackgroundWriter() StartChildProcess(BS_XLOG_BGWRITER)
299 * Postmaster main entry point
302 PostmasterMain(int argc, char *argv[])
306 char *potential_DataDir = NULL;
309 progname = get_progname(argv[0]);
311 MyProcPid = PostmasterPid = getpid();
313 IsPostmasterEnvironment = true;
316 * Catch standard options before doing much else. This even works on
317 * systems without getopt_long.
321 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
326 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
328 puts("postmaster (PostgreSQL) " PG_VERSION);
334 * for security, no dir or file created can be group or other
337 umask((mode_t) 0077);
340 * Fire up essential subsystems: memory management
345 * By default, palloc() requests in the postmaster will be allocated
346 * in the PostmasterContext, which is space that can be recycled by
347 * backends. Allocated data that needs to be available to backends
348 * should be allocated in TopMemoryContext.
350 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
352 ALLOCSET_DEFAULT_MINSIZE,
353 ALLOCSET_DEFAULT_INITSIZE,
354 ALLOCSET_DEFAULT_MAXSIZE);
355 MemoryContextSwitchTo(PostmasterContext);
357 IgnoreSystemIndexes(false);
359 if (find_my_exec(argv[0], my_exec_path) < 0)
360 elog(FATAL, "%s: could not locate my own executable path",
363 get_pkglib_path(my_exec_path, pkglib_path);
368 InitializeGUCOptions();
370 potential_DataDir = getenv("PGDATA"); /* default value */
374 while ((opt = getopt(argc, argv, "A:a:B:b:c:D:d:Fh:ik:lm:MN:no:p:Ss-:")) != -1)
379 #ifdef USE_ASSERT_CHECKING
380 SetConfigOption("debug_assertions", optarg, PGC_POSTMASTER, PGC_S_ARGV);
382 postmaster_error("assert checking is not compiled in");
386 /* Can no longer set authentication method. */
389 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
392 /* Can no longer set the backend executable file to use. */
395 potential_DataDir = optarg;
399 /* Turn on debugging for the postmaster. */
400 char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
402 sprintf(debugstr, "debug%s", optarg);
403 SetConfigOption("log_min_messages", debugstr,
404 PGC_POSTMASTER, PGC_S_ARGV);
406 debug_flag = atoi(optarg);
410 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
413 SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
416 SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
419 SetConfigOption("unix_socket_directory", optarg, PGC_POSTMASTER, PGC_S_ARGV);
423 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
427 /* Multiplexed backends no longer supported. */
432 * ignore this flag. This may be passed in because the
433 * program was run as 'postgres -M' instead of
438 /* The max number of backends to start. */
439 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
442 /* Don't reinit shared mem after abnormal exit */
448 * Other options to pass to the backend on the command line
450 strcat(ExtraOptions, " ");
451 strcat(ExtraOptions, optarg);
454 SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
459 * Start in 'S'ilent mode (disassociate from controlling
460 * tty). You may also think of this as 'S'ysV mode since
461 * it's most badly needed on SysV-derived systems like
464 SetConfigOption("silent_mode", "true", PGC_POSTMASTER, PGC_S_ARGV);
469 * In the event that some backend dumps core, send
470 * SIGSTOP, rather than SIGQUIT, to all its peers. This
471 * lets the wily post_hacker collect core dumps from
482 ParseLongOption(optarg, &name, &value);
487 (errcode(ERRCODE_SYNTAX_ERROR),
488 errmsg("--%s requires a value",
492 (errcode(ERRCODE_SYNTAX_ERROR),
493 errmsg("-c %s requires a value",
497 SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
506 gettext("Try \"%s --help\" for more information.\n"),
513 * Postmaster accepts no non-option switch arguments.
517 postmaster_error("invalid argument: \"%s\"", argv[optind]);
519 gettext("Try \"%s --help\" for more information.\n"),
525 * Now we can set the data directory, and then read postgresql.conf.
527 checkDataDir(potential_DataDir); /* issues error messages */
528 SetDataDir(potential_DataDir);
530 ProcessConfigFile(PGC_POSTMASTER);
532 /* If timezone is not set, determine what the OS uses */
533 pg_timezone_initialize();
536 write_nondefault_variables(PGC_POSTMASTER);
540 * Check for invalid combinations of GUC settings.
542 if (NBuffers < 2 * MaxBackends || NBuffers < 16)
545 * Do not accept -B so small that backends are likely to starve
546 * for lack of buffers. The specific choices here are somewhat
549 postmaster_error("the number of buffers (-B) must be at least twice the number of allowed connections (-N) and at least 16");
553 if (ReservedBackends >= MaxBackends)
555 postmaster_error("superuser_reserved_connections must be less than max_connections");
560 * Other one-time internal sanity checks can go here.
562 if (!CheckDateTokenTables())
564 postmaster_error("invalid datetoken tables, please fix");
569 * Now that we are done processing the postmaster arguments, reset
570 * getopt(3) library so that it will work correctly in subprocesses.
573 #ifdef HAVE_INT_OPTRESET
574 optreset = 1; /* some systems need this too */
577 /* For debugging: display postmaster environment */
579 extern char **environ;
583 (errmsg_internal("%s: PostmasterMain: initial environ dump:",
586 (errmsg_internal("-----------------------------------------")));
587 for (p = environ; *p; ++p)
589 (errmsg_internal("\t%s", *p)));
591 (errmsg_internal("-----------------------------------------")));
595 if (find_other_exec(argv[0], "postgres", PG_VERSIONSTR,
596 postgres_exec_path) < 0)
598 (errmsg("%s: could not locate matching postgres executable",
603 * Initialize SSL library, if specified.
611 * process any libraries that should be preloaded and optionally
614 if (preload_libraries_string)
615 process_preload_libraries(preload_libraries_string);
618 * Fork away from controlling terminal, if -S specified.
620 * Must do this before we grab any interlock files, else the interlocks
621 * will show the wrong PID.
627 * Create lockfile for data directory.
629 * We want to do this before we try to grab the input sockets, because
630 * the data directory interlock is more reliable than the socket-file
631 * interlock (thanks to whoever decided to put socket files in /tmp
632 * :-(). For the same reason, it's best to grab the TCP socket(s) before
635 CreateDataDirLockFile(DataDir, true);
638 * Remove old temporary files. At this point there can be no other
639 * Postgres processes running in this directory, so this should be
645 * Establish input sockets.
647 for (i = 0; i < MAXLISTEN; i++)
648 ListenSocket[i] = -1;
656 curhost = ListenAddresses;
659 /* ignore whitespace */
660 while (isspace((unsigned char) *curhost))
662 if (*curhost == '\0')
665 while (*endptr != '\0' && !isspace((unsigned char) *endptr))
669 if (strcmp(curhost, "*") == 0)
670 status = StreamServerPort(AF_UNSPEC, NULL,
671 (unsigned short) PostPortNumber,
673 ListenSocket, MAXLISTEN);
675 status = StreamServerPort(AF_UNSPEC, curhost,
676 (unsigned short) PostPortNumber,
678 ListenSocket, MAXLISTEN);
679 if (status != STATUS_OK)
681 (errmsg("could not create listen socket for \"%s\"",
685 curhost = endptr + 1;
691 #ifdef USE_RENDEZVOUS
692 /* Register for Rendezvous only if we opened TCP socket(s) */
693 if (ListenSocket[0] != -1 && rendezvous_name != NULL)
695 DNSServiceRegistrationCreate(rendezvous_name,
698 htonl(PostPortNumber),
700 (DNSServiceRegistrationReply) reg_reply,
705 #ifdef HAVE_UNIX_SOCKETS
706 status = StreamServerPort(AF_UNIX, NULL,
707 (unsigned short) PostPortNumber,
709 ListenSocket, MAXLISTEN);
710 if (status != STATUS_OK)
712 (errmsg("could not create Unix-domain socket")));
716 * check that we have some socket to listen on
718 if (ListenSocket[0] == -1)
720 (errmsg("no socket created for listening")));
725 * Set up shared memory and semaphores.
727 reset_shared(PostPortNumber);
730 * Estimate number of openable files. This must happen after setting
731 * up semaphores, because on some platforms semaphores count as open
737 * Initialize the list of active backends.
739 BackendList = DLNewList();
743 * Initialize the child pid/HANDLE arrays for signal handling.
745 win32_childPIDArray = (pid_t *)
746 malloc(NUM_BACKENDARRAY_ELEMS * sizeof(pid_t));
747 win32_childHNDArray = (HANDLE *)
748 malloc(NUM_BACKENDARRAY_ELEMS * sizeof(HANDLE));
749 if (!win32_childPIDArray || !win32_childHNDArray)
751 (errcode(ERRCODE_OUT_OF_MEMORY),
752 errmsg("out of memory")));
755 * Set up a handle that child processes can use to check whether the
756 * postmaster is still running.
758 if (DuplicateHandle(GetCurrentProcess(),
764 DUPLICATE_SAME_ACCESS) == 0)
766 (errmsg_internal("could not duplicate postmaster handle: %d",
767 (int) GetLastError())));
771 * Record postmaster options. We delay this till now to avoid
772 * recording bogus options (eg, NBuffers too high for available
775 if (!CreateOptsFile(argc, argv, my_exec_path))
779 * Set up signal handlers for the postmaster process.
781 * CAUTION: when changing this list, check for side-effects on the signal
782 * handling setup of child processes. See tcop/postgres.c,
783 * bootstrap/bootstrap.c, postmaster/bgwriter.c, and postmaster/pgstat.c.
786 PG_SETMASK(&BlockSig);
788 pqsignal(SIGHUP, SIGHUP_handler); /* reread config file and have
789 * children do same */
790 pqsignal(SIGINT, pmdie); /* send SIGTERM and shut down */
791 pqsignal(SIGQUIT, pmdie); /* send SIGQUIT and die */
792 pqsignal(SIGTERM, pmdie); /* wait for children and shut down */
793 pqsignal(SIGALRM, SIG_IGN); /* ignored */
794 pqsignal(SIGPIPE, SIG_IGN); /* ignored */
795 pqsignal(SIGUSR1, sigusr1_handler); /* message from child process */
796 pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
797 pqsignal(SIGCHLD, reaper); /* handle child termination */
798 pqsignal(SIGTTIN, SIG_IGN); /* ignored */
799 pqsignal(SIGTTOU, SIG_IGN); /* ignored */
800 /* ignore SIGXFSZ, so that ulimit violations work like disk full */
802 pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
806 * Reset whereToSendOutput from Debug (its starting state) to None.
807 * This prevents ereport from sending log messages to stderr unless
808 * the syslog/stderr switch permits. We don't do this until the
809 * postmaster is fully launched, since startup failures may as well be
810 * reported to stderr.
812 whereToSendOutput = None;
815 * Initialize and try to startup the statistics collector process
821 * Load cached files for client authentication.
829 * We're ready to rock and roll...
831 StartupPID = StartupDataBase();
833 status = ServerLoop();
836 * ServerLoop probably shouldn't ever return, but if it does, close
839 ExitPostmaster(status != STATUS_OK);
841 return 0; /* not reached */
846 * Validate the proposed data directory
849 checkDataDir(const char *checkdir)
851 char path[MAXPGPATH];
853 struct stat stat_buf;
855 if (checkdir == NULL)
858 gettext("%s does not know where to find the database system data.\n"
859 "You must specify the directory that contains the database system\n"
860 "either by specifying the -D invocation option or by setting the\n"
861 "PGDATA environment variable.\n"),
866 if (stat(checkdir, &stat_buf) == -1)
870 (errcode_for_file_access(),
871 errmsg("data directory \"%s\" does not exist",
875 (errcode_for_file_access(),
876 errmsg("could not read permissions of directory \"%s\": %m",
881 * Check if the directory has group or world access. If so, reject.
883 * XXX temporarily suppress check when on Windows, because there may not
884 * be proper support for Unix-y file permissions. Need to think of a
885 * reasonable check to apply on Windows.
887 #if !defined(__CYGWIN__) && !defined(WIN32)
888 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
890 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
891 errmsg("data directory \"%s\" has group or world access",
893 errdetail("Permissions should be u=rwx (0700).")));
896 /* Look for PG_VERSION before looking for pg_control */
897 ValidatePgVersion(checkdir);
899 snprintf(path, sizeof(path), "%s/global/pg_control", checkdir);
901 fp = AllocateFile(path, PG_BINARY_R);
905 gettext("%s: could not find the database system\n"
906 "Expected to find it in the directory \"%s\",\n"
907 "but could not open file \"%s\": %s\n"),
908 progname, checkdir, path, strerror(errno));
915 #ifdef USE_RENDEZVOUS
918 * empty callback function for DNSServiceRegistrationCreate()
921 reg_reply(DNSServiceRegistrationReplyErrorType errorCode, void *context)
926 #endif /* USE_RENDEZVOUS */
930 * Fork away from the controlling terminal (-S option)
940 struct itimerval prof_itimer;
944 /* see comments in BackendStartup */
945 getitimer(ITIMER_PROF, &prof_itimer);
949 if (pid == (pid_t) -1)
951 postmaster_error("could not fork background process: %s",
957 /* Parent should just exit, without doing any atexit cleanup */
962 setitimer(ITIMER_PROF, &prof_itimer, NULL);
965 MyProcPid = PostmasterPid = getpid(); /* reset PID vars to child */
967 /* GH: If there's no setsid(), we hopefully don't need silent mode.
968 * Until there's a better solution.
973 postmaster_error("could not dissociate from controlling TTY: %s",
978 i = open(NULL_DEV, O_RDWR | PG_BINARY);
985 elog(FATAL, "SilentMode not supported under WIN32");
991 * Print out help message
994 usage(const char *progname)
996 printf(gettext("%s is the PostgreSQL server.\n\n"), progname);
997 printf(gettext("Usage:\n %s [OPTION]...\n\n"), progname);
998 printf(gettext("Options:\n"));
999 #ifdef USE_ASSERT_CHECKING
1000 printf(gettext(" -A 1|0 enable/disable run-time assert checking\n"));
1002 printf(gettext(" -B NBUFFERS number of shared buffers\n"));
1003 printf(gettext(" -c NAME=VALUE set run-time parameter\n"));
1004 printf(gettext(" -d 1-5 debugging level\n"));
1005 printf(gettext(" -D DATADIR database directory\n"));
1006 printf(gettext(" -F turn fsync off\n"));
1007 printf(gettext(" -h HOSTNAME host name or IP address to listen on\n"));
1008 printf(gettext(" -i enable TCP/IP connections\n"));
1009 printf(gettext(" -k DIRECTORY Unix-domain socket location\n"));
1011 printf(gettext(" -l enable SSL connections\n"));
1013 printf(gettext(" -N MAX-CONNECT maximum number of allowed connections\n"));
1014 printf(gettext(" -o OPTIONS pass \"OPTIONS\" to each server process\n"));
1015 printf(gettext(" -p PORT port number to listen on\n"));
1016 printf(gettext(" -S silent mode (start in background without logging output)\n"));
1017 printf(gettext(" --help show this help, then exit\n"));
1018 printf(gettext(" --version output version information, then exit\n"));
1020 printf(gettext("\nDeveloper options:\n"));
1021 printf(gettext(" -n do not reinitialize shared memory after abnormal exit\n"));
1022 printf(gettext(" -s send SIGSTOP to all backend servers if one dies\n"));
1024 printf(gettext("\nPlease read the documentation for the complete list of run-time\n"
1025 "configuration settings and how to set them on the command line or in\n"
1026 "the configuration file.\n\n"
1027 "Report bugs to <pgsql-bugs@postgresql.org>.\n"));
1032 * Main idle loop of postmaster
1041 struct timeval earlier,
1045 gettimeofday(&earlier, &tz);
1046 last_touch_time = time(NULL);
1048 nSockets = initMasks(&readmask);
1054 struct timeval timeout;
1059 * Wait for something to happen.
1061 * We wait at most one minute, to ensure that the other background
1062 * tasks handled below get done even when no requests are arriving.
1064 memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
1066 timeout.tv_sec = 60;
1067 timeout.tv_usec = 0;
1069 PG_SETMASK(&UnBlockSig);
1071 selres = select(nSockets, &rmask, NULL, NULL, &timeout);
1074 * Block all signals until we wait again. (This makes it safe for
1075 * our signal handlers to do nontrivial work.)
1077 PG_SETMASK(&BlockSig);
1081 if (errno == EINTR || errno == EWOULDBLOCK)
1084 (errcode_for_socket_access(),
1085 errmsg("select() failed in postmaster: %m")));
1086 return STATUS_ERROR;
1090 * New connection pending on any of our sockets? If so, fork a
1091 * child process to deal with it.
1096 * Select a random seed at the time of first receiving a request.
1098 while (random_seed == 0)
1100 gettimeofday(&later, &tz);
1103 * We are not sure how much precision is in tv_usec, so we
1104 * swap the nibbles of 'later' and XOR them with 'earlier'. On
1105 * the off chance that the result is 0, we loop until it isn't.
1107 random_seed = earlier.tv_usec ^
1108 ((later.tv_usec << 16) |
1109 ((later.tv_usec >> 16) & 0xffff));
1112 for (i = 0; i < MAXLISTEN; i++)
1114 if (ListenSocket[i] == -1)
1116 if (FD_ISSET(ListenSocket[i], &rmask))
1118 port = ConnCreate(ListenSocket[i]);
1121 BackendStartup(port);
1124 * We no longer need the open socket or port structure
1127 StreamClose(port->sock);
1135 * If no background writer process is running, and we are not in
1136 * a state that prevents it, start one. It doesn't matter if this
1137 * fails, we'll just try again later.
1139 if (BgWriterPID == 0 && StartupPID == 0 && !FatalError)
1141 BgWriterPID = StartBackgroundWriter();
1142 /* If shutdown is pending, set it going */
1143 if (Shutdown > NoShutdown && BgWriterPID != 0)
1144 kill(BgWriterPID, SIGUSR2);
1147 /* If we have lost the stats collector, try to start a new one */
1148 if (!pgstat_is_running)
1152 * Touch the socket and lock file at least every ten minutes, to ensure
1153 * that they are not removed by overzealous /tmp-cleaning tasks.
1156 if (now - last_touch_time >= 10 * 60)
1159 TouchSocketLockFile();
1160 last_touch_time = now;
1167 * Initialise the masks for select() for the ports we are listening on.
1168 * Return the number of sockets to listen on.
1171 initMasks(fd_set *rmask)
1178 for (i = 0; i < MAXLISTEN; i++)
1180 int fd = ListenSocket[i];
1194 * Read the startup packet and do something according to it.
1196 * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
1197 * not return at all.
1199 * (Note that ereport(FATAL) stuff is sent to the client, so only use it
1200 * if that's what you want. Return STATUS_ERROR if you don't want to
1201 * send anything to the client, which would typically be appropriate
1202 * if we detect a communications failure.)
1205 ProcessStartupPacket(Port *port, bool SSLdone)
1209 ProtocolVersion proto;
1210 MemoryContext oldcontext;
1212 if (pq_getbytes((char *) &len, 4) == EOF)
1215 * EOF after SSLdone probably means the client didn't like our
1216 * response to NEGOTIATE_SSL_CODE. That's not an error condition,
1217 * so don't clutter the log with a complaint.
1221 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1222 errmsg("incomplete startup packet")));
1223 return STATUS_ERROR;
1229 if (len < (int32) sizeof(ProtocolVersion) ||
1230 len > MAX_STARTUP_PACKET_LENGTH)
1233 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1234 errmsg("invalid length of startup packet")));
1235 return STATUS_ERROR;
1239 * Allocate at least the size of an old-style startup packet, plus one
1240 * extra byte, and make sure all are zeroes. This ensures we will
1241 * have null termination of all strings, in both fixed- and
1242 * variable-length packet layouts.
1244 if (len <= (int32) sizeof(StartupPacket))
1245 buf = palloc0(sizeof(StartupPacket) + 1);
1247 buf = palloc0(len + 1);
1249 if (pq_getbytes(buf, len) == EOF)
1252 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1253 errmsg("incomplete startup packet")));
1254 return STATUS_ERROR;
1258 * The first field is either a protocol version number or a special
1261 port->proto = proto = ntohl(*((ProtocolVersion *) buf));
1263 if (proto == CANCEL_REQUEST_CODE)
1265 processCancelRequest(port, buf);
1266 return 127; /* XXX */
1269 if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
1274 /* No SSL when disabled or on Unix sockets */
1275 if (!EnableSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
1278 SSLok = 'S'; /* Support for SSL */
1280 SSLok = 'N'; /* No support for SSL */
1282 if (send(port->sock, &SSLok, 1, 0) != 1)
1285 (errcode_for_socket_access(),
1286 errmsg("failed to send SSL negotiation response: %m")));
1287 return STATUS_ERROR; /* close the connection */
1291 if (SSLok == 'S' && secure_open_server(port) == -1)
1292 return STATUS_ERROR;
1294 /* regular startup packet, cancel, etc packet should follow... */
1295 /* but not another SSL negotiation request */
1296 return ProcessStartupPacket(port, true);
1299 /* Could add additional special packet types here */
1302 * Set FrontendProtocol now so that ereport() knows what format to
1303 * send if we fail during startup.
1305 FrontendProtocol = proto;
1307 /* Check we can handle the protocol the frontend is using. */
1309 if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
1310 PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
1311 (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
1312 PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
1314 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1315 errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
1316 PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
1317 PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST),
1318 PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST),
1319 PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))));
1322 * Now fetch parameters out of startup packet and save them into the
1323 * Port structure. All data structures attached to the Port struct
1324 * must be allocated in TopMemoryContext so that they won't disappear
1325 * when we pass them to PostgresMain (see BackendRun). We need not
1326 * worry about leaking this storage on failure, since we aren't in the
1327 * postmaster process anymore.
1329 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1331 if (PG_PROTOCOL_MAJOR(proto) >= 3)
1333 int32 offset = sizeof(ProtocolVersion);
1336 * Scan packet body for name/option pairs. We can assume any
1337 * string beginning within the packet body is null-terminated,
1338 * thanks to zeroing extra byte above.
1340 port->guc_options = NIL;
1342 while (offset < len)
1344 char *nameptr = ((char *) buf) + offset;
1348 if (*nameptr == '\0')
1349 break; /* found packet terminator */
1350 valoffset = offset + strlen(nameptr) + 1;
1351 if (valoffset >= len)
1352 break; /* missing value, will complain below */
1353 valptr = ((char *) buf) + valoffset;
1355 if (strcmp(nameptr, "database") == 0)
1356 port->database_name = pstrdup(valptr);
1357 else if (strcmp(nameptr, "user") == 0)
1358 port->user_name = pstrdup(valptr);
1359 else if (strcmp(nameptr, "options") == 0)
1360 port->cmdline_options = pstrdup(valptr);
1363 /* Assume it's a generic GUC option */
1364 port->guc_options = lappend(port->guc_options,
1366 port->guc_options = lappend(port->guc_options,
1369 offset = valoffset + strlen(valptr) + 1;
1373 * If we didn't find a packet terminator exactly at the end of the
1374 * given packet length, complain.
1376 if (offset != len - 1)
1378 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1379 errmsg("invalid startup packet layout: expected terminator as last byte")));
1384 * Get the parameters from the old-style, fixed-width-fields
1385 * startup packet as C strings. The packet destination was
1386 * cleared first so a short packet has zeros silently added. We
1387 * have to be prepared to truncate the pstrdup result for oversize
1390 StartupPacket *packet = (StartupPacket *) buf;
1392 port->database_name = pstrdup(packet->database);
1393 if (strlen(port->database_name) > sizeof(packet->database))
1394 port->database_name[sizeof(packet->database)] = '\0';
1395 port->user_name = pstrdup(packet->user);
1396 if (strlen(port->user_name) > sizeof(packet->user))
1397 port->user_name[sizeof(packet->user)] = '\0';
1398 port->cmdline_options = pstrdup(packet->options);
1399 if (strlen(port->cmdline_options) > sizeof(packet->options))
1400 port->cmdline_options[sizeof(packet->options)] = '\0';
1401 port->guc_options = NIL;
1404 /* Check a user name was given. */
1405 if (port->user_name == NULL || port->user_name[0] == '\0')
1407 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1408 errmsg("no PostgreSQL user name specified in startup packet")));
1410 /* The database defaults to the user name. */
1411 if (port->database_name == NULL || port->database_name[0] == '\0')
1412 port->database_name = pstrdup(port->user_name);
1414 if (Db_user_namespace)
1417 * If user@, it is a global user, remove '@'. We only want to do
1418 * this if there is an '@' at the end and no earlier in the user
1419 * string or they may fake as a local user of another database
1420 * attaching to this database.
1422 if (strchr(port->user_name, '@') ==
1423 port->user_name + strlen(port->user_name) - 1)
1424 *strchr(port->user_name, '@') = '\0';
1427 /* Append '@' and dbname */
1430 db_user = palloc(strlen(port->user_name) +
1431 strlen(port->database_name) + 2);
1432 sprintf(db_user, "%s@%s", port->user_name, port->database_name);
1433 port->user_name = db_user;
1438 * Truncate given database and user names to length of a Postgres
1439 * name. This avoids lookup failures when overlength names are given.
1441 if (strlen(port->database_name) >= NAMEDATALEN)
1442 port->database_name[NAMEDATALEN - 1] = '\0';
1443 if (strlen(port->user_name) >= NAMEDATALEN)
1444 port->user_name[NAMEDATALEN - 1] = '\0';
1447 * Done putting stuff in TopMemoryContext.
1449 MemoryContextSwitchTo(oldcontext);
1452 * If we're going to reject the connection due to database state, say
1453 * so now instead of wasting cycles on an authentication exchange.
1454 * (This also allows a pg_ping utility to be written.)
1456 switch (port->canAcceptConnections)
1460 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1461 errmsg("the database system is starting up")));
1465 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1466 errmsg("the database system is shutting down")));
1470 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1471 errmsg("the database system is in recovery mode")));
1475 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
1476 errmsg("sorry, too many clients already")));
1488 * The client has sent a cancel request packet, not a normal
1489 * start-a-new-connection packet. Perform the necessary processing.
1490 * Nothing is sent back to the client.
1493 processCancelRequest(Port *port, void *pkt)
1495 CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
1497 long cancelAuthCode;
1499 #ifndef EXEC_BACKEND
1505 backendPID = (int) ntohl(canc->backendPID);
1506 cancelAuthCode = (long) ntohl(canc->cancelAuthCode);
1508 if (backendPID == BgWriterPID)
1511 (errmsg_internal("ignoring cancel request for bgwriter process %d",
1517 * See if we have a matching backend. In the EXEC_BACKEND case, we
1518 * can no longer access the postmaster's own backend list, and must
1519 * rely on the duplicate array in shared memory.
1521 #ifndef EXEC_BACKEND
1522 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
1524 bp = (Backend *) DLE_VAL(curr);
1526 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
1528 bp = (Backend *) &ShmemBackendArray[i];
1530 if (bp->pid == backendPID)
1532 if (bp->cancel_key == cancelAuthCode)
1534 /* Found a match; signal that backend to cancel current op */
1536 (errmsg_internal("processing cancel request: sending SIGINT to process %d",
1538 kill(bp->pid, SIGINT);
1541 /* Right PID, wrong key: no way, Jose */
1543 (errmsg_internal("bad key in cancel request for process %d",
1549 /* No matching backend */
1551 (errmsg_internal("bad pid in cancel request for process %d",
1556 * canAcceptConnections --- check to see if database state allows connections.
1558 static enum CAC_state
1559 canAcceptConnections(void)
1561 /* Can't start backends when in startup/shutdown/recovery state. */
1562 if (Shutdown > NoShutdown)
1563 return CAC_SHUTDOWN;
1567 return CAC_RECOVERY;
1570 * Don't start too many children.
1572 * We allow more connections than we can have backends here because some
1573 * might still be authenticating; they might fail auth, or some
1574 * existing backend might exit before the auth cycle is completed. The
1575 * exact MaxBackends limit is enforced when a new backend tries to
1576 * join the shared-inval backend array.
1578 if (CountChildren() >= 2 * MaxBackends)
1586 * ConnCreate -- create a local connection data structure
1589 ConnCreate(int serverFd)
1593 if (!(port = (Port *) calloc(1, sizeof(Port))))
1596 (errcode(ERRCODE_OUT_OF_MEMORY),
1597 errmsg("out of memory")));
1601 if (StreamConnection(serverFd, port) != STATUS_OK)
1603 StreamClose(port->sock);
1610 * Precompute password salt values to use for this connection.
1611 * It's slightly annoying to do this long in advance of knowing
1612 * whether we'll need 'em or not, but we must do the random()
1613 * calls before we fork, not after. Else the postmaster's random
1614 * sequence won't get advanced, and all backends would end up
1615 * using the same salt...
1617 RandomSalt(port->cryptSalt, port->md5Salt);
1625 * ConnFree -- free a local connection data structure
1628 ConnFree(Port *conn)
1638 * ClosePostmasterPorts -- close all the postmaster's open sockets
1640 * This is called during child process startup to release file descriptors
1641 * that are not needed by that child process. The postmaster still has
1642 * them open, of course.
1645 ClosePostmasterPorts(void)
1649 /* Close the listen sockets */
1650 for (i = 0; i < MAXLISTEN; i++)
1652 if (ListenSocket[i] != -1)
1654 StreamClose(ListenSocket[i]);
1655 ListenSocket[i] = -1;
1662 * reset_shared -- reset shared memory and semaphores
1665 reset_shared(unsigned short port)
1668 * Create or re-create shared memory and semaphores.
1670 * Note: in each "cycle of life" we will normally assign the same IPC
1671 * keys (if using SysV shmem and/or semas), since the port number is
1672 * used to determine IPC keys. This helps ensure that we will clean
1673 * up dead IPC objects if the postmaster crashes and is restarted.
1675 CreateSharedMemoryAndSemaphores(false, MaxBackends, port);
1680 * SIGHUP -- reread config files, and tell children to do same
1683 SIGHUP_handler(SIGNAL_ARGS)
1685 int save_errno = errno;
1687 PG_SETMASK(&BlockSig);
1689 if (Shutdown <= SmartShutdown)
1692 (errmsg("received SIGHUP, reloading configuration files")));
1693 ProcessConfigFile(PGC_SIGHUP);
1694 SignalChildren(SIGHUP);
1695 if (BgWriterPID != 0)
1696 kill(BgWriterPID, SIGHUP);
1701 /* Update the starting-point file for future children */
1702 write_nondefault_variables(PGC_SIGHUP);
1706 PG_SETMASK(&UnBlockSig);
1713 * pmdie -- signal handler for processing various postmaster signals.
1718 int save_errno = errno;
1720 PG_SETMASK(&BlockSig);
1723 (errmsg_internal("postmaster received signal %d",
1724 postgres_signal_arg)));
1726 switch (postgres_signal_arg)
1732 * Wait for children to end their work, then shut down.
1734 if (Shutdown >= SmartShutdown)
1736 Shutdown = SmartShutdown;
1738 (errmsg("received smart shutdown request")));
1740 if (DLGetHead(BackendList))
1741 break; /* let reaper() handle this */
1744 * No children left. Begin shutdown of data base system.
1746 if (StartupPID != 0 || FatalError)
1747 break; /* let reaper() handle this */
1748 /* Start the bgwriter if not running */
1749 if (BgWriterPID == 0)
1750 BgWriterPID = StartBackgroundWriter();
1751 /* And tell it to shut down */
1752 if (BgWriterPID != 0)
1753 kill(BgWriterPID, SIGUSR2);
1760 * Abort all children with SIGTERM (rollback active transactions
1761 * and exit) and shut down when they are gone.
1763 if (Shutdown >= FastShutdown)
1765 Shutdown = FastShutdown;
1767 (errmsg("received fast shutdown request")));
1769 if (DLGetHead(BackendList))
1774 (errmsg("aborting any active transactions")));
1775 SignalChildren(SIGTERM);
1776 /* reaper() does the rest */
1782 * No children left. Begin shutdown of data base system.
1784 * Note: if we previously got SIGTERM then we may send SIGUSR2
1785 * to the bgwriter a second time here. This should be harmless.
1787 if (StartupPID != 0 || FatalError)
1788 break; /* let reaper() handle this */
1789 /* Start the bgwriter if not running */
1790 if (BgWriterPID == 0)
1791 BgWriterPID = StartBackgroundWriter();
1792 /* And tell it to shut down */
1793 if (BgWriterPID != 0)
1794 kill(BgWriterPID, SIGUSR2);
1799 * Immediate Shutdown:
1801 * abort all children with SIGQUIT and exit without attempt to
1802 * properly shut down data base system.
1805 (errmsg("received immediate shutdown request")));
1806 if (StartupPID != 0)
1807 kill(StartupPID, SIGQUIT);
1808 if (BgWriterPID != 0)
1809 kill(BgWriterPID, SIGQUIT);
1810 if (DLGetHead(BackendList))
1811 SignalChildren(SIGQUIT);
1816 PG_SETMASK(&UnBlockSig);
1822 * Reaper -- signal handler to cleanup after a backend (child) dies.
1827 int save_errno = errno;
1830 int status; /* backend exit status */
1834 union wait status; /* backend exit status */
1838 int pid; /* process id of dead backend */
1840 PG_SETMASK(&BlockSig);
1843 (errmsg_internal("reaping dead processes")));
1845 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1847 exitstatus = status;
1850 while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
1852 exitstatus = status.w_status;
1854 while ((pid = win32_waitpid(&exitstatus)) > 0)
1857 * We need to do this here, and not in CleanupProc, since this is
1858 * to be called on all children when we are done with them. Could
1859 * move to LogChildExit, but that seems like asking for future
1862 win32_RemoveChild(pid);
1864 #endif /* HAVE_WAITPID */
1867 * Check if this child was the statistics collector. If so, try to
1868 * start a new one. (If fail, we'll try again in future cycles of
1871 if (pgstat_ispgstat(pid))
1873 LogChildExit(LOG, gettext("statistics collector process"),
1880 * Check if this child was a startup process.
1882 if (StartupPID != 0 && pid == StartupPID)
1885 if (exitstatus != 0)
1887 LogChildExit(LOG, gettext("startup process"),
1890 (errmsg("aborting startup due to startup process failure")));
1895 * Startup succeeded - we are done with system startup or recovery.
1900 * Crank up the background writer. It doesn't matter if this
1901 * fails, we'll just try again later.
1903 Assert(BgWriterPID == 0);
1904 BgWriterPID = StartBackgroundWriter();
1907 * Go to shutdown mode if a shutdown request was pending.
1909 if (Shutdown > NoShutdown && BgWriterPID != 0)
1910 kill(BgWriterPID, SIGUSR2);
1916 * Was it the bgwriter?
1918 if (BgWriterPID != 0 && pid == BgWriterPID)
1920 if (exitstatus == 0 && Shutdown > NoShutdown &&
1921 !FatalError && !DLGetHead(BackendList))
1924 * Normal postmaster exit is here: we've seen normal
1925 * exit of the bgwriter after it's been told to shut down.
1926 * We expect that it wrote a shutdown checkpoint. (If
1927 * for some reason it didn't, recovery will occur on next
1928 * postmaster start.)
1933 * Any unexpected exit of the bgwriter is treated as a crash.
1935 LogChildExit(DEBUG2, gettext("background writer process"),
1937 HandleChildCrash(pid, exitstatus);
1942 * Else do standard backend child cleanup.
1944 CleanupProc(pid, exitstatus);
1945 } /* loop over pending child-death reports */
1950 * Wait for all children exit, then reset shmem and
1953 if (DLGetHead(BackendList) || StartupPID != 0 || BgWriterPID != 0)
1956 (errmsg("all server processes terminated; reinitializing")));
1959 reset_shared(PostPortNumber);
1961 StartupPID = StartupDataBase();
1966 if (Shutdown > NoShutdown)
1968 if (DLGetHead(BackendList) || StartupPID != 0)
1970 /* Start the bgwriter if not running */
1971 if (BgWriterPID == 0)
1972 BgWriterPID = StartBackgroundWriter();
1973 /* And tell it to shut down */
1974 if (BgWriterPID != 0)
1975 kill(BgWriterPID, SIGUSR2);
1979 PG_SETMASK(&UnBlockSig);
1986 * CleanupProc -- cleanup after terminated backend.
1988 * Remove all local state associated with backend.
1991 CleanupProc(int pid,
1992 int exitstatus) /* child's exit status. */
1996 LogChildExit(DEBUG2, gettext("server process"), pid, exitstatus);
1999 * If a backend dies in an ugly way (i.e. exit status not 0) then we
2000 * must signal all other backends to quickdie. If exit status is zero
2001 * we assume everything is hunky dory and simply remove the backend
2002 * from the active backend list.
2004 if (exitstatus != 0)
2006 HandleChildCrash(pid, exitstatus);
2010 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2012 Backend *bp = (Backend *) DLE_VAL(curr);
2020 ShmemBackendArrayRemove(pid);
2022 /* Tell the collector about backend termination */
2030 * HandleChildCrash -- cleanup after failed backend or bgwriter.
2032 * The objectives here are to clean up our local state about the child
2033 * process, and to signal all other remaining children to quickdie.
2036 HandleChildCrash(int pid,
2037 int exitstatus) /* child's exit status. */
2044 * Make log entry unless there was a previous crash (if so, nonzero
2045 * exit status is to be expected in SIGQUIT response; don't clutter log)
2050 (pid == BgWriterPID) ?
2051 gettext("background writer process") :
2052 gettext("server process"),
2055 (errmsg("terminating any other active server processes")));
2058 /* Process regular backends */
2059 for (curr = DLGetHead(BackendList); curr; curr = next)
2061 next = DLGetSucc(curr);
2062 bp = (Backend *) DLE_VAL(curr);
2066 * Found entry for freshly-dead backend, so remove it.
2072 ShmemBackendArrayRemove(pid);
2074 /* Tell the collector about backend termination */
2076 /* Keep looping so we can signal remaining backends */
2081 * This backend is still alive. Unless we did so already,
2082 * tell it to commit hara-kiri.
2084 * SIGQUIT is the special signal that says exit without proc_exit
2085 * and let the user know what's going on. But if SendStop is
2086 * set (-s on command line), then we send SIGSTOP instead, so
2087 * that we can get core dumps from all backends by hand.
2092 (errmsg_internal("sending %s to process %d",
2093 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2095 kill(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
2100 /* Take care of the bgwriter too */
2101 if (pid == BgWriterPID)
2103 else if (BgWriterPID != 0 && !FatalError)
2106 (errmsg_internal("sending %s to process %d",
2107 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2108 (int) BgWriterPID)));
2109 kill(BgWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
2116 * Log the death of a child process.
2119 LogChildExit(int lev, const char *procname, int pid, int exitstatus)
2121 if (WIFEXITED(exitstatus))
2125 * translator: %s is a noun phrase describing a child process,
2126 * such as "server process"
2128 (errmsg("%s (PID %d) exited with exit code %d",
2129 procname, pid, WEXITSTATUS(exitstatus))));
2130 else if (WIFSIGNALED(exitstatus))
2134 * translator: %s is a noun phrase describing a child process,
2135 * such as "server process"
2137 (errmsg("%s (PID %d) was terminated by signal %d",
2138 procname, pid, WTERMSIG(exitstatus))));
2143 * translator: %s is a noun phrase describing a child process,
2144 * such as "server process"
2146 (errmsg("%s (PID %d) exited with unexpected status %d",
2147 procname, pid, exitstatus)));
2151 * Send a signal to all backend children.
2154 SignalChildren(int signal)
2158 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2160 Backend *bp = (Backend *) DLE_VAL(curr);
2163 (errmsg_internal("sending signal %d to process %d",
2164 signal, (int) bp->pid)));
2165 kill(bp->pid, signal);
2170 * BackendStartup -- start backend process
2172 * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
2175 BackendStartup(Port *port)
2177 Backend *bn; /* for backend cleanup */
2180 #ifdef LINUX_PROFILE
2181 struct itimerval prof_itimer;
2185 * Compute the cancel key that will be assigned to this backend. The
2186 * backend will have its own copy in the forked-off process' value of
2187 * MyCancelKey, so that it can transmit the key to the frontend.
2189 MyCancelKey = PostmasterRandom();
2192 * Make room for backend data structure. Better before the fork() so
2193 * we can handle failure cleanly.
2195 bn = (Backend *) malloc(sizeof(Backend));
2199 (errcode(ERRCODE_OUT_OF_MEMORY),
2200 errmsg("out of memory")));
2201 return STATUS_ERROR;
2204 /* Pass down canAcceptConnections state (kluge for EXEC_BACKEND case) */
2205 port->canAcceptConnections = canAcceptConnections();
2208 * Flush stdio channels just before fork, to avoid double-output
2209 * problems. Ideally we'd use fflush(NULL) here, but there are still a
2210 * few non-ANSI stdio libraries out there (like SunOS 4.1.x) that
2211 * coredump if we do. Presently stdout and stderr are the only stdio
2212 * output channels used by the postmaster, so fflush'ing them should
2220 pid = backend_forkexec(port);
2222 #else /* !EXEC_BACKEND */
2224 #ifdef LINUX_PROFILE
2227 * Linux's fork() resets the profiling timer in the child process. If
2228 * we want to profile child processes then we need to save and restore
2229 * the timer setting. This is a waste of time if not profiling,
2230 * however, so only do it if commanded by specific -DLINUX_PROFILE
2233 getitimer(ITIMER_PROF, &prof_itimer);
2237 /* Specific beos actions before backend startup */
2238 beos_before_backend_startup();
2243 if (pid == 0) /* child */
2245 #ifdef LINUX_PROFILE
2246 setitimer(ITIMER_PROF, &prof_itimer, NULL);
2250 /* Specific beos backend startup actions */
2251 beos_backend_startup();
2255 proc_exit(BackendRun(port));
2258 #endif /* EXEC_BACKEND */
2262 /* in parent, fork failed */
2263 int save_errno = errno;
2266 /* Specific beos backend startup actions */
2267 beos_backend_startup_failed();
2272 (errmsg("could not fork new process for connection: %m")));
2273 report_fork_failure_to_client(port, save_errno);
2274 return STATUS_ERROR;
2277 /* in parent, successful fork */
2279 (errmsg_internal("forked new backend, pid=%d socket=%d",
2280 (int) pid, port->sock)));
2283 * Everything's been successful, it's safe to add this backend to our
2287 bn->cancel_key = MyCancelKey;
2288 DLAddHead(BackendList, DLNewElem(bn));
2290 ShmemBackendArrayAdd(bn);
2297 * Try to report backend fork() failure to client before we close the
2298 * connection. Since we do not care to risk blocking the postmaster on
2299 * this connection, we set the connection to non-blocking and try only once.
2301 * This is grungy special-purpose code; we cannot use backend libpq since
2302 * it's not up and running.
2305 report_fork_failure_to_client(Port *port, int errnum)
2309 /* Format the error message packet (always V2 protocol) */
2310 snprintf(buffer, sizeof(buffer), "E%s%s\n",
2311 gettext("could not fork new process for connection: "),
2314 /* Set port to non-blocking. Don't do send() if this fails */
2315 if (!set_noblock(port->sock))
2318 send(port->sock, buffer, strlen(buffer) + 1, 0);
2323 * split_opts -- split a string of options and append it to an argv array
2325 * NB: the string is destructively modified!
2327 * Since no current POSTGRES arguments require any quoting characters,
2328 * we can use the simple-minded tactic of assuming each set of space-
2329 * delimited characters is a separate argv element.
2331 * If you don't like that, well, we *used* to pass the whole option string
2332 * as ONE argument to execl(), which was even less intelligent...
2335 split_opts(char **argv, int *argcp, char *s)
2339 while (isspace((unsigned char) *s))
2343 argv[(*argcp)++] = s;
2344 while (*s && !isspace((unsigned char) *s))
2353 * BackendRun -- perform authentication, and if successful,
2354 * set up the backend's argument list and invoke PostgresMain()
2357 * Shouldn't return at all.
2358 * If PostgresMain() fails, return status.
2361 BackendRun(Port *port)
2366 char remote_host[NI_MAXHOST];
2367 char remote_port[NI_MAXSERV];
2368 char remote_ps_data[NI_MAXHOST];
2376 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
2379 * Let's clean up ourselves as the postmaster child, and close the
2380 * postmaster's listen sockets
2382 ClosePostmasterPorts();
2384 /* We don't want the postmaster's proc_exit() handlers */
2388 * Signal handlers setting is moved to tcop/postgres...
2391 /* Save port etc. for ps status */
2394 /* Reset MyProcPid to new backend's pid */
2395 MyProcPid = getpid();
2398 * PreAuthDelay is a debugging aid for investigating problems in the
2399 * authentication cycle: it can be set in postgresql.conf to allow
2400 * time to attach to the newly-forked backend with a debugger. (See
2401 * also the -W backend switch, which we allow clients to pass through
2402 * PGOPTIONS, but it is not honored until after authentication.)
2404 if (PreAuthDelay > 0)
2405 pg_usleep(PreAuthDelay * 1000000L);
2407 ClientAuthInProgress = true; /* limit visibility of log messages */
2409 /* save start time for end of session reporting */
2410 gettimeofday(&(port->session_start), NULL);
2412 /* set these to empty in case they are needed before we set them up */
2413 port->remote_host = "";
2414 port->remote_port = "";
2415 port->commandTag = "";
2418 * Initialize libpq and enable reporting of ereport errors to the
2419 * client. Must do this now because authentication uses libpq to send
2422 pq_init(); /* initialize libpq to talk to client */
2423 whereToSendOutput = Remote; /* now safe to ereport to client */
2426 * We arrange for a simple exit(0) if we receive SIGTERM or SIGQUIT
2427 * during any client authentication related communication. Otherwise
2428 * the postmaster cannot shutdown the database FAST or IMMED cleanly
2429 * if a buggy client blocks a backend during authentication.
2431 pqsignal(SIGTERM, authdie);
2432 pqsignal(SIGQUIT, authdie);
2433 pqsignal(SIGALRM, authdie);
2434 PG_SETMASK(&AuthBlockSig);
2437 * Get the remote host name and port for logging and status display.
2439 remote_host[0] = '\0';
2440 remote_port[0] = '\0';
2441 if (getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2442 remote_host, sizeof(remote_host),
2443 remote_port, sizeof(remote_port),
2444 (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV))
2446 int ret = getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2447 remote_host, sizeof(remote_host),
2448 remote_port, sizeof(remote_port),
2449 NI_NUMERICHOST | NI_NUMERICSERV);
2453 (errmsg("getnameinfo_all() failed: %s",
2454 gai_strerror(ret))));
2456 snprintf(remote_ps_data, sizeof(remote_ps_data),
2457 remote_port[0] == '\0' ? "%s" : "%s(%s)",
2458 remote_host, remote_port);
2460 if (Log_connections)
2462 (errmsg("connection received: host=%s port=%s",
2463 remote_host, remote_port)));
2466 * save remote_host and remote_port in port stucture
2468 port->remote_host = strdup(remote_host);
2469 port->remote_port = strdup(remote_port);
2472 * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.c
2473 * etcetera from the postmaster, and have to load them ourselves.
2474 * Build the PostmasterContext (which didn't exist before, in this
2475 * process) to contain the data.
2477 * FIXME: [fork/exec] Ugh. Is there a way around this overhead?
2480 Assert(PostmasterContext == NULL);
2481 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
2483 ALLOCSET_DEFAULT_MINSIZE,
2484 ALLOCSET_DEFAULT_INITSIZE,
2485 ALLOCSET_DEFAULT_MAXSIZE);
2486 MemoryContextSwitchTo(PostmasterContext);
2495 * Ready to begin client interaction. We will give up and exit(0)
2496 * after a time delay, so that a broken client can't hog a connection
2497 * indefinitely. PreAuthDelay doesn't count against the time limit.
2499 if (!enable_sig_alarm(AuthenticationTimeout * 1000, false))
2500 elog(FATAL, "could not set timer for authorization timeout");
2503 * Receive the startup packet (which might turn out to be a cancel
2506 status = ProcessStartupPacket(port, false);
2508 if (status != STATUS_OK)
2512 * Now that we have the user and database name, we can set the process
2513 * title for ps. It's good to do this as early as possible in
2516 init_ps_display(port->user_name, port->database_name, remote_ps_data);
2517 set_ps_display("authentication");
2520 * Now perform authentication exchange.
2522 ClientAuthentication(port); /* might not return, if failure */
2525 * Done with authentication. Disable timeout, and prevent
2526 * SIGTERM/SIGQUIT again until backend startup is complete.
2528 if (!disable_sig_alarm(false))
2529 elog(FATAL, "could not disable timer for authorization timeout");
2530 PG_SETMASK(&BlockSig);
2532 if (Log_connections)
2534 (errmsg("connection authorized: user=%s database=%s",
2535 port->user_name, port->database_name)));
2538 * Don't want backend to be able to see the postmaster random number
2539 * generator state. We have to clobber the static random_seed *and*
2540 * start a new random sequence in the random() library function.
2543 gettimeofday(&now, &tz);
2544 srandom((unsigned int) now.tv_usec);
2548 * Now, build the argv vector that will be given to PostgresMain.
2550 * The layout of the command line is
2551 * postgres [secure switches] -p databasename [insecure switches]
2552 * where the switches after -p come from the client request.
2554 * The maximum possible number of commandline arguments that could come
2555 * from ExtraOptions or port->cmdline_options is (strlen + 1) / 2; see
2559 maxac = 10; /* for fixed args supplied below */
2560 maxac += (strlen(ExtraOptions) + 1) / 2;
2561 if (port->cmdline_options)
2562 maxac += (strlen(port->cmdline_options) + 1) / 2;
2564 av = (char **) MemoryContextAlloc(TopMemoryContext,
2565 maxac * sizeof(char *));
2568 av[ac++] = "postgres";
2571 * Pass the requested debugging level along to the backend.
2575 snprintf(debugbuf, sizeof(debugbuf), "-d%d", debug_flag);
2576 av[ac++] = debugbuf;
2580 * Pass any backend switches specified with -o in the postmaster's own
2581 * command line. We assume these are secure. (It's OK to mangle
2582 * ExtraOptions now, since we're safely inside a subprocess.)
2584 split_opts(av, &ac, ExtraOptions);
2586 /* Tell the backend what protocol the frontend is using. */
2587 snprintf(protobuf, sizeof(protobuf), "-v%u", port->proto);
2588 av[ac++] = protobuf;
2591 * Tell the backend it is being called from the postmaster, and which
2592 * database to use. -p marks the end of secure switches.
2595 av[ac++] = port->database_name;
2598 * Pass the (insecure) option switches from the connection request.
2599 * (It's OK to mangle port->cmdline_options now.)
2601 if (port->cmdline_options)
2602 split_opts(av, &ac, port->cmdline_options);
2609 * Release postmaster's working memory context so that backend can
2610 * recycle the space. Note this does not trash *MyProcPort, because
2611 * ConnCreate() allocated that space with malloc() ... else we'd need
2612 * to copy the Port data here. Also, subsidiary data such as the
2613 * username isn't lost either; see ProcessStartupPacket().
2615 MemoryContextSwitchTo(TopMemoryContext);
2616 MemoryContextDelete(PostmasterContext);
2617 PostmasterContext = NULL;
2620 * Debug: print arguments being passed to backend
2623 (errmsg_internal("%s child[%d]: starting with (",
2624 progname, getpid())));
2625 for (i = 0; i < ac; ++i)
2627 (errmsg_internal("\t%s", av[i])));
2629 (errmsg_internal(")")));
2631 ClientAuthInProgress = false; /* client_min_messages is active
2634 return (PostgresMain(ac, av, port->user_name));
2641 * postmaster_forkexec -- fork and exec a postmaster subprocess
2643 * The caller must have set up the argv array already, except for argv[2]
2644 * which will be filled with the name of the temp variable file.
2646 * Returns the child process PID, or -1 on fork failure (a suitable error
2647 * message has been logged on failure).
2649 * All uses of this routine will dispatch to SubPostmasterMain in the
2653 postmaster_forkexec(int argc, char *argv[])
2657 /* This entry point passes dummy values for the Port variables */
2658 memset(&port, 0, sizeof(port));
2659 return internal_forkexec(argc, argv, &port);
2663 * backend_forkexec -- fork/exec off a backend process
2665 * returns the pid of the fork/exec'd process, or -1 on failure
2668 backend_forkexec(Port *port)
2673 av[ac++] = "postgres";
2674 av[ac++] = "-forkbackend";
2675 av[ac++] = NULL; /* filled in by internal_forkexec */
2678 Assert(ac < lengthof(av));
2680 return internal_forkexec(ac, av, port);
2684 internal_forkexec(int argc, char *argv[], Port *port)
2687 char tmpfilename[MAXPGPATH];
2689 if (!write_backend_variables(tmpfilename, port))
2690 return -1; /* log made by write_backend_variables */
2692 /* Make sure caller set up argv properly */
2694 Assert(argv[argc] == NULL);
2695 Assert(strncmp(argv[1], "-fork", 5) == 0);
2696 Assert(argv[2] == NULL);
2698 /* Insert temp file name after -fork argument */
2699 argv[2] = tmpfilename;
2702 pid = win32_forkexec(postgres_exec_path, argv);
2704 /* Fire off execv in child */
2705 if ((pid = fork()) == 0)
2707 if (execv(postgres_exec_path, argv) < 0)
2710 (errmsg("could not exec backend process \"%s\": %m",
2711 postgres_exec_path)));
2712 /* We're already in the child process here, can't return */
2718 return pid; /* Parent returns pid, or -1 on fork failure */
2722 * SubPostmasterMain -- Get the fork/exec'd process into a state equivalent
2723 * to what it would be if we'd simply forked on Unix, and then
2724 * dispatch to the appropriate place.
2726 * The first two command line arguments are expected to be "-forkFOO"
2727 * (where FOO indicates which postmaster child we are to become), and
2728 * the name of a variables file that we can read to load data that would
2729 * have been inherited by fork() on Unix. Remaining arguments go to the
2730 * subprocess FooMain() routine.
2733 SubPostmasterMain(int argc, char *argv[])
2737 /* Do this sooner rather than later... */
2738 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
2740 MyProcPid = getpid(); /* reset MyProcPid */
2742 /* In EXEC_BACKEND case we will not have inherited these settings */
2743 IsPostmasterEnvironment = true;
2744 whereToSendOutput = None;
2746 PG_SETMASK(&BlockSig);
2748 /* Setup essential subsystems */
2749 MemoryContextInit();
2750 InitializeGUCOptions();
2752 /* Check we got appropriate args */
2754 elog(FATAL, "invalid subpostmaster invocation");
2756 /* Read in file-based context */
2757 memset(&port, 0, sizeof(Port));
2758 read_backend_variables(argv[2], &port);
2759 read_nondefault_variables();
2761 /* Run backend or appropriate child */
2762 if (strcmp(argv[1], "-forkbackend") == 0)
2764 /* BackendRun will close sockets */
2766 /* Attach process to shared segments */
2767 CreateSharedMemoryAndSemaphores(false, MaxBackends, 0);
2769 Assert(argc == 3); /* shouldn't be any more args */
2770 proc_exit(BackendRun(&port));
2772 if (strcmp(argv[1], "-forkboot") == 0)
2774 /* Close the postmaster's sockets */
2775 ClosePostmasterPorts();
2777 /* Attach process to shared segments */
2778 CreateSharedMemoryAndSemaphores(false, MaxBackends, 0);
2780 BootstrapMain(argc - 2, argv + 2);
2783 if (strcmp(argv[1], "-forkbuf") == 0)
2785 /* Close the postmaster's sockets */
2786 ClosePostmasterPorts();
2788 /* Do not want to attach to shared memory */
2790 PgstatBufferMain(argc, argv);
2793 if (strcmp(argv[1], "-forkcol") == 0)
2796 * Do NOT close postmaster sockets here, because we are forking from
2797 * pgstat buffer process, which already did it.
2800 /* Do not want to attach to shared memory */
2802 PgstatCollectorMain(argc, argv);
2806 return 1; /* shouldn't get here */
2809 #endif /* EXEC_BACKEND */
2813 * ExitPostmaster -- cleanup
2815 * Do NOT call exit() directly --- always go through here!
2818 ExitPostmaster(int status)
2820 /* should cleanup shared memory and kill all backends */
2823 * Not sure of the semantics here. When the Postmaster dies, should
2824 * the backends all be killed? probably not.
2826 * MUST -- vadim 05-10-1999
2833 * sigusr1_handler - handle signal conditions from child processes
2836 sigusr1_handler(SIGNAL_ARGS)
2838 int save_errno = errno;
2840 PG_SETMASK(&BlockSig);
2842 if (CheckPostmasterSignal(PMSIGNAL_PASSWORD_CHANGE))
2845 * Password or group file has changed.
2851 if (CheckPostmasterSignal(PMSIGNAL_WAKEN_CHILDREN))
2854 * Send SIGUSR1 to all children (triggers
2855 * CatchupInterruptHandler). See storage/ipc/sinval[adt].c for the
2858 if (Shutdown <= SmartShutdown)
2859 SignalChildren(SIGUSR1);
2862 PG_SETMASK(&UnBlockSig);
2869 * Dummy signal handler
2871 * We use this for signals that we don't actually use in the postmaster,
2872 * but we do use in backends. If we were to SIG_IGN such signals in the
2873 * postmaster, then a newly started backend might drop a signal that arrives
2874 * before it's able to reconfigure its signal processing. (See notes in
2878 dummy_handler(SIGNAL_ARGS)
2884 * CharRemap: given an int in range 0..61, produce textual encoding of it
2885 * per crypt(3) conventions.
2909 RandomSalt(char *cryptSalt, char *md5Salt)
2911 long rand = PostmasterRandom();
2913 cryptSalt[0] = CharRemap(rand % 62);
2914 cryptSalt[1] = CharRemap(rand / 62);
2917 * It's okay to reuse the first random value for one of the MD5 salt
2918 * bytes, since only one of the two salts will be sent to the client.
2919 * After that we need to compute more random bits.
2921 * We use % 255, sacrificing one possible byte value, so as to ensure
2922 * that all bits of the random() value participate in the result.
2923 * While at it, add one to avoid generating any null bytes.
2925 md5Salt[0] = (rand % 255) + 1;
2926 rand = PostmasterRandom();
2927 md5Salt[1] = (rand % 255) + 1;
2928 rand = PostmasterRandom();
2929 md5Salt[2] = (rand % 255) + 1;
2930 rand = PostmasterRandom();
2931 md5Salt[3] = (rand % 255) + 1;
2938 PostmasterRandom(void)
2940 static bool initialized = false;
2944 Assert(random_seed != 0);
2945 srandom(random_seed);
2953 * Count up number of child processes.
2961 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2970 * StartChildProcess -- start a non-backend child process for the postmaster
2972 * xlog determines what kind of child will be started. All child types
2973 * initially go to BootstrapMain, which will handle common setup.
2975 * Return value of StartChildProcess is subprocess' PID, or 0 if failed
2976 * to start subprocess.
2979 StartChildProcess(int xlop)
2985 #ifdef LINUX_PROFILE
2986 struct itimerval prof_itimer;
2990 * Set up command-line arguments for subprocess
2992 av[ac++] = "postgres";
2995 av[ac++] = "-forkboot";
2996 av[ac++] = NULL; /* filled in by postmaster_forkexec */
2999 snprintf(xlbuf, sizeof(xlbuf), "-x%d", xlop);
3003 av[ac++] = "template1";
3006 Assert(ac < lengthof(av));
3009 * Flush stdio channels (see comments in BackendStartup)
3016 pid = postmaster_forkexec(ac, av);
3018 #else /* !EXEC_BACKEND */
3020 #ifdef LINUX_PROFILE
3021 /* see comments in BackendStartup */
3022 getitimer(ITIMER_PROF, &prof_itimer);
3026 /* Specific beos actions before backend startup */
3027 beos_before_backend_startup();
3032 if (pid == 0) /* child */
3034 #ifdef LINUX_PROFILE
3035 setitimer(ITIMER_PROF, &prof_itimer, NULL);
3039 /* Specific beos actions after backend startup */
3040 beos_backend_startup();
3043 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
3045 /* Close the postmaster's sockets */
3046 ClosePostmasterPorts();
3048 /* Lose the postmaster's on-exit routines and port connections */
3051 BootstrapMain(ac, av);
3055 #endif /* EXEC_BACKEND */
3059 /* in parent, fork failed */
3060 int save_errno = errno;
3063 /* Specific beos actions before backend startup */
3064 beos_backend_startup_failed();
3069 case BS_XLOG_STARTUP:
3071 (errmsg("could not fork startup process: %m")));
3073 case BS_XLOG_BGWRITER:
3075 (errmsg("could not fork background writer process: %m")));
3079 (errmsg("could not fork process: %m")));
3084 * fork failure is fatal during startup, but there's no need
3085 * to choke immediately if starting other child types fails.
3087 if (xlop == BS_XLOG_STARTUP)
3093 * in parent, successful fork
3100 * Create the opts file
3103 CreateOptsFile(int argc, char *argv[], char *fullprogname)
3105 char filename[MAXPGPATH];
3109 snprintf(filename, sizeof(filename), "%s/postmaster.opts", DataDir);
3111 if ((fp = fopen(filename, "w")) == NULL)
3113 elog(LOG, "could not create file \"%s\": %m", filename);
3117 fprintf(fp, "%s", fullprogname);
3118 for (i = 1; i < argc; i++)
3119 fprintf(fp, " '%s'", argv[i]);
3124 elog(LOG, "could not write file \"%s\": %m", filename);
3132 * This should be used only for reporting "interactive" errors (essentially,
3133 * bogus arguments on the command line). Once the postmaster is launched,
3134 * use ereport. In particular, don't use this for anything that occurs
3135 * after pmdaemonize.
3138 postmaster_error(const char *fmt,...)
3142 fprintf(stderr, "%s: ", progname);
3144 vfprintf(stderr, gettext(fmt), ap);
3146 fprintf(stderr, "\n");
3153 * The following need to be available to the read/write_backend_variables
3156 #include "storage/spin.h"
3158 extern slock_t *ShmemLock;
3159 extern slock_t *ShmemIndexLock;
3160 extern void *ShmemIndexAlloc;
3161 typedef struct LWLock LWLock;
3162 extern LWLock *LWLockArray;
3163 extern slock_t *ProcStructLock;
3164 extern int pgStatSock;
3166 #define write_var(var,fp) fwrite((void*)&(var),sizeof(var),1,fp)
3167 #define read_var(var,fp) fread((void*)&(var),sizeof(var),1,fp)
3168 #define write_array_var(var,fp) fwrite((void*)(var),sizeof(var),1,fp)
3169 #define read_array_var(var,fp) fread((void*)(var),sizeof(var),1,fp)
3172 write_backend_variables(char *filename, Port *port)
3174 static unsigned long tmpBackendFileNum = 0;
3176 char str_buf[MAXPGPATH];
3178 /* Calculate name for temp file in caller's buffer */
3180 snprintf(filename, MAXPGPATH, "%s/%s/%s.backend_var.%d.%lu",
3181 DataDir, PG_TEMP_FILES_DIR, PG_TEMP_FILE_PREFIX,
3182 MyProcPid, ++tmpBackendFileNum);
3185 fp = AllocateFile(filename, PG_BINARY_W);
3188 /* As per OpenTemporaryFile... */
3189 char dirname[MAXPGPATH];
3191 snprintf(dirname, MAXPGPATH, "%s/%s", DataDir, PG_TEMP_FILES_DIR);
3192 mkdir(dirname, S_IRWXU);
3194 fp = AllocateFile(filename, PG_BINARY_W);
3198 (errcode_for_file_access(),
3199 errmsg("could not create file \"%s\": %m",
3206 write_var(port->sock, fp);
3207 write_var(port->proto, fp);
3208 write_var(port->laddr, fp);
3209 write_var(port->raddr, fp);
3210 write_var(port->canAcceptConnections, fp);
3211 write_var(port->cryptSalt, fp);
3212 write_var(port->md5Salt, fp);
3215 * XXX FIXME later: writing these strings as MAXPGPATH bytes always is
3216 * probably a waste of resources
3219 StrNCpy(str_buf, DataDir, MAXPGPATH);
3220 write_array_var(str_buf, fp);
3222 write_array_var(ListenSocket, fp);
3224 write_var(MyCancelKey, fp);
3226 write_var(UsedShmemSegID, fp);
3227 write_var(UsedShmemSegAddr, fp);
3229 write_var(ShmemLock, fp);
3230 write_var(ShmemIndexLock, fp);
3231 write_var(ShmemVariableCache, fp);
3232 write_var(ShmemIndexAlloc, fp);
3233 write_var(ShmemBackendArray, fp);
3235 write_var(LWLockArray, fp);
3236 write_var(ProcStructLock, fp);
3237 write_var(pgStatSock, fp);
3239 write_var(debug_flag, fp);
3240 write_var(PostmasterPid, fp);
3242 write_var(PostmasterHandle, fp);
3245 StrNCpy(str_buf, my_exec_path, MAXPGPATH);
3246 write_array_var(str_buf, fp);
3248 write_array_var(ExtraOptions, fp);
3250 StrNCpy(str_buf, setlocale(LC_COLLATE, NULL), MAXPGPATH);
3251 write_array_var(str_buf, fp);
3252 StrNCpy(str_buf, setlocale(LC_CTYPE, NULL), MAXPGPATH);
3253 write_array_var(str_buf, fp);
3259 (errcode_for_file_access(),
3260 errmsg("could not write to file \"%s\": %m", filename)));
3268 read_backend_variables(char *filename, Port *port)
3271 char str_buf[MAXPGPATH];
3274 fp = AllocateFile(filename, PG_BINARY_R);
3277 (errcode_for_file_access(),
3278 errmsg("could not read from backend variables file \"%s\": %m",
3282 read_var(port->sock, fp);
3283 read_var(port->proto, fp);
3284 read_var(port->laddr, fp);
3285 read_var(port->raddr, fp);
3286 read_var(port->canAcceptConnections, fp);
3287 read_var(port->cryptSalt, fp);
3288 read_var(port->md5Salt, fp);
3290 read_array_var(str_buf, fp);
3291 SetDataDir(str_buf);
3293 read_array_var(ListenSocket, fp);
3295 read_var(MyCancelKey, fp);
3297 read_var(UsedShmemSegID, fp);
3298 read_var(UsedShmemSegAddr, fp);
3300 read_var(ShmemLock, fp);
3301 read_var(ShmemIndexLock, fp);
3302 read_var(ShmemVariableCache, fp);
3303 read_var(ShmemIndexAlloc, fp);
3304 read_var(ShmemBackendArray, fp);
3306 read_var(LWLockArray, fp);
3307 read_var(ProcStructLock, fp);
3308 read_var(pgStatSock, fp);
3310 read_var(debug_flag, fp);
3311 read_var(PostmasterPid, fp);
3313 read_var(PostmasterHandle, fp);
3316 read_array_var(str_buf, fp);
3317 StrNCpy(my_exec_path, str_buf, MAXPGPATH);
3319 read_array_var(ExtraOptions, fp);
3321 read_array_var(str_buf, fp);
3322 setlocale(LC_COLLATE, str_buf);
3323 read_array_var(str_buf, fp);
3324 setlocale(LC_CTYPE, str_buf);
3328 if (unlink(filename) != 0)
3330 (errcode_for_file_access(),
3331 errmsg("could not remove file \"%s\": %m", filename)));
3336 ShmemBackendArraySize(void)
3338 return (NUM_BACKENDARRAY_ELEMS * sizeof(Backend));
3342 ShmemBackendArrayAllocation(void)
3344 size_t size = ShmemBackendArraySize();
3346 ShmemBackendArray = (Backend *) ShmemAlloc(size);
3347 /* Mark all slots as empty */
3348 memset(ShmemBackendArray, 0, size);
3352 ShmemBackendArrayAdd(Backend *bn)
3356 /* Find an empty slot */
3357 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
3359 if (ShmemBackendArray[i].pid == 0)
3361 ShmemBackendArray[i] = *bn;
3367 (errmsg_internal("no free slots in shmem backend array")));
3371 ShmemBackendArrayRemove(pid_t pid)
3375 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
3377 if (ShmemBackendArray[i].pid == pid)
3379 /* Mark the slot as empty */
3380 ShmemBackendArray[i].pid = 0;
3386 (errmsg_internal("could not find backend entry with pid %d",
3390 #endif /* EXEC_BACKEND */
3396 win32_forkexec(const char *path, char *argv[])
3399 PROCESS_INFORMATION pi;
3402 char cmdLine[MAXPGPATH * 2];
3403 HANDLE childHandleCopy;
3404 HANDLE waiterThread;
3406 /* Format the cmd line */
3407 cmdLine[sizeof(cmdLine)-1] = '\0';
3408 cmdLine[sizeof(cmdLine)-2] = '\0';
3409 snprintf(cmdLine, sizeof(cmdLine)-1, "\"%s\"", path);
3411 while (argv[++i] != NULL)
3413 j = strlen(cmdLine);
3414 snprintf(cmdLine+j, sizeof(cmdLine)-1-j, " \"%s\"", argv[i]);
3416 if (cmdLine[sizeof(cmdLine)-2] != '\0')
3418 elog(LOG, "subprocess command line too long");
3422 memset(&pi, 0, sizeof(pi));
3423 memset(&si, 0, sizeof(si));
3425 if (!CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
3427 elog(LOG, "CreateProcess call failed (%d): %m", (int) GetLastError());
3431 if (!IsUnderPostmaster)
3433 /* We are the Postmaster creating a child... */
3434 win32_AddChild(pi.dwProcessId, pi.hProcess);
3437 if (DuplicateHandle(GetCurrentProcess(),
3439 GetCurrentProcess(),
3443 DUPLICATE_SAME_ACCESS) == 0)
3445 (errmsg_internal("could not duplicate child handle: %d",
3446 (int) GetLastError())));
3448 waiterThread = CreateThread(NULL, 64 * 1024, win32_sigchld_waiter,
3449 (LPVOID) childHandleCopy, 0, NULL);
3452 (errmsg_internal("could not create sigchld waiter thread: %d",
3453 (int) GetLastError())));
3454 CloseHandle(waiterThread);
3456 if (IsUnderPostmaster)
3457 CloseHandle(pi.hProcess);
3458 CloseHandle(pi.hThread);
3460 return pi.dwProcessId;
3464 * Note: The following three functions must not be interrupted (eg. by
3465 * signals). As the Postgres Win32 signalling architecture (currently)
3466 * requires polling, or APC checking functions which aren't used here, this
3469 * We keep two separate arrays, instead of a single array of pid/HANDLE
3470 * structs, to avoid having to re-create a handle array for
3471 * WaitForMultipleObjects on each call to win32_waitpid.
3475 win32_AddChild(pid_t pid, HANDLE handle)
3477 Assert(win32_childPIDArray && win32_childHNDArray);
3478 if (win32_numChildren < NUM_BACKENDARRAY_ELEMS)
3480 win32_childPIDArray[win32_numChildren] = pid;
3481 win32_childHNDArray[win32_numChildren] = handle;
3482 ++win32_numChildren;
3486 (errmsg_internal("no room for child entry with pid %lu",
3487 (unsigned long) pid)));
3491 win32_RemoveChild(pid_t pid)
3495 Assert(win32_childPIDArray && win32_childHNDArray);
3497 for (i = 0; i < win32_numChildren; i++)
3499 if (win32_childPIDArray[i] == pid)
3501 CloseHandle(win32_childHNDArray[i]);
3503 /* Swap last entry into the "removed" one */
3504 --win32_numChildren;
3505 win32_childPIDArray[i] = win32_childPIDArray[win32_numChildren];
3506 win32_childHNDArray[i] = win32_childHNDArray[win32_numChildren];
3512 (errmsg_internal("could not find child entry with pid %lu",
3513 (unsigned long) pid)));
3517 win32_waitpid(int *exitstatus)
3519 Assert(win32_childPIDArray && win32_childHNDArray);
3520 elog(DEBUG3, "waiting on %lu children", win32_numChildren);
3522 if (win32_numChildren > 0)
3525 * Note: Do NOT use WaitForMultipleObjectsEx, as we don't want to
3526 * run queued APCs here.
3532 ret = WaitForMultipleObjects(win32_numChildren, win32_childHNDArray,
3538 (errmsg_internal("failed to wait on %lu children: %d",
3539 win32_numChildren, (int) GetLastError())));
3543 /* No children have finished */
3549 * Get the exit code, and return the PID of, the
3550 * respective process
3552 index = ret - WAIT_OBJECT_0;
3553 Assert(index >= 0 && index < win32_numChildren);
3554 if (!GetExitCodeProcess(win32_childHNDArray[index], &exitCode))
3557 * If we get this far, this should never happen, but,
3558 * then again... No choice other than to assume a
3559 * catastrophic failure.
3562 (errmsg_internal("failed to get exit code for child %lu",
3563 win32_childPIDArray[index])));
3565 *exitstatus = (int) exitCode;
3566 return win32_childPIDArray[index];
3575 * Note! Code below executes on separate threads, one for
3576 * each child process created
3579 win32_sigchld_waiter(LPVOID param)
3581 HANDLE procHandle = (HANDLE) param;
3583 DWORD r = WaitForSingleObject(procHandle, INFINITE);
3585 if (r == WAIT_OBJECT_0)
3586 pg_queue_signal(SIGCHLD);
3588 fprintf(stderr, "ERROR: failed to wait on child process handle: %d\n",
3589 (int) GetLastError());
3590 CloseHandle(procHandle);