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, shutdown, and periodic checkpoints. The postmaster
11 * itself doesn't do those operations, mind you --- it just forks
12 * off a subprocess to do them at the right times. It also takes
13 * care of resetting the system 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.382 2004/05/06 19:23:25 momjian Exp $
45 * The Postmaster sets up a few shared memory data structures
46 * for the backends. It should at the very least initialize the
50 * The Postmaster shares memory with the backends but should avoid
51 * touching shared memory, so as not to become stuck if a crashing
52 * backend screws up locks or shared memory. Likewise, the Postmaster
53 * should never block on messages from frontend clients.
56 * The Postmaster cleans up after backends if they have an emergency
57 * exit and/or core dump.
59 *-------------------------------------------------------------------------
70 #include <sys/socket.h>
74 #include <sys/param.h>
75 #include <netinet/in.h>
76 #include <arpa/inet.h>
80 #ifdef HAVE_SYS_SELECT_H
81 #include <sys/select.h>
89 #include <DNSServiceDiscovery/DNSServiceDiscovery.h>
92 #include "catalog/pg_database.h"
93 #include "commands/async.h"
94 #include "lib/dllist.h"
95 #include "libpq/auth.h"
96 #include "libpq/crypt.h"
97 #include "libpq/libpq.h"
98 #include "libpq/pqcomm.h"
99 #include "libpq/pqsignal.h"
100 #include "miscadmin.h"
101 #include "nodes/nodes.h"
102 #include "storage/fd.h"
103 #include "storage/ipc.h"
104 #include "storage/pg_shmem.h"
105 #include "storage/pmsignal.h"
106 #include "storage/proc.h"
107 #include "storage/bufmgr.h"
108 #include "access/xlog.h"
109 #include "tcop/tcopprot.h"
110 #include "utils/guc.h"
111 #include "utils/memutils.h"
112 #include "utils/ps_status.h"
113 #include "bootstrap/bootstrap.h"
117 #define INVALID_SOCK (-1)
119 #ifdef HAVE_SIGPROCMASK
131 * List of active backends (or child processes anyway; we don't actually
132 * know whether a given child has become a backend or is still in the
133 * authorization phase). This is used mainly to keep track of how many
134 * children we have and send them appropriate signals when necessary.
138 pid_t pid; /* process id of backend */
139 long cancel_key; /* cancel key for cancels for this backend */
142 static Dllist *BackendList;
145 #define NUM_BACKENDARRAY_ELEMS (2*MaxBackends)
146 static Backend *ShmemBackendArray;
149 /* The socket number we are listening for connections on */
152 char *ListenAddresses;
155 * MaxBackends is the limit on the number of backends we can start.
156 * Note that a larger MaxBackends value will increase the size of the
157 * shared memory area as well as cause the postmaster to grab more
158 * kernel semaphores, even if you never actually use that many
164 * ReservedBackends is the number of backends reserved for superuser use.
165 * This number is taken out of the pool size given by MaxBackends so
166 * number of backend slots available to non-superusers is
167 * (MaxBackends - ReservedBackends). Note what this really means is
168 * "if there are <= ReservedBackends connections available, only superusers
169 * can make new connections" --- pre-existing superuser connections don't
170 * count against the limit.
172 int ReservedBackends;
175 static char *progname = NULL;
177 /* The socket(s) we're listening to. */
179 static int ListenSocket[MAXLISTEN];
181 /* Used to reduce macros tests */
183 const bool ExecBackend = true;
186 const bool ExecBackend = false;
190 * Set by the -o option
192 static char ExtraOptions[MAXPGPATH];
195 * These globals control the behavior of the postmaster in case some
196 * backend dumps core. Normally, it kills all peers of the dead backend
197 * and reinitializes shared memory. By specifying -s or -n, we can have
198 * the postmaster stop (rather than kill) peers and not reinitialize
199 * shared data structures.
201 static bool Reinit = true;
202 static int SendStop = false;
204 /* still more option variables */
205 bool EnableSSL = false;
206 bool SilentMode = false; /* silent mode (-S) */
208 int PreAuthDelay = 0;
209 int AuthenticationTimeout = 60;
210 int CheckPointTimeout = 300;
211 int CheckPointWarning = 30;
212 time_t LastSignalledCheckpoint = 0;
214 bool log_hostname; /* for ps display and logging */
215 bool Log_connections = false;
216 bool Db_user_namespace = false;
218 char *rendezvous_name;
220 /* list of library:init-function to be preloaded */
221 char *preload_libraries_string = NULL;
223 /* Startup/shutdown state */
224 static pid_t StartupPID = 0,
228 static time_t checkpointed = 0;
231 #define SmartShutdown 1
232 #define FastShutdown 2
234 static int Shutdown = NoShutdown;
236 static bool FatalError = false; /* T if recovering from backend crash */
238 bool ClientAuthInProgress = false; /* T during new-client
242 * State for assigning random salts and cancel keys.
243 * Also, the global MyCancelKey passes the cancel key assigned to a given
244 * backend from the postmaster to that backend (via fork).
247 static unsigned int random_seed = 0;
249 static int debug_flag = 0;
255 #ifdef HAVE_INT_OPTRESET
260 * postmaster.c - function prototypes
262 static void pmdaemonize(int argc, char *argv[]);
263 static Port *ConnCreate(int serverFd);
264 static void ConnFree(Port *port);
265 static void reset_shared(unsigned short port);
266 static void SIGHUP_handler(SIGNAL_ARGS);
267 static void pmdie(SIGNAL_ARGS);
268 static void reaper(SIGNAL_ARGS);
269 static void sigusr1_handler(SIGNAL_ARGS);
270 static void dummy_handler(SIGNAL_ARGS);
271 static void CleanupProc(int pid, int exitstatus);
272 static void LogChildExit(int lev, const char *procname,
273 int pid, int exitstatus);
274 static void BackendInit(Port *port);
275 static int BackendRun(Port *port);
276 static void ExitPostmaster(int status);
277 static void usage(const char *);
278 static int ServerLoop(void);
279 static int BackendStartup(Port *port);
280 static int ProcessStartupPacket(Port *port, bool SSLdone);
281 static void processCancelRequest(Port *port, void *pkt);
282 static int initMasks(fd_set *rmask);
283 static void report_fork_failure_to_client(Port *port, int errnum);
284 static enum CAC_state canAcceptConnections(void);
285 static long PostmasterRandom(void);
286 static void RandomSalt(char *cryptSalt, char *md5Salt);
287 static void SignalChildren(int signal);
288 static int CountChildren(void);
289 static bool CreateOptsFile(int argc, char *argv[]);
290 NON_EXEC_STATIC void SSDataBaseInit(int xlop);
291 static pid_t SSDataBase(int xlop);
293 postmaster_error(const char *fmt,...)
294 /* This lets gcc check the format string for consistency. */
295 __attribute__((format(printf, 1, 2)));
299 pid_t win32_forkexec(const char* path, char *argv[]);
301 static void win32_AddChild(pid_t pid, HANDLE handle);
302 static void win32_RemoveChild(pid_t pid);
303 static pid_t win32_waitpid(int *exitstatus);
304 static DWORD WINAPI win32_sigchld_waiter(LPVOID param);
306 static pid_t *win32_childPIDArray;
307 static HANDLE *win32_childHNDArray;
308 static unsigned long win32_numChildren = 0;
311 static pid_t Backend_forkexec(Port *port);
313 static unsigned long tmpBackendFileNum = 0;
314 void read_backend_variables(unsigned long id, Port *port);
315 static bool write_backend_variables(Port *port);
317 static void ShmemBackendArrayAdd(Backend *bn);
318 static void ShmemBackendArrayRemove(pid_t pid);
321 #define StartupDataBase() SSDataBase(BS_XLOG_STARTUP)
322 #define CheckPointDataBase() SSDataBase(BS_XLOG_CHECKPOINT)
323 #define StartBackgroundWriter() SSDataBase(BS_XLOG_BGWRITER)
324 #define ShutdownDataBase() SSDataBase(BS_XLOG_SHUTDOWN)
328 checkDataDir(const char *checkdir)
330 char path[MAXPGPATH];
332 struct stat stat_buf;
334 if (checkdir == NULL)
337 gettext("%s does not know where to find the database system data.\n"
338 "You must specify the directory that contains the database system\n"
339 "either by specifying the -D invocation option or by setting the\n"
340 "PGDATA environment variable.\n"),
345 if (stat(checkdir, &stat_buf) == -1)
349 (errcode_for_file_access(),
350 errmsg("data directory \"%s\" does not exist",
354 (errcode_for_file_access(),
355 errmsg("could not read permissions of directory \"%s\": %m",
360 * Check if the directory has group or world access. If so, reject.
362 * XXX temporarily suppress check when on Windows, because there may not
363 * be proper support for Unix-y file permissions. Need to think of a
364 * reasonable check to apply on Windows.
366 #if !defined(__CYGWIN__) && !defined(WIN32)
367 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
369 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
370 errmsg("data directory \"%s\" has group or world access",
372 errdetail("Permissions should be u=rwx (0700).")));
375 /* Look for PG_VERSION before looking for pg_control */
376 ValidatePgVersion(checkdir);
378 snprintf(path, sizeof(path), "%s/global/pg_control", checkdir);
380 fp = AllocateFile(path, PG_BINARY_R);
384 gettext("%s: could not find the database system\n"
385 "Expected to find it in the directory \"%s\",\n"
386 "but could not open file \"%s\": %s\n"),
387 progname, checkdir, path, strerror(errno));
394 #ifdef USE_RENDEZVOUS
396 /* reg_reply -- empty callback function for DNSServiceRegistrationCreate() */
398 reg_reply(DNSServiceRegistrationReplyErrorType errorCode, void *context)
405 PostmasterMain(int argc, char *argv[])
409 char original_extraoptions[MAXPGPATH];
410 char *potential_DataDir = NULL;
413 *original_extraoptions = '\0';
417 IsPostmasterEnvironment = true;
420 * Catch standard options before doing much else. This even works on
421 * systems without getopt_long.
425 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
430 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
432 puts("postmaster (PostgreSQL) " PG_VERSION);
438 * for security, no dir or file created can be group or other
441 umask((mode_t) 0077);
443 MyProcPid = PostmasterPid = getpid();
446 * Fire up essential subsystems: memory management
451 * By default, palloc() requests in the postmaster will be allocated
452 * in the PostmasterContext, which is space that can be recycled by
453 * backends. Allocated data that needs to be available to backends
454 * should be allocated in TopMemoryContext.
456 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
458 ALLOCSET_DEFAULT_MINSIZE,
459 ALLOCSET_DEFAULT_INITSIZE,
460 ALLOCSET_DEFAULT_MAXSIZE);
461 MemoryContextSwitchTo(PostmasterContext);
463 IgnoreSystemIndexes(false);
468 InitializeGUCOptions();
470 potential_DataDir = getenv("PGDATA"); /* default value */
474 while ((opt = getopt(argc, argv, "A:a:B:b:c:D:d:Fh:ik:lm:MN:no:p:Ss-:")) != -1)
479 #ifdef USE_ASSERT_CHECKING
480 SetConfigOption("debug_assertions", optarg, PGC_POSTMASTER, PGC_S_ARGV);
482 postmaster_error("assert checking is not compiled in");
486 /* Can no longer set authentication method. */
489 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
492 /* Can no longer set the backend executable file to use. */
495 potential_DataDir = optarg;
499 /* Turn on debugging for the postmaster. */
500 char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
502 sprintf(debugstr, "debug%s", optarg);
503 SetConfigOption("log_min_messages", debugstr,
504 PGC_POSTMASTER, PGC_S_ARGV);
506 debug_flag = atoi(optarg);
510 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
513 SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
516 SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
519 SetConfigOption("unix_socket_directory", optarg, PGC_POSTMASTER, PGC_S_ARGV);
523 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
527 /* Multiplexed backends no longer supported. */
532 * ignore this flag. This may be passed in because the
533 * program was run as 'postgres -M' instead of
538 /* The max number of backends to start. */
539 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
542 /* Don't reinit shared mem after abnormal exit */
548 * Other options to pass to the backend on the command
549 * line -- useful only for debugging.
551 strcat(ExtraOptions, " ");
552 strcat(ExtraOptions, optarg);
553 strcpy(original_extraoptions, optarg);
556 SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
561 * Start in 'S'ilent mode (disassociate from controlling
562 * tty). You may also think of this as 'S'ysV mode since
563 * it's most badly needed on SysV-derived systems like
566 SetConfigOption("silent_mode", "true", PGC_POSTMASTER, PGC_S_ARGV);
571 * In the event that some backend dumps core, send
572 * SIGSTOP, rather than SIGQUIT, to all its peers. This
573 * lets the wily post_hacker collect core dumps from
584 ParseLongOption(optarg, &name, &value);
589 (errcode(ERRCODE_SYNTAX_ERROR),
590 errmsg("--%s requires a value",
594 (errcode(ERRCODE_SYNTAX_ERROR),
595 errmsg("-c %s requires a value",
599 SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
608 gettext("Try \"%s --help\" for more information.\n"),
615 * Postmaster accepts no non-option switch arguments.
619 postmaster_error("invalid argument: \"%s\"", argv[optind]);
621 gettext("Try \"%s --help\" for more information.\n"),
627 * Now we can set the data directory, and then read postgresql.conf.
629 checkDataDir(potential_DataDir); /* issues error messages */
630 SetDataDir(potential_DataDir);
632 ProcessConfigFile(PGC_POSTMASTER);
634 write_nondefault_variables(PGC_POSTMASTER);
638 * Check for invalid combinations of GUC settings.
640 if (NBuffers < 2 * MaxBackends || NBuffers < 16)
643 * Do not accept -B so small that backends are likely to starve
644 * for lack of buffers. The specific choices here are somewhat
647 postmaster_error("the number of buffers (-B) must be at least twice the number of allowed connections (-N) and at least 16");
651 if (ReservedBackends >= MaxBackends)
653 postmaster_error("superuser_reserved_connections must be less than max_connections");
658 * Other one-time internal sanity checks can go here.
660 if (!CheckDateTokenTables())
662 postmaster_error("invalid datetoken tables, please fix");
667 * Now that we are done processing the postmaster arguments, reset
668 * getopt(3) library so that it will work correctly in subprocesses.
671 #ifdef HAVE_INT_OPTRESET
672 optreset = 1; /* some systems need this too */
675 /* For debugging: display postmaster environment */
677 extern char **environ;
681 (errmsg_internal("%s: PostmasterMain: initial environ dump:",
684 (errmsg_internal("-----------------------------------------")));
685 for (p = environ; *p; ++p)
687 (errmsg_internal("\t%s", *p)));
689 (errmsg_internal("-----------------------------------------")));
693 * On some systems our dynloader code needs the executable's pathname.
695 if (FindExec(pg_pathname, progname, "postgres") < 0)
697 (errmsg("%s: could not locate postgres executable",
701 * Initialize SSL library, if specified.
709 * process any libraries that should be preloaded and optionally
712 if (preload_libraries_string)
713 process_preload_libraries(preload_libraries_string);
716 * Fork away from controlling terminal, if -S specified.
718 * Must do this before we grab any interlock files, else the interlocks
719 * will show the wrong PID.
722 pmdaemonize(argc, argv);
725 * Create lockfile for data directory.
727 * We want to do this before we try to grab the input sockets, because
728 * the data directory interlock is more reliable than the socket-file
729 * interlock (thanks to whoever decided to put socket files in /tmp
730 * :-(). For the same reason, it's best to grab the TCP socket before
733 CreateDataDirLockFile(DataDir, true);
736 * Remove old temporary files. At this point there can be no other
737 * Postgres processes running in this directory, so this should be
743 * Establish input sockets.
745 for (i = 0; i < MAXLISTEN; i++)
746 ListenSocket[i] = -1;
754 curhost = ListenAddresses;
757 /* ignore whitespace */
758 while (isspace((unsigned char) *curhost))
760 if (*curhost == '\0')
763 while (*endptr != '\0' && !isspace((unsigned char) *endptr))
767 if (strcmp(curhost,"*") == 0)
768 status = StreamServerPort(AF_UNSPEC, NULL,
769 (unsigned short) PostPortNumber,
771 ListenSocket, MAXLISTEN);
773 status = StreamServerPort(AF_UNSPEC, curhost,
774 (unsigned short) PostPortNumber,
776 ListenSocket, MAXLISTEN);
777 if (status != STATUS_OK)
779 (errmsg("could not create listen socket for \"%s\"",
789 #ifdef USE_RENDEZVOUS
790 /* Register for Rendezvous only if we opened TCP socket(s) */
791 if (ListenSocket[0] != -1 && rendezvous_name != NULL)
793 DNSServiceRegistrationCreate(rendezvous_name,
796 htonl(PostPortNumber),
798 (DNSServiceRegistrationReply) reg_reply,
803 #ifdef HAVE_UNIX_SOCKETS
804 status = StreamServerPort(AF_UNIX, NULL,
805 (unsigned short) PostPortNumber,
807 ListenSocket, MAXLISTEN);
808 if (status != STATUS_OK)
810 (errmsg("could not create Unix-domain socket")));
814 * check that we have some socket to listen on
816 if (ListenSocket[0] == -1)
818 (errmsg("no socket created for listening")));
823 * Set up shared memory and semaphores.
825 reset_shared(PostPortNumber);
828 * Estimate number of openable files. This must happen after setting up
829 * semaphores, because on some platforms semaphores count as open files.
834 * Initialize the list of active backends.
836 BackendList = DLNewList();
840 * Initialize the child pid/HANDLE arrays
842 win32_childPIDArray = (pid_t*)malloc(NUM_BACKENDARRAY_ELEMS*sizeof(pid_t));
843 win32_childHNDArray = (HANDLE*)malloc(NUM_BACKENDARRAY_ELEMS*sizeof(HANDLE));
844 if (!win32_childPIDArray || !win32_childHNDArray)
846 (errcode(ERRCODE_OUT_OF_MEMORY),
847 errmsg("out of memory")));
851 * Record postmaster options. We delay this till now to avoid
852 * recording bogus options (eg, NBuffers too high for available
855 if (!CreateOptsFile(argc, argv))
859 * Set up signal handlers for the postmaster process.
861 * CAUTION: when changing this list, check for side-effects on the signal
862 * handling setup of child processes. See tcop/postgres.c,
863 * bootstrap/bootstrap.c, and postmaster/pgstat.c.
866 PG_SETMASK(&BlockSig);
868 pqsignal(SIGHUP, SIGHUP_handler); /* reread config file and have
869 * children do same */
870 pqsignal(SIGINT, pmdie); /* send SIGTERM and ShutdownDataBase */
871 pqsignal(SIGQUIT, pmdie); /* send SIGQUIT and die */
872 pqsignal(SIGTERM, pmdie); /* wait for children and ShutdownDataBase */
873 pqsignal(SIGALRM, SIG_IGN); /* ignored */
874 pqsignal(SIGPIPE, SIG_IGN); /* ignored */
875 pqsignal(SIGUSR1, sigusr1_handler); /* message from child process */
876 pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
877 pqsignal(SIGCHLD, reaper); /* handle child termination */
878 pqsignal(SIGTTIN, SIG_IGN); /* ignored */
879 pqsignal(SIGTTOU, SIG_IGN); /* ignored */
880 /* ignore SIGXFSZ, so that ulimit violations work like disk full */
882 pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
886 * Reset whereToSendOutput from Debug (its starting state) to None.
887 * This prevents ereport from sending log messages to stderr unless
888 * the syslog/stderr switch permits. We don't do this until the
889 * postmaster is fully launched, since startup failures may as well be
890 * reported to stderr.
892 whereToSendOutput = None;
895 * On many platforms, the first call of localtime() incurs significant
896 * overhead to load timezone info from the system configuration files.
897 * By doing it once in the postmaster, we avoid having to do it in
898 * every started child process. The savings are not huge, but they
902 time_t now = time(NULL);
904 (void) localtime(&now);
908 * Initialize and try to startup the statistics collector process
914 * Load cached files for client authentication.
922 * We're ready to rock and roll...
924 StartupPID = StartupDataBase();
926 status = ServerLoop();
929 * ServerLoop probably shouldn't ever return, but if it does, close
932 ExitPostmaster(status != STATUS_OK);
934 return 0; /* not reached */
938 pmdaemonize(int argc, char *argv[])
942 elog(FATAL,"SilentMode not supported under WIN32");
948 struct itimerval prof_itimer;
952 /* see comments in BackendRun */
953 getitimer(ITIMER_PROF, &prof_itimer);
957 if (pid == (pid_t) -1)
959 postmaster_error("could not fork background process: %s",
965 /* Parent should just exit, without doing any atexit cleanup */
970 setitimer(ITIMER_PROF, &prof_itimer, NULL);
973 MyProcPid = getpid(); /* reset MyProcPid to child */
975 /* GH: If there's no setsid(), we hopefully don't need silent mode.
976 * Until there's a better solution.
981 postmaster_error("could not dissociate from controlling TTY: %s",
986 i = open(NULL_DEV, O_RDWR | PG_BINARY);
997 * Print out help message
1000 usage(const char *progname)
1002 printf(gettext("%s is the PostgreSQL server.\n\n"), progname);
1003 printf(gettext("Usage:\n %s [OPTION]...\n\n"), progname);
1004 printf(gettext("Options:\n"));
1005 #ifdef USE_ASSERT_CHECKING
1006 printf(gettext(" -A 1|0 enable/disable run-time assert checking\n"));
1008 printf(gettext(" -B NBUFFERS number of shared buffers\n"));
1009 printf(gettext(" -c NAME=VALUE set run-time parameter\n"));
1010 printf(gettext(" -d 1-5 debugging level\n"));
1011 printf(gettext(" -D DATADIR database directory\n"));
1012 printf(gettext(" -F turn fsync off\n"));
1013 printf(gettext(" -h HOSTNAME host name or IP address to listen on\n"));
1014 printf(gettext(" -i enable TCP/IP connections\n"));
1015 printf(gettext(" -k DIRECTORY Unix-domain socket location\n"));
1017 printf(gettext(" -l enable SSL connections\n"));
1019 printf(gettext(" -N MAX-CONNECT maximum number of allowed connections\n"));
1020 printf(gettext(" -o OPTIONS pass \"OPTIONS\" to each server process\n"));
1021 printf(gettext(" -p PORT port number to listen on\n"));
1022 printf(gettext(" -S silent mode (start in background without logging output)\n"));
1023 printf(gettext(" --help show this help, then exit\n"));
1024 printf(gettext(" --version output version information, then exit\n"));
1026 printf(gettext("\nDeveloper options:\n"));
1027 printf(gettext(" -n do not reinitialize shared memory after abnormal exit\n"));
1028 printf(gettext(" -s send SIGSTOP to all backend servers if one dies\n"));
1030 printf(gettext("\nPlease read the documentation for the complete list of run-time\n"
1031 "configuration settings and how to set them on the command line or in\n"
1032 "the configuration file.\n\n"
1033 "Report bugs to <pgsql-bugs@postgresql.org>.\n"));
1046 gettimeofday(&now, &tz);
1048 nSockets = initMasks(&readmask);
1054 struct timeval timeout;
1057 * The timeout for the select() below is normally set on the basis
1058 * of the time to the next checkpoint. However, if for some
1059 * reason we don't have a next-checkpoint time, time out after 60
1060 * seconds. This keeps checkpoint scheduling from locking up when
1061 * we get new connection requests infrequently (since we are
1062 * likely to detect checkpoint completion just after enabling
1063 * signals below, after we've already made the decision about how
1064 * long to wait this time).
1066 timeout.tv_sec = 60;
1067 timeout.tv_usec = 0;
1069 if (CheckPointPID == 0 && checkpointed &&
1070 StartupPID == 0 && Shutdown == NoShutdown &&
1071 !FatalError && random_seed != 0)
1073 time_t now = time(NULL);
1075 if (CheckPointTimeout + checkpointed > now)
1078 * Not time for checkpoint yet, so set select timeout
1080 timeout.tv_sec = CheckPointTimeout + checkpointed - now;
1084 /* Time to make the checkpoint... */
1085 CheckPointPID = CheckPointDataBase();
1088 * if fork failed, schedule another try at 0.1 normal
1091 if (CheckPointPID == 0)
1093 timeout.tv_sec = CheckPointTimeout / 10;
1094 checkpointed = now + timeout.tv_sec - CheckPointTimeout;
1100 * If no background writer process is running and we should
1101 * do background writing, start one. It doesn't matter if
1102 * this fails, we'll just try again later.
1104 if (BgWriterPID == 0 && BgWriterPercent > 0 &&
1105 StartupPID == 0 && Shutdown == NoShutdown &&
1106 !FatalError && random_seed != 0)
1108 BgWriterPID = StartBackgroundWriter();
1112 * Wait for something to happen.
1114 memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
1116 PG_SETMASK(&UnBlockSig);
1118 if (select(nSockets, &rmask, NULL, NULL, &timeout) < 0)
1120 PG_SETMASK(&BlockSig);
1121 if (errno == EINTR || errno == EWOULDBLOCK)
1124 (errcode_for_socket_access(),
1125 errmsg("select() failed in postmaster: %m")));
1126 return STATUS_ERROR;
1130 * Block all signals until we wait again. (This makes it safe for
1131 * our signal handlers to do nontrivial work.)
1133 PG_SETMASK(&BlockSig);
1136 * Select a random seed at the time of first receiving a request.
1138 while (random_seed == 0)
1140 gettimeofday(&later, &tz);
1143 * We are not sure how much precision is in tv_usec, so we
1144 * swap the nibbles of 'later' and XOR them with 'now'. On the
1145 * off chance that the result is 0, we loop until it isn't.
1147 random_seed = now.tv_usec ^
1148 ((later.tv_usec << 16) |
1149 ((later.tv_usec >> 16) & 0xffff));
1153 * New connection pending on any of our sockets? If so, fork a
1154 * child process to deal with it.
1156 for (i = 0; i < MAXLISTEN; i++)
1158 if (ListenSocket[i] == -1)
1160 if (FD_ISSET(ListenSocket[i], &rmask))
1162 port = ConnCreate(ListenSocket[i]);
1165 BackendStartup(port);
1168 * We no longer need the open socket or port structure
1171 StreamClose(port->sock);
1177 /* If we have lost the stats collector, try to start a new one */
1178 if (!pgstat_is_running)
1185 * Initialise the masks for select() for the ports
1186 * we are listening on. Return the number of sockets to listen on.
1190 initMasks(fd_set *rmask)
1197 for (i = 0; i < MAXLISTEN; i++)
1199 int fd = ListenSocket[i];
1213 * Read the startup packet and do something according to it.
1215 * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
1216 * not return at all.
1218 * (Note that ereport(FATAL) stuff is sent to the client, so only use it
1219 * if that's what you want. Return STATUS_ERROR if you don't want to
1220 * send anything to the client, which would typically be appropriate
1221 * if we detect a communications failure.)
1224 ProcessStartupPacket(Port *port, bool SSLdone)
1228 ProtocolVersion proto;
1229 MemoryContext oldcontext;
1231 if (pq_getbytes((char *) &len, 4) == EOF)
1234 * EOF after SSLdone probably means the client didn't like our
1235 * response to NEGOTIATE_SSL_CODE. That's not an error condition,
1236 * so don't clutter the log with a complaint.
1240 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1241 errmsg("incomplete startup packet")));
1242 return STATUS_ERROR;
1248 if (len < (int32) sizeof(ProtocolVersion) ||
1249 len > MAX_STARTUP_PACKET_LENGTH)
1252 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1253 errmsg("invalid length of startup packet")));
1254 return STATUS_ERROR;
1258 * Allocate at least the size of an old-style startup packet, plus one
1259 * extra byte, and make sure all are zeroes. This ensures we will
1260 * have null termination of all strings, in both fixed- and
1261 * variable-length packet layouts.
1263 if (len <= (int32) sizeof(StartupPacket))
1264 buf = palloc0(sizeof(StartupPacket) + 1);
1266 buf = palloc0(len + 1);
1268 if (pq_getbytes(buf, len) == EOF)
1271 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1272 errmsg("incomplete startup packet")));
1273 return STATUS_ERROR;
1277 * The first field is either a protocol version number or a special
1280 port->proto = proto = ntohl(*((ProtocolVersion *) buf));
1282 if (proto == CANCEL_REQUEST_CODE)
1284 processCancelRequest(port, buf);
1285 return 127; /* XXX */
1288 if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
1293 /* No SSL when disabled or on Unix sockets */
1294 if (!EnableSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
1297 SSLok = 'S'; /* Support for SSL */
1299 SSLok = 'N'; /* No support for SSL */
1301 if (send(port->sock, &SSLok, 1, 0) != 1)
1304 (errcode_for_socket_access(),
1305 errmsg("failed to send SSL negotiation response: %m")));
1306 return STATUS_ERROR; /* close the connection */
1310 if (SSLok == 'S' && secure_open_server(port) == -1)
1311 return STATUS_ERROR;
1313 /* regular startup packet, cancel, etc packet should follow... */
1314 /* but not another SSL negotiation request */
1315 return ProcessStartupPacket(port, true);
1318 /* Could add additional special packet types here */
1321 * Set FrontendProtocol now so that ereport() knows what format to
1322 * send if we fail during startup.
1324 FrontendProtocol = proto;
1326 /* Check we can handle the protocol the frontend is using. */
1328 if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
1329 PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
1330 (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
1331 PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
1333 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1334 errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
1335 PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
1336 PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST),
1337 PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST),
1338 PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))));
1341 * Now fetch parameters out of startup packet and save them into the
1342 * Port structure. All data structures attached to the Port struct
1343 * must be allocated in TopMemoryContext so that they won't disappear
1344 * when we pass them to PostgresMain (see BackendRun). We need not
1345 * worry about leaking this storage on failure, since we aren't in the
1346 * postmaster process anymore.
1348 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1350 if (PG_PROTOCOL_MAJOR(proto) >= 3)
1352 int32 offset = sizeof(ProtocolVersion);
1355 * Scan packet body for name/option pairs. We can assume any
1356 * string beginning within the packet body is null-terminated,
1357 * thanks to zeroing extra byte above.
1359 port->guc_options = NIL;
1361 while (offset < len)
1363 char *nameptr = ((char *) buf) + offset;
1367 if (*nameptr == '\0')
1368 break; /* found packet terminator */
1369 valoffset = offset + strlen(nameptr) + 1;
1370 if (valoffset >= len)
1371 break; /* missing value, will complain below */
1372 valptr = ((char *) buf) + valoffset;
1374 if (strcmp(nameptr, "database") == 0)
1375 port->database_name = pstrdup(valptr);
1376 else if (strcmp(nameptr, "user") == 0)
1377 port->user_name = pstrdup(valptr);
1378 else if (strcmp(nameptr, "options") == 0)
1379 port->cmdline_options = pstrdup(valptr);
1382 /* Assume it's a generic GUC option */
1383 port->guc_options = lappend(port->guc_options,
1385 port->guc_options = lappend(port->guc_options,
1388 offset = valoffset + strlen(valptr) + 1;
1392 * If we didn't find a packet terminator exactly at the end of the
1393 * given packet length, complain.
1395 if (offset != len - 1)
1397 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1398 errmsg("invalid startup packet layout: expected terminator as last byte")));
1403 * Get the parameters from the old-style, fixed-width-fields
1404 * startup packet as C strings. The packet destination was
1405 * cleared first so a short packet has zeros silently added. We
1406 * have to be prepared to truncate the pstrdup result for oversize
1409 StartupPacket *packet = (StartupPacket *) buf;
1411 port->database_name = pstrdup(packet->database);
1412 if (strlen(port->database_name) > sizeof(packet->database))
1413 port->database_name[sizeof(packet->database)] = '\0';
1414 port->user_name = pstrdup(packet->user);
1415 if (strlen(port->user_name) > sizeof(packet->user))
1416 port->user_name[sizeof(packet->user)] = '\0';
1417 port->cmdline_options = pstrdup(packet->options);
1418 if (strlen(port->cmdline_options) > sizeof(packet->options))
1419 port->cmdline_options[sizeof(packet->options)] = '\0';
1420 port->guc_options = NIL;
1423 /* Check a user name was given. */
1424 if (port->user_name == NULL || port->user_name[0] == '\0')
1426 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1427 errmsg("no PostgreSQL user name specified in startup packet")));
1429 /* The database defaults to the user name. */
1430 if (port->database_name == NULL || port->database_name[0] == '\0')
1431 port->database_name = pstrdup(port->user_name);
1433 if (Db_user_namespace)
1436 * If user@, it is a global user, remove '@'. We only want to do
1437 * this if there is an '@' at the end and no earlier in the user
1438 * string or they may fake as a local user of another database
1439 * attaching to this database.
1441 if (strchr(port->user_name, '@') ==
1442 port->user_name + strlen(port->user_name) - 1)
1443 *strchr(port->user_name, '@') = '\0';
1446 /* Append '@' and dbname */
1449 db_user = palloc(strlen(port->user_name) +
1450 strlen(port->database_name) + 2);
1451 sprintf(db_user, "%s@%s", port->user_name, port->database_name);
1452 port->user_name = db_user;
1457 * Truncate given database and user names to length of a Postgres
1458 * name. This avoids lookup failures when overlength names are given.
1460 if (strlen(port->database_name) >= NAMEDATALEN)
1461 port->database_name[NAMEDATALEN - 1] = '\0';
1462 if (strlen(port->user_name) >= NAMEDATALEN)
1463 port->user_name[NAMEDATALEN - 1] = '\0';
1466 * Done putting stuff in TopMemoryContext.
1468 MemoryContextSwitchTo(oldcontext);
1471 * If we're going to reject the connection due to database state, say
1472 * so now instead of wasting cycles on an authentication exchange.
1473 * (This also allows a pg_ping utility to be written.)
1475 switch (port->canAcceptConnections)
1479 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1480 errmsg("the database system is starting up")));
1484 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1485 errmsg("the database system is shutting down")));
1489 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1490 errmsg("the database system is in recovery mode")));
1494 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
1495 errmsg("sorry, too many clients already")));
1507 * The client has sent a cancel request packet, not a normal
1508 * start-a-new-connection packet. Perform the necessary processing.
1509 * Nothing is sent back to the client.
1512 processCancelRequest(Port *port, void *pkt)
1514 CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
1516 long cancelAuthCode;
1518 #ifndef EXEC_BACKEND
1524 backendPID = (int) ntohl(canc->backendPID);
1525 cancelAuthCode = (long) ntohl(canc->cancelAuthCode);
1527 if (backendPID == CheckPointPID)
1530 (errmsg_internal("ignoring cancel request for checkpoint process %d",
1534 else if (backendPID == BgWriterPID)
1537 (errmsg_internal("ignoring cancel request for bgwriter process %d",
1542 /* See if we have a matching backend */
1543 #ifndef EXEC_BACKEND
1544 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
1546 bp = (Backend *) DLE_VAL(curr);
1548 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
1550 bp = (Backend*) &ShmemBackendArray[i];
1552 if (bp->pid == backendPID)
1554 if (bp->cancel_key == cancelAuthCode)
1556 /* Found a match; signal that backend to cancel current op */
1558 (errmsg_internal("processing cancel request: sending SIGINT to process %d",
1560 kill(bp->pid, SIGINT);
1563 /* Right PID, wrong key: no way, Jose */
1565 (errmsg_internal("bad key in cancel request for process %d",
1571 /* No matching backend */
1573 (errmsg_internal("bad pid in cancel request for process %d",
1578 * canAcceptConnections --- check to see if database state allows connections.
1580 static enum CAC_state
1581 canAcceptConnections(void)
1583 /* Can't start backends when in startup/shutdown/recovery state. */
1584 if (Shutdown > NoShutdown)
1585 return CAC_SHUTDOWN;
1589 return CAC_RECOVERY;
1592 * Don't start too many children.
1594 * We allow more connections than we can have backends here because some
1595 * might still be authenticating; they might fail auth, or some
1596 * existing backend might exit before the auth cycle is completed. The
1597 * exact MaxBackends limit is enforced when a new backend tries to
1598 * join the shared-inval backend array.
1600 if (CountChildren() >= 2 * MaxBackends)
1608 * ConnCreate -- create a local connection data structure
1611 ConnCreate(int serverFd)
1615 if (!(port = (Port *) calloc(1, sizeof(Port))))
1618 (errcode(ERRCODE_OUT_OF_MEMORY),
1619 errmsg("out of memory")));
1623 if (StreamConnection(serverFd, port) != STATUS_OK)
1625 StreamClose(port->sock);
1632 * Precompute password salt values to use for this connection.
1633 * It's slightly annoying to do this long in advance of knowing
1634 * whether we'll need 'em or not, but we must do the random()
1635 * calls before we fork, not after. Else the postmaster's random
1636 * sequence won't get advanced, and all backends would end up
1637 * using the same salt...
1639 RandomSalt(port->cryptSalt, port->md5Salt);
1647 * ConnFree -- free a local connection data structure
1650 ConnFree(Port *conn)
1660 * ClosePostmasterPorts -- close all the postmaster's open sockets
1662 * This is called during child process startup to release file descriptors
1663 * that are not needed by that child process. The postmaster still has
1664 * them open, of course.
1667 ClosePostmasterPorts(bool pgstat_too)
1671 /* Close the listen sockets */
1672 for (i = 0; i < MAXLISTEN; i++)
1674 if (ListenSocket[i] != -1)
1676 StreamClose(ListenSocket[i]);
1677 ListenSocket[i] = -1;
1681 /* Close pgstat control sockets, unless we're starting pgstat itself */
1683 pgstat_close_sockets();
1688 * reset_shared -- reset shared memory and semaphores
1691 reset_shared(unsigned short port)
1694 * Create or re-create shared memory and semaphores.
1696 * Note: in each "cycle of life" we will normally assign the same IPC
1697 * keys (if using SysV shmem and/or semas), since the port number is
1698 * used to determine IPC keys. This helps ensure that we will clean
1699 * up dead IPC objects if the postmaster crashes and is restarted.
1701 CreateSharedMemoryAndSemaphores(false, MaxBackends, port);
1706 * SIGHUP -- reread config files, and tell children to do same
1709 SIGHUP_handler(SIGNAL_ARGS)
1711 int save_errno = errno;
1713 PG_SETMASK(&BlockSig);
1715 if (Shutdown <= SmartShutdown)
1718 (errmsg("received SIGHUP, reloading configuration files")));
1719 ProcessConfigFile(PGC_SIGHUP);
1721 write_nondefault_variables(PGC_SIGHUP);
1723 SignalChildren(SIGHUP);
1728 * Tell the background writer to terminate so that we
1729 * will start a new one with a possibly changed config
1731 if (BgWriterPID != 0)
1732 kill(BgWriterPID, SIGTERM);
1735 PG_SETMASK(&UnBlockSig);
1743 * pmdie -- signal handler for processing various postmaster signals.
1748 int save_errno = errno;
1750 PG_SETMASK(&BlockSig);
1753 (errmsg_internal("postmaster received signal %d",
1754 postgres_signal_arg)));
1756 switch (postgres_signal_arg)
1763 * Wait for children to end their work and ShutdownDataBase.
1765 if (Shutdown >= SmartShutdown)
1767 Shutdown = SmartShutdown;
1769 (errmsg("received smart shutdown request")));
1771 /* Must tell bgwriter to quit, or it never will... */
1772 if (BgWriterPID != 0)
1773 kill(BgWriterPID, SIGTERM);
1775 if (DLGetHead(BackendList)) /* let reaper() handle this */
1779 * No children left. Shutdown data base system.
1781 if (StartupPID > 0 || FatalError) /* let reaper() handle
1784 if (ShutdownPID > 0)
1786 elog(PANIC, "shutdown process %d already running",
1791 ShutdownPID = ShutdownDataBase();
1799 * Abort all children with SIGTERM (rollback active transactions
1800 * and exit) and ShutdownDataBase when they are gone.
1802 if (Shutdown >= FastShutdown)
1804 Shutdown = FastShutdown;
1806 (errmsg("received fast shutdown request")));
1808 if (DLGetHead(BackendList))
1813 (errmsg("aborting any active transactions")));
1814 SignalChildren(SIGTERM);
1815 /* reaper() does the rest */
1821 * No children left. Shutdown data base system.
1823 * Unlike the previous case, it is not an error for the shutdown
1824 * process to be running already (we could get SIGTERM followed
1825 * shortly later by SIGINT).
1827 if (StartupPID > 0 || FatalError) /* let reaper() handle
1830 if (ShutdownPID == 0)
1831 ShutdownPID = ShutdownDataBase();
1837 * Immediate Shutdown:
1839 * abort all children with SIGQUIT and exit without attempt to
1840 * properly shutdown data base system.
1843 (errmsg("received immediate shutdown request")));
1844 if (ShutdownPID > 0)
1845 kill(ShutdownPID, SIGQUIT);
1847 kill(StartupPID, SIGQUIT);
1848 if (DLGetHead(BackendList))
1849 SignalChildren(SIGQUIT);
1854 PG_SETMASK(&UnBlockSig);
1860 * Reaper -- signal handler to cleanup after a backend (child) dies.
1865 int save_errno = errno;
1868 int status; /* backend exit status */
1871 union wait status; /* backend exit status */
1875 int pid; /* process id of dead backend */
1877 PG_SETMASK(&BlockSig);
1880 (errmsg_internal("reaping dead processes")));
1882 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1884 exitstatus = status;
1887 while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
1889 exitstatus = status.w_status;
1891 while ((pid = win32_waitpid(&exitstatus)) > 0)
1894 * We need to do this here, and not in CleanupProc, since this
1895 * is to be called on all children when we are done with them.
1896 * Could move to LogChildExit, but that seems like asking for
1899 win32_RemoveChild(pid);
1904 * Check if this child was the statistics collector. If so, try to
1905 * start a new one. (If fail, we'll try again in future cycles of
1908 if (pgstat_ispgstat(pid))
1910 LogChildExit(LOG, gettext("statistics collector process"),
1917 * Check if this child was a shutdown or startup process.
1919 if (ShutdownPID > 0 && pid == ShutdownPID)
1921 if (exitstatus != 0)
1923 LogChildExit(LOG, gettext("shutdown process"),
1927 /* Normal postmaster exit is here */
1931 if (StartupPID > 0 && pid == StartupPID)
1933 if (exitstatus != 0)
1935 LogChildExit(LOG, gettext("startup process"),
1938 (errmsg("aborting startup due to startup process failure")));
1944 * Startup succeeded - remember its ID and RedoRecPtr.
1946 * NB: this MUST happen before we fork a checkpoint or shutdown
1947 * subprocess, else they will have wrong local ThisStartUpId.
1951 FatalError = false; /* done with recovery */
1954 * Arrange for first checkpoint to occur after standard delay.
1957 checkpointed = time(NULL);
1960 * Go to shutdown mode if a shutdown request was pending.
1962 if (Shutdown > NoShutdown)
1964 if (ShutdownPID > 0)
1966 elog(PANIC, "startup process %d died while shutdown process %d already running",
1967 pid, (int) ShutdownPID);
1970 ShutdownPID = ShutdownDataBase();
1977 * Else do standard child cleanup.
1979 CleanupProc(pid, exitstatus);
1981 } /* loop over pending child-death reports */
1986 * Wait for all children exit, then reset shmem and
1989 if (DLGetHead(BackendList) || StartupPID > 0 || ShutdownPID > 0)
1992 (errmsg("all server processes terminated; reinitializing")));
1995 reset_shared(PostPortNumber);
1997 StartupPID = StartupDataBase();
2002 if (Shutdown > NoShutdown)
2004 if (DLGetHead(BackendList))
2006 if (StartupPID > 0 || ShutdownPID > 0)
2008 ShutdownPID = ShutdownDataBase();
2012 PG_SETMASK(&UnBlockSig);
2019 * CleanupProc -- cleanup after terminated backend.
2021 * Remove all local state associated with backend.
2024 CleanupProc(int pid,
2025 int exitstatus) /* child's exit status. */
2031 LogChildExit(DEBUG2, gettext("child process"), pid, exitstatus);
2034 * If a backend dies in an ugly way (i.e. exit status not 0) then we
2035 * must signal all other backends to quickdie. If exit status is zero
2036 * we assume everything is hunky dory and simply remove the backend
2037 * from the active backend list.
2039 if (exitstatus == 0)
2041 curr = DLGetHead(BackendList);
2044 bp = (Backend *) DLE_VAL(curr);
2048 ShmemBackendArrayRemove(bp->pid);
2055 curr = DLGetSucc(curr);
2058 if (pid == CheckPointPID)
2063 checkpointed = time(NULL);
2064 /* Update RedoRecPtr for future child backends */
2065 GetSavedRedoRecPtr();
2068 else if (pid == BgWriterPID)
2076 /* below here we're dealing with a non-normal exit */
2078 /* Make log entry unless we did so already */
2082 (pid == CheckPointPID) ? gettext("checkpoint process") :
2083 (pid == BgWriterPID) ? gettext("bgwriter process") :
2084 gettext("server process"),
2087 (errmsg("terminating any other active server processes")));
2090 curr = DLGetHead(BackendList);
2093 next = DLGetSucc(curr);
2094 bp = (Backend *) DLE_VAL(curr);
2098 * This backend is still alive. Unless we did so already,
2099 * tell it to commit hara-kiri.
2101 * SIGQUIT is the special signal that says exit without proc_exit
2102 * and let the user know what's going on. But if SendStop is
2103 * set (-s on command line), then we send SIGSTOP instead, so
2104 * that we can get core dumps from all backends by hand.
2109 (errmsg_internal("sending %s to process %d",
2110 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2112 kill(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
2118 * Found entry for freshly-dead backend, so remove it.
2121 ShmemBackendArrayRemove(bp->pid);
2130 if (pid == CheckPointPID)
2135 else if (pid == BgWriterPID)
2142 * Tell the collector about backend termination
2151 * Log the death of a child process.
2154 LogChildExit(int lev, const char *procname, int pid, int exitstatus)
2156 if (WIFEXITED(exitstatus))
2160 * translator: %s is a noun phrase describing a child process,
2161 * such as "server process"
2163 (errmsg("%s (PID %d) exited with exit code %d",
2164 procname, pid, WEXITSTATUS(exitstatus))));
2165 else if (WIFSIGNALED(exitstatus))
2169 * translator: %s is a noun phrase describing a child process,
2170 * such as "server process"
2172 (errmsg("%s (PID %d) was terminated by signal %d",
2173 procname, pid, WTERMSIG(exitstatus))));
2178 * translator: %s is a noun phrase describing a child process,
2179 * such as "server process"
2181 (errmsg("%s (PID %d) exited with unexpected status %d",
2182 procname, pid, exitstatus)));
2186 * Send a signal to all backend children.
2189 SignalChildren(int signal)
2195 curr = DLGetHead(BackendList);
2198 next = DLGetSucc(curr);
2199 bp = (Backend *) DLE_VAL(curr);
2201 if (bp->pid != MyProcPid)
2204 (errmsg_internal("sending signal %d to process %d",
2207 kill(bp->pid, signal);
2215 * BackendStartup -- start backend process
2217 * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
2220 BackendStartup(Port *port)
2222 Backend *bn; /* for backend cleanup */
2225 #ifdef LINUX_PROFILE
2226 struct itimerval prof_itimer;
2230 * Compute the cancel key that will be assigned to this backend. The
2231 * backend will have its own copy in the forked-off process' value of
2232 * MyCancelKey, so that it can transmit the key to the frontend.
2234 MyCancelKey = PostmasterRandom();
2237 * Make room for backend data structure. Better before the fork() so
2238 * we can handle failure cleanly.
2240 bn = (Backend *) malloc(sizeof(Backend));
2244 (errcode(ERRCODE_OUT_OF_MEMORY),
2245 errmsg("out of memory")));
2246 return STATUS_ERROR;
2250 * Flush stdio channels just before fork, to avoid double-output
2251 * problems. Ideally we'd use fflush(NULL) here, but there are still a
2252 * few non-ANSI stdio libraries out there (like SunOS 4.1.x) that
2253 * coredump if we do. Presently stdout and stderr are the only stdio
2254 * output channels used by the postmaster, so fflush'ing them should
2260 #ifdef LINUX_PROFILE
2263 * Linux's fork() resets the profiling timer in the child process. If
2264 * we want to profile child processes then we need to save and restore
2265 * the timer setting. This is a waste of time if not profiling,
2266 * however, so only do it if commanded by specific -DLINUX_PROFILE
2269 getitimer(ITIMER_PROF, &prof_itimer);
2273 /* Specific beos actions before backend startup */
2274 beos_before_backend_startup();
2277 port->canAcceptConnections = canAcceptConnections();
2279 pid = Backend_forkexec(port);
2283 if (pid == 0) /* child */
2285 #ifdef LINUX_PROFILE
2286 setitimer(ITIMER_PROF, &prof_itimer, NULL);
2290 /* Specific beos backend startup actions */
2291 beos_backend_startup();
2295 proc_exit(BackendRun(port));
2299 /* in parent, error */
2302 int save_errno = errno;
2305 /* Specific beos backend startup actions */
2306 beos_backend_startup_failed();
2311 (errmsg("could not fork new process for connection: %m")));
2312 report_fork_failure_to_client(port, save_errno);
2313 return STATUS_ERROR;
2316 /* in parent, normal */
2318 (errmsg_internal("forked new backend, pid=%d socket=%d",
2319 (int) pid, port->sock)));
2322 * Everything's been successful, it's safe to add this backend to our
2326 bn->cancel_key = MyCancelKey;
2328 ShmemBackendArrayAdd(bn);
2330 DLAddHead(BackendList, DLNewElem(bn));
2336 * Try to report backend fork() failure to client before we close the
2337 * connection. Since we do not care to risk blocking the postmaster on
2338 * this connection, we set the connection to non-blocking and try only once.
2340 * This is grungy special-purpose code; we cannot use backend libpq since
2341 * it's not up and running.
2344 report_fork_failure_to_client(Port *port, int errnum)
2348 /* Format the error message packet (always V2 protocol) */
2349 snprintf(buffer, sizeof(buffer), "E%s%s\n",
2350 gettext("could not fork new process for connection: "),
2353 /* Set port to non-blocking. Don't do send() if this fails */
2354 if (!set_noblock(port->sock))
2357 send(port->sock, buffer, strlen(buffer) + 1, 0);
2362 * split_opts -- split a string of options and append it to an argv array
2364 * NB: the string is destructively modified!
2366 * Since no current POSTGRES arguments require any quoting characters,
2367 * we can use the simple-minded tactic of assuming each set of space-
2368 * delimited characters is a separate argv element.
2370 * If you don't like that, well, we *used* to pass the whole option string
2371 * as ONE argument to execl(), which was even less intelligent...
2374 split_opts(char **argv, int *argcp, char *s)
2378 while (isspace((unsigned char) *s))
2382 argv[(*argcp)++] = s;
2383 while (*s && !isspace((unsigned char) *s))
2392 * BackendInit/Run -- perform authentication [BackendInit], and if successful,
2393 * set up the backend's argument list [BackendRun] and invoke
2397 * Shouldn't return at all.
2398 * If PostgresMain() fails, return status.
2401 BackendInit(Port *port)
2406 char remote_host[NI_MAXHOST];
2407 char remote_port[NI_MAXSERV];
2408 char remote_ps_data[NI_MAXHOST];
2410 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
2412 ClientAuthInProgress = true; /* limit visibility of log messages */
2414 /* We don't want the postmaster's proc_exit() handlers */
2418 * Signal handlers setting is moved to tcop/postgres...
2421 /* save start time for end of session reporting */
2422 gettimeofday(&(port->session_start),NULL);
2424 /* set these to empty in case they are needed before we set them up */
2425 port->remote_host = "";
2426 port->remote_port = "";
2427 port->commandTag = "";
2429 /* Save port etc. for ps status */
2432 /* Reset MyProcPid to new backend's pid */
2433 MyProcPid = getpid();
2436 * Initialize libpq and enable reporting of ereport errors to the
2437 * client. Must do this now because authentication uses libpq to send
2440 pq_init(); /* initialize libpq to talk to client */
2441 whereToSendOutput = Remote; /* now safe to ereport to client */
2444 * We arrange for a simple exit(0) if we receive SIGTERM or SIGQUIT
2445 * during any client authentication related communication. Otherwise
2446 * the postmaster cannot shutdown the database FAST or IMMED cleanly
2447 * if a buggy client blocks a backend during authentication.
2449 pqsignal(SIGTERM, authdie);
2450 pqsignal(SIGQUIT, authdie);
2451 pqsignal(SIGALRM, authdie);
2452 PG_SETMASK(&AuthBlockSig);
2455 * Get the remote host name and port for logging and status display.
2457 remote_host[0] = '\0';
2458 remote_port[0] = '\0';
2459 if (getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2460 remote_host, sizeof(remote_host),
2461 remote_port, sizeof(remote_port),
2462 (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV))
2464 getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2465 remote_host, sizeof(remote_host),
2466 remote_port, sizeof(remote_port),
2467 NI_NUMERICHOST | NI_NUMERICSERV);
2469 snprintf(remote_ps_data, sizeof(remote_ps_data),
2470 remote_port[0] == '\0' ? "%s" : "%s(%s)",
2471 remote_host, remote_port);
2473 if (Log_connections)
2475 (errmsg("connection received: host=%s port=%s",
2476 remote_host, remote_port)));
2479 * save remote_host and remote_port in port stucture
2481 port->remote_host = strdup(remote_host);
2482 port->remote_port = strdup(remote_port);
2485 * Ready to begin client interaction. We will give up and exit(0)
2486 * after a time delay, so that a broken client can't hog a connection
2487 * indefinitely. PreAuthDelay doesn't count against the time limit.
2489 if (!enable_sig_alarm(AuthenticationTimeout * 1000, false))
2490 elog(FATAL, "could not set timer for authorization timeout");
2493 * Receive the startup packet (which might turn out to be a cancel
2496 status = ProcessStartupPacket(port, false);
2498 if (status != STATUS_OK)
2502 * Now that we have the user and database name, we can set the process
2503 * title for ps. It's good to do this as early as possible in
2506 init_ps_display(port->user_name, port->database_name, remote_ps_data);
2507 set_ps_display("authentication");
2510 * Now perform authentication exchange.
2512 ClientAuthentication(port); /* might not return, if failure */
2515 * Done with authentication. Disable timeout, and prevent
2516 * SIGTERM/SIGQUIT again until backend startup is complete.
2518 if (!disable_sig_alarm(false))
2519 elog(FATAL, "could not disable timer for authorization timeout");
2520 PG_SETMASK(&BlockSig);
2522 if (Log_connections)
2524 (errmsg("connection authorized: user=%s database=%s",
2525 port->user_name, port->database_name)));
2528 * Don't want backend to be able to see the postmaster random number
2529 * generator state. We have to clobber the static random_seed *and*
2530 * start a new random sequence in the random() library function.
2533 gettimeofday(&now, &tz);
2534 srandom((unsigned int) now.tv_usec);
2539 BackendRun(Port *port)
2549 * Let's clean up ourselves as the postmaster child, and
2550 * close the postmaster's other sockets
2552 ClosePostmasterPorts(true);
2555 * PreAuthDelay is a debugging aid for investigating problems in the
2556 * authentication cycle: it can be set in postgresql.conf to allow
2557 * time to attach to the newly-forked backend with a debugger. (See
2558 * also the -W backend switch, which we allow clients to pass through
2559 * PGOPTIONS, but it is not honored until after authentication.)
2561 if (PreAuthDelay > 0)
2562 pg_usleep(PreAuthDelay*1000000L);
2564 /* Will exit on failure */
2569 * Now, build the argv vector that will be given to PostgresMain.
2571 * The layout of the command line is
2572 * postgres [secure switches] -p databasename [insecure switches]
2573 * where the switches after -p come from the client request.
2575 * The maximum possible number of commandline arguments that could come
2576 * from ExtraOptions or port->cmdline_options is (strlen + 1) / 2; see
2580 maxac = 10; /* for fixed args supplied below */
2581 maxac += (strlen(ExtraOptions) + 1) / 2;
2582 if (port->cmdline_options)
2583 maxac += (strlen(port->cmdline_options) + 1) / 2;
2585 av = (char **) MemoryContextAlloc(TopMemoryContext,
2586 maxac * sizeof(char *));
2589 av[ac++] = "postgres";
2592 * Pass the requested debugging level along to the backend.
2596 snprintf(debugbuf, sizeof(debugbuf), "-d%d", debug_flag);
2597 av[ac++] = debugbuf;
2601 * Pass any backend switches specified with -o in the postmaster's own
2602 * command line. We assume these are secure.
2604 split_opts(av, &ac, ExtraOptions);
2606 /* Tell the backend what protocol the frontend is using. */
2607 snprintf(protobuf, sizeof(protobuf), "-v%u", port->proto);
2608 av[ac++] = protobuf;
2611 /* pass data dir before end of secure switches (-p) */
2617 * Tell the backend it is being called from the postmaster, and which
2618 * database to use. -p marks the end of secure switches.
2621 av[ac++] = port->database_name;
2624 * Pass the (insecure) option switches from the connection request.
2625 * (It's OK to mangle port->cmdline_options now.)
2627 if (port->cmdline_options)
2628 split_opts(av, &ac, port->cmdline_options);
2635 * Release postmaster's working memory context so that backend can
2636 * recycle the space. Note this does not trash *MyProcPort, because
2637 * ConnCreate() allocated that space with malloc() ... else we'd need
2638 * to copy the Port data here. Also, subsidiary data such as the
2639 * username isn't lost either; see ProcessStartupPacket().
2641 MemoryContextSwitchTo(TopMemoryContext);
2642 #ifndef EXEC_BACKEND
2643 MemoryContextDelete(PostmasterContext);
2645 PostmasterContext = NULL;
2648 * Debug: print arguments being passed to backend
2651 (errmsg_internal("%s child[%d]: starting with (",
2652 progname, getpid())));
2653 for (i = 0; i < ac; ++i)
2655 (errmsg_internal("\t%s", av[i])));
2657 (errmsg_internal(")")));
2659 ClientAuthInProgress = false; /* client_min_messages is active
2662 return (PostgresMain(ac, av, port->user_name));
2670 * SubPostmasterMain -- prepare the fork/exec'd process to be in an equivalent
2671 * state (for calling BackendRun) as a forked process.
2674 * Shouldn't return at all.
2677 SubPostmasterMain(int argc, char* argv[])
2679 unsigned long backendID;
2682 memset((void*)&port, 0, sizeof(Port));
2685 /* Do this sooner rather than later... */
2686 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
2688 /* In EXEC case we will not have inherited these settings */
2689 IsPostmasterEnvironment = true;
2690 whereToSendOutput = None;
2692 /* Setup global context */
2693 MemoryContextInit();
2694 InitializeGUCOptions();
2696 /* Parse passed-in context */
2698 backendID = (unsigned long)atol(argv[argc++]);
2699 DataDir = strdup(argv[argc++]);
2701 /* Read in file-based context */
2702 read_nondefault_variables();
2703 read_backend_variables(backendID,&port);
2705 /* Remaining initialization */
2706 pgstat_init_forkexec_backend();
2708 /* FIXME: [fork/exec] Ugh */
2714 /* Attach process to shared segments */
2715 CreateSharedMemoryAndSemaphores(false, MaxBackends, 0);
2718 proc_exit(BackendRun(&port));
2723 * Backend_forkexec -- fork/exec off a backend process
2726 * the pid of the fork/exec'd process
2729 Backend_forkexec(Port *port)
2733 int ac = 0, bufc = 0, i;
2734 char buf[2][MAXPGPATH];
2736 if (!write_backend_variables(port))
2737 return -1; /* log made by write_backend_variables */
2739 av[ac++] = "postgres";
2740 av[ac++] = "-forkexec";
2742 /* Format up context to pass to exec'd process */
2743 snprintf(buf[bufc++],MAXPGPATH,"%lu",tmpBackendFileNum);
2744 snprintf(buf[bufc++],MAXPGPATH,"\"%s\"",DataDir);
2746 /* Add to the arg list */
2747 Assert(bufc <= lengthof(buf));
2748 for (i = 0; i < bufc; i++)
2751 /* FIXME: [fork/exec] ExtraOptions? */
2754 Assert(ac <= lengthof(av));
2757 pid = win32_forkexec(pg_pathname,av); /* logs on error */
2759 /* Fire off execv in child */
2760 if ((pid = fork()) == 0 && (execv(pg_pathname,av) == -1))
2762 * FIXME: [fork/exec] suggestions for what to do here?
2763 * Probably OK to issue error (unlike pgstat case)
2767 return pid; /* Parent returns pid */
2774 * ExitPostmaster -- cleanup
2776 * Do NOT call exit() directly --- always go through here!
2779 ExitPostmaster(int status)
2781 /* should cleanup shared memory and kill all backends */
2784 * Not sure of the semantics here. When the Postmaster dies, should
2785 * the backends all be killed? probably not.
2787 * MUST -- vadim 05-10-1999
2789 /* Should I use true instead? */
2790 ClosePostmasterPorts(false);
2796 * sigusr1_handler - handle signal conditions from child processes
2799 sigusr1_handler(SIGNAL_ARGS)
2801 int save_errno = errno;
2803 PG_SETMASK(&BlockSig);
2805 if (CheckPostmasterSignal(PMSIGNAL_DO_CHECKPOINT))
2807 if (CheckPointWarning != 0)
2810 * This only times checkpoints forced by running out of
2811 * segment files. Other checkpoints could reduce the
2812 * frequency of forced checkpoints.
2814 time_t now = time(NULL);
2816 if (LastSignalledCheckpoint != 0)
2818 int elapsed_secs = now - LastSignalledCheckpoint;
2820 if (elapsed_secs < CheckPointWarning)
2822 (errmsg("checkpoints are occurring too frequently (%d seconds apart)",
2824 errhint("Consider increasing the configuration parameter \"checkpoint_segments\".")));
2826 LastSignalledCheckpoint = now;
2830 * Request to schedule a checkpoint
2832 * Ignore request if checkpoint is already running or checkpointing
2833 * is currently disabled
2835 if (CheckPointPID == 0 && checkpointed &&
2836 StartupPID == 0 && Shutdown == NoShutdown &&
2837 !FatalError && random_seed != 0)
2839 CheckPointPID = CheckPointDataBase();
2840 /* note: if fork fails, CheckPointPID stays 0; nothing happens */
2844 if (CheckPostmasterSignal(PMSIGNAL_PASSWORD_CHANGE))
2847 * Password or group file has changed.
2853 if (CheckPostmasterSignal(PMSIGNAL_WAKEN_CHILDREN))
2856 * Send SIGUSR2 to all children (triggers AsyncNotifyHandler). See
2857 * storage/ipc/sinvaladt.c for the use of this.
2859 if (Shutdown == NoShutdown)
2860 SignalChildren(SIGUSR2);
2863 PG_SETMASK(&UnBlockSig);
2870 * Dummy signal handler
2872 * We use this for signals that we don't actually use in the postmaster,
2873 * but we do use in backends. If we SIG_IGN such signals in the postmaster,
2874 * then a newly started backend might drop a signal that arrives before it's
2875 * able to reconfigure its signal processing. (See notes in postgres.c.)
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.
2962 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2964 bp = (Backend *) DLE_VAL(curr);
2965 if (bp->pid != MyProcPid)
2968 /* Checkpoint and bgwriter will be in the list, discount them */
2969 if (CheckPointPID != 0)
2971 if (BgWriterPID != 0)
2977 * Fire off a subprocess for startup/shutdown/checkpoint/bgwriter.
2979 * Return value of SSDataBase is subprocess' PID, or 0 if failed to start subprocess
2980 * (0 is returned only for checkpoint/bgwriter cases).
2982 * note: in the EXEC_BACKEND case, we delay the fork until argument list has been
2985 NON_EXEC_STATIC void
2986 SSDataBaseInit(int xlop)
2988 const char *statmsg;
2990 IsUnderPostmaster = true; /* we are a postmaster subprocess
2994 /* In EXEC case we will not have inherited these settings */
2995 IsPostmasterEnvironment = true;
2996 whereToSendOutput = None;
2999 MyProcPid = getpid(); /* reset MyProcPid */
3001 /* Lose the postmaster's on-exit routines and port connections */
3005 * Identify myself via ps
3009 case BS_XLOG_STARTUP:
3010 statmsg = "startup subprocess";
3012 case BS_XLOG_CHECKPOINT:
3013 statmsg = "checkpoint subprocess";
3015 case BS_XLOG_BGWRITER:
3016 statmsg = "bgwriter subprocess";
3018 case BS_XLOG_SHUTDOWN:
3019 statmsg = "shutdown subprocess";
3022 statmsg = "??? subprocess";
3025 init_ps_display(statmsg, "", "");
3031 SSDataBase(int xlop)
3035 #ifndef EXEC_BACKEND
3036 #ifdef LINUX_PROFILE
3037 struct itimerval prof_itimer;
3041 char ddirbuf[MAXPGPATH];
3047 #ifndef EXEC_BACKEND
3048 #ifdef LINUX_PROFILE
3049 /* see comments in BackendRun */
3050 getitimer(ITIMER_PROF, &prof_itimer);
3054 /* Specific beos actions before backend startup */
3055 beos_before_backend_startup();
3058 /* Non EXEC_BACKEND case; fork here */
3059 if ((pid = fork()) == 0) /* child */
3067 #ifndef EXEC_BACKEND
3068 #ifdef LINUX_PROFILE
3069 setitimer(ITIMER_PROF, &prof_itimer, NULL);
3073 /* Specific beos actions after backend startup */
3074 beos_backend_startup();
3077 /* Close the postmaster's sockets */
3078 ClosePostmasterPorts(true);
3080 SSDataBaseInit(xlop);
3082 if (!write_backend_variables(NULL))
3083 return -1; /* log issued by write_backend_variables */
3086 /* Set up command-line arguments for subprocess */
3087 av[ac++] = "postgres";
3092 snprintf(nbbuf, sizeof(nbbuf), "-B%d", NBuffers);
3095 snprintf(xlbuf, sizeof(xlbuf), "-x%d", xlop);
3099 /* pass data dir before end of secure switches (-p) */
3100 snprintf(ddirbuf, MAXPGPATH, "\"%s\"", DataDir);
3104 /* and the backend identifier + dbname */
3105 snprintf(idbuf, sizeof(idbuf), "-p%lu,template1", tmpBackendFileNum);
3109 av[ac++] = "template1";
3114 Assert(ac < lengthof(av));
3117 /* EXEC_BACKEND case; fork/exec here */
3119 pid = win32_forkexec(pg_pathname,av); /* logs on error */
3121 if ((pid = fork()) == 0 && (execv(pg_pathname,av) == -1))
3124 elog(ERROR,"unable to execv in SSDataBase: %m");
3129 BootstrapMain(ac, av);
3137 #ifndef EXEC_BACKEND
3139 /* Specific beos actions before backend startup */
3140 beos_backend_startup_failed();
3145 case BS_XLOG_STARTUP:
3147 (errmsg("could not fork startup process: %m")));
3149 case BS_XLOG_CHECKPOINT:
3151 (errmsg("could not fork checkpoint process: %m")));
3153 case BS_XLOG_BGWRITER:
3155 (errmsg("could not fork bgwriter process: %m")));
3157 case BS_XLOG_SHUTDOWN:
3159 (errmsg("could not fork shutdown process: %m")));
3163 (errmsg("could not fork process: %m")));
3168 * fork failure is fatal during startup/shutdown, but there's no
3169 * need to choke if a routine checkpoint or starting a background
3172 if (xlop == BS_XLOG_CHECKPOINT)
3174 if (xlop == BS_XLOG_BGWRITER)
3180 * The startup and shutdown processes are not considered normal
3181 * backends, but the checkpoint and bgwriter processes are.
3182 * They must be added to the list of backends.
3184 if (xlop == BS_XLOG_CHECKPOINT || xlop == BS_XLOG_BGWRITER)
3186 if (!(bn = (Backend *) malloc(sizeof(Backend))))
3189 (errcode(ERRCODE_OUT_OF_MEMORY),
3190 errmsg("out of memory")));
3195 bn->cancel_key = PostmasterRandom();
3197 ShmemBackendArrayAdd(bn);
3199 DLAddHead(BackendList, DLNewElem(bn));
3202 * Since this code is executed periodically, it's a fine place to
3203 * do other actions that should happen every now and then on no
3204 * particular schedule. Such as...
3207 TouchSocketLockFile();
3215 * Create the opts file
3218 CreateOptsFile(int argc, char *argv[])
3220 char fullprogname[MAXPGPATH];
3221 char filename[MAXPGPATH];
3225 if (FindExec(fullprogname, argv[0], "postmaster") < 0)
3227 elog(LOG, "could not locate postmaster");
3231 snprintf(filename, sizeof(filename), "%s/postmaster.opts", DataDir);
3233 if ((fp = fopen(filename, "w")) == NULL)
3235 elog(LOG, "could not create file \"%s\": %m", filename);
3239 fprintf(fp, "%s", fullprogname);
3240 for (i = 1; i < argc; i++)
3241 fprintf(fp, " '%s'", argv[i]);
3246 elog(LOG, "could not write file \"%s\": %m", filename);
3254 * This should be used only for reporting "interactive" errors (essentially,
3255 * bogus arguments on the command line). Once the postmaster is launched,
3256 * use ereport. In particular, don't use this for anything that occurs
3257 * after pmdaemonize.
3260 postmaster_error(const char *fmt,...)
3264 fprintf(stderr, "%s: ", progname);
3266 vfprintf(stderr, gettext(fmt), ap);
3268 fprintf(stderr, "\n");
3275 * The following need to be available to the read/write_backend_variables
3278 #include "storage/spin.h"
3279 extern XLogRecPtr RedoRecPtr;
3280 extern XLogwrtResult LogwrtResult;
3281 extern slock_t *ShmemLock;
3282 extern slock_t *ShmemIndexLock;
3283 extern void *ShmemIndexAlloc;
3284 typedef struct LWLock LWLock;
3285 extern LWLock *LWLockArray;
3286 extern slock_t *ProcStructLock;
3287 extern int pgStatSock;
3289 #define write_var(var,fp) fwrite((void*)&(var),sizeof(var),1,fp)
3290 #define read_var(var,fp) fread((void*)&(var),sizeof(var),1,fp)
3291 #define get_tmp_backend_file_name(buf,id) \
3295 "%s/%s/%s.backend_var.%lu", \
3297 PG_TEMP_FILES_DIR, \
3298 PG_TEMP_FILE_PREFIX, \
3303 write_backend_variables(Port *port)
3305 char filename[MAXPGPATH];
3307 get_tmp_backend_file_name(filename,++tmpBackendFileNum);
3310 fp = AllocateFile(filename, PG_BINARY_W);
3313 /* As per OpenTemporaryFile... */
3314 char dirname[MAXPGPATH];
3315 sprintf(dirname,"%s/%s",DataDir,PG_TEMP_FILES_DIR);
3316 mkdir(dirname, S_IRWXU);
3318 fp = AllocateFile(filename, PG_BINARY_W);
3322 (errcode_for_file_access(),
3323 errmsg("could not write to file \"%s\": %m", filename)));
3331 write_var(port->sock,fp);
3332 write_var(port->proto,fp);
3333 write_var(port->laddr,fp);
3334 write_var(port->raddr,fp);
3335 write_var(port->canAcceptConnections,fp);
3336 write_var(port->cryptSalt,fp);
3337 write_var(port->md5Salt,fp);
3339 write_var(MyCancelKey,fp);
3341 write_var(RedoRecPtr,fp);
3342 write_var(LogwrtResult,fp);
3344 write_var(UsedShmemSegID,fp);
3345 write_var(UsedShmemSegAddr,fp);
3347 write_var(ShmemLock,fp);
3348 write_var(ShmemIndexLock,fp);
3349 write_var(ShmemVariableCache,fp);
3350 write_var(ShmemIndexAlloc,fp);
3351 write_var(ShmemBackendArray,fp);
3353 write_var(LWLockArray,fp);
3354 write_var(ProcStructLock,fp);
3355 write_var(pgStatSock,fp);
3357 write_var(PreAuthDelay,fp);
3358 write_var(debug_flag,fp);
3359 write_var(PostmasterPid,fp);
3365 (errcode_for_file_access(),
3366 errmsg("could not write to file \"%s\": %m", filename)));
3374 read_backend_variables(unsigned long id, Port *port)
3376 char filename[MAXPGPATH];
3378 get_tmp_backend_file_name(filename,id);
3381 fp = AllocateFile(filename, PG_BINARY_R);
3385 (errcode_for_file_access(),
3386 errmsg("could not read from backend_variables file \"%s\": %m", filename)));
3393 read_var(port->sock,fp);
3394 read_var(port->proto,fp);
3395 read_var(port->laddr,fp);
3396 read_var(port->raddr,fp);
3397 read_var(port->canAcceptConnections,fp);
3398 read_var(port->cryptSalt,fp);
3399 read_var(port->md5Salt,fp);
3401 read_var(MyCancelKey,fp);
3403 read_var(RedoRecPtr,fp);
3404 read_var(LogwrtResult,fp);
3406 read_var(UsedShmemSegID,fp);
3407 read_var(UsedShmemSegAddr,fp);
3409 read_var(ShmemLock,fp);
3410 read_var(ShmemIndexLock,fp);
3411 read_var(ShmemVariableCache,fp);
3412 read_var(ShmemIndexAlloc,fp);
3413 read_var(ShmemBackendArray,fp);
3415 read_var(LWLockArray,fp);
3416 read_var(ProcStructLock,fp);
3417 read_var(pgStatSock,fp);
3419 read_var(PreAuthDelay,fp);
3420 read_var(debug_flag,fp);
3421 read_var(PostmasterPid,fp);
3425 if (unlink(filename) != 0)
3427 (errcode_for_file_access(),
3428 errmsg("could not remove file \"%s\": %m", filename)));
3432 size_t ShmemBackendArraySize(void)
3434 return (NUM_BACKENDARRAY_ELEMS*sizeof(Backend));
3437 void ShmemBackendArrayAllocation(void)
3439 size_t size = ShmemBackendArraySize();
3440 ShmemBackendArray = (Backend*)ShmemAlloc(size);
3441 memset(ShmemBackendArray, 0, size);
3444 static void ShmemBackendArrayAdd(Backend *bn)
3447 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
3449 /* Find an empty slot */
3450 if (ShmemBackendArray[i].pid == 0)
3452 ShmemBackendArray[i] = *bn;
3458 (errmsg_internal("unable to add backend entry")));
3461 static void ShmemBackendArrayRemove(pid_t pid)
3464 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
3466 if (ShmemBackendArray[i].pid == pid)
3468 /* Mark the slot as empty */
3469 ShmemBackendArray[i].pid = 0;
3475 (errmsg_internal("unable to find backend entry with pid %d",
3483 pid_t win32_forkexec(const char* path, char *argv[])
3486 PROCESS_INFORMATION pi;
3489 char cmdLine[MAXPGPATH];
3490 HANDLE childHandleCopy;
3491 HANDLE waiterThread;
3493 /* Format the cmd line */
3494 snprintf(cmdLine,sizeof(cmdLine),"\"%s\"",path);
3496 while (argv[++i] != NULL)
3498 /* FIXME: [fork/exec] some strlen checks might be prudent here */
3499 strcat(cmdLine," ");
3500 strcat(cmdLine,argv[i]);
3504 * The following snippet can disappear when we consistently
3505 * use forward slashes.
3508 while (*(p++) != '\0')
3509 if (*p == '/') *p = '\\';
3511 memset(&pi,0,sizeof(pi));
3512 memset(&si,0,sizeof(si));
3514 if (!CreateProcess(NULL,cmdLine,NULL,NULL,TRUE,0,NULL,NULL,&si,&pi))
3516 elog(ERROR,"CreateProcess call failed (%i): %m",(int)GetLastError());
3520 if (!IsUnderPostmaster)
3521 /* We are the Postmaster creating a child... */
3522 win32_AddChild(pi.dwProcessId,pi.hProcess);
3524 if (!DuplicateHandle(GetCurrentProcess(),
3526 GetCurrentProcess(),
3530 DUPLICATE_SAME_ACCESS))
3532 (errmsg_internal("failed to duplicate child handle: %i",(int)GetLastError())));
3533 waiterThread = CreateThread(NULL, 64*1024, win32_sigchld_waiter, (LPVOID)childHandleCopy, 0, NULL);
3536 (errmsg_internal("failed to create sigchld waiter thread: %i",(int)GetLastError())));
3537 CloseHandle(waiterThread);
3539 if (IsUnderPostmaster)
3540 CloseHandle(pi.hProcess);
3541 CloseHandle(pi.hThread);
3543 return pi.dwProcessId;
3547 * Note: The following three functions must not be interrupted (eg. by signals).
3548 * As the Postgres Win32 signalling architecture (currently) requires polling,
3549 * or APC checking functions which aren't used here, this is not an issue.
3551 * We keep two separate arrays, instead of a single array of pid/HANDLE structs,
3552 * to avoid having to re-create a handle array for WaitForMultipleObjects on
3553 * each call to win32_waitpid.
3556 static void win32_AddChild(pid_t pid, HANDLE handle)
3558 Assert(win32_childPIDArray && win32_childHNDArray);
3559 if (win32_numChildren < NUM_BACKENDARRAY_ELEMS)
3561 win32_childPIDArray[win32_numChildren] = pid;
3562 win32_childHNDArray[win32_numChildren] = handle;
3563 ++win32_numChildren;
3567 (errmsg_internal("unable to add child entry with pid %lu",
3571 static void win32_RemoveChild(pid_t pid)
3574 Assert(win32_childPIDArray && win32_childHNDArray);
3576 for (i = 0; i < win32_numChildren; i++)
3578 if (win32_childPIDArray[i] == pid)
3580 CloseHandle(win32_childHNDArray[i]);
3582 /* Swap last entry into the "removed" one */
3583 --win32_numChildren;
3584 win32_childPIDArray[i] = win32_childPIDArray[win32_numChildren];
3585 win32_childHNDArray[i] = win32_childHNDArray[win32_numChildren];
3591 (errmsg_internal("unable to find child entry with pid %lu",
3595 static pid_t win32_waitpid(int *exitstatus)
3597 Assert(win32_childPIDArray && win32_childHNDArray);
3598 elog(DEBUG3,"waiting on %lu children",win32_numChildren);
3600 if (win32_numChildren > 0)
3603 * Note: Do NOT use WaitForMultipleObjectsEx, as we don't
3604 * want to run queued APCs here.
3608 DWORD ret = WaitForMultipleObjects(win32_numChildren,win32_childHNDArray,FALSE,0);
3614 (errmsg_internal("failed to wait on %lu children: %i",
3615 win32_numChildren,(int)GetLastError())));
3616 /* Fall through to WAIT_TIMEOUTs return */
3619 /* No children have finished */
3623 /* Get the exit code, and return the PID of, the respective process */
3624 index = ret-WAIT_OBJECT_0;
3625 Assert(index >= 0 && index < win32_numChildren);
3626 if (!GetExitCodeProcess(win32_childHNDArray[index],&exitCode))
3628 * If we get this far, this should never happen, but, then again...
3629 * No choice other than to assume a catastrophic failure.
3632 (errmsg_internal("failed to get exit code for child %lu",
3633 win32_childPIDArray[index])));
3634 *exitstatus = (int)exitCode;
3635 return win32_childPIDArray[index];
3643 /* Note! Code belows executes on separate threads, one for
3644 each child process created */
3645 static DWORD WINAPI win32_sigchld_waiter(LPVOID param) {
3646 HANDLE procHandle = (HANDLE)param;
3648 DWORD r = WaitForSingleObject(procHandle, INFINITE);
3649 if (r == WAIT_OBJECT_0)
3650 pg_queue_signal(SIGCHLD);
3652 fprintf(stderr,"ERROR: Failed to wait on child process handle: %i\n",(int)GetLastError());
3653 CloseHandle(procHandle);