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 * $Header: /cvsroot/pgsql/src/backend/postmaster/postmaster.c,v 1.340 2003/08/04 02:40:02 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 "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"
116 #define INVALID_SOCK (-1)
118 #ifdef HAVE_SIGPROCMASK
130 * List of active backends (or child processes anyway; we don't actually
131 * know whether a given child has become a backend or is still in the
132 * authorization phase). This is used mainly to keep track of how many
133 * children we have and send them appropriate signals when necessary.
137 pid_t pid; /* process id of backend */
138 long cancel_key; /* cancel key for cancels for this backend */
141 static Dllist *BackendList;
143 /* The socket number we are listening for connections on */
149 * MaxBackends is the limit on the number of backends we can start.
150 * Note that a larger MaxBackends value will increase the size of the
151 * shared memory area as well as cause the postmaster to grab more
152 * kernel semaphores, even if you never actually use that many
158 * ReservedBackends is the number of backends reserved for superuser use.
159 * This number is taken out of the pool size given by MaxBackends so
160 * number of backend slots available to non-superusers is
161 * (MaxBackends - ReservedBackends). Note what this really means is
162 * "if there are <= ReservedBackends connections available, only superusers
163 * can make new connections" --- pre-existing superuser connections don't
164 * count against the limit.
166 int ReservedBackends;
169 static char *progname = (char *) NULL;
171 /* The socket(s) we're listening to. */
173 static int ListenSocket[MAXLISTEN];
175 /* Used to reduce macros tests */
177 const bool ExecBackend = true;
180 const bool ExecBackend = false;
184 * Set by the -o option
186 static char ExtraOptions[MAXPGPATH];
189 * These globals control the behavior of the postmaster in case some
190 * backend dumps core. Normally, it kills all peers of the dead backend
191 * and reinitializes shared memory. By specifying -s or -n, we can have
192 * the postmaster stop (rather than kill) peers and not reinitialize
193 * shared data structures.
195 static bool Reinit = true;
196 static int SendStop = false;
198 /* still more option variables */
199 bool NetServer = false; /* listen on TCP/IP */
200 bool EnableSSL = false;
201 bool SilentMode = false; /* silent mode (-S) */
203 int PreAuthDelay = 0;
204 int AuthenticationTimeout = 60;
205 int CheckPointTimeout = 300;
206 int CheckPointWarning = 30;
207 time_t LastSignalledCheckpoint = 0;
209 bool log_hostname; /* for ps display */
211 bool Log_connections = false;
212 bool Db_user_namespace = false;
214 char *rendezvous_name;
216 /* For FNCTL_NONBLOCK */
217 #if defined(WIN32) || defined(__BEOS__)
218 long ioctlsocket_ret;
221 /* list of library:init-function to be preloaded */
222 char *preload_libraries_string = NULL;
224 /* Startup/shutdown state */
225 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 int BackendFork(Port *port);
275 static void ExitPostmaster(int status);
276 static void usage(const char *);
277 static int ServerLoop(void);
278 static int BackendStartup(Port *port);
279 static int ProcessStartupPacket(Port *port, bool SSLdone);
280 static void processCancelRequest(Port *port, void *pkt);
281 static int initMasks(fd_set *rmask);
282 static void report_fork_failure_to_client(Port *port, int errnum);
285 CAC_OK, CAC_STARTUP, CAC_SHUTDOWN, CAC_RECOVERY, CAC_TOOMANY
287 static enum CAC_state canAcceptConnections(void);
288 static long PostmasterRandom(void);
289 static void RandomSalt(char *cryptSalt, char *md5Salt);
290 static void SignalChildren(int signal);
291 static int CountChildren(void);
292 static bool CreateOptsFile(int argc, char *argv[]);
293 static pid_t SSDataBase(int xlop);
295 postmaster_error(const char *fmt,...)
296 /* This lets gcc check the format string for consistency. */
297 __attribute__((format(printf, 1, 2)));
299 #define StartupDataBase() SSDataBase(BS_XLOG_STARTUP)
300 #define CheckPointDataBase() SSDataBase(BS_XLOG_CHECKPOINT)
301 #define ShutdownDataBase() SSDataBase(BS_XLOG_SHUTDOWN)
305 checkDataDir(const char *checkdir)
307 char path[MAXPGPATH];
309 struct stat stat_buf;
311 if (checkdir == NULL)
314 gettext("%s does not know where to find the database system data.\n"
315 "You must specify the directory that contains the database system\n"
316 "either by specifying the -D invocation option or by setting the\n"
317 "PGDATA environment variable.\n"),
322 if (stat(checkdir, &stat_buf) == -1)
326 (errcode_for_file_access(),
327 errmsg("data directory \"%s\" does not exist",
331 (errcode_for_file_access(),
332 errmsg("could not read permissions of directory \"%s\": %m",
337 * Check if the directory has group or world access. If so, reject.
339 * XXX temporarily suppress check when on Windows, because there may not
340 * be proper support for Unix-y file permissions. Need to think of a
341 * reasonable check to apply on Windows.
343 #if !defined(__CYGWIN__) && !defined(WIN32)
344 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
346 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
347 errmsg("data directory \"%s\" has group or world access",
349 errdetail("Permissions should be u=rwx (0700).")));
352 /* Look for PG_VERSION before looking for pg_control */
353 ValidatePgVersion(checkdir);
355 snprintf(path, sizeof(path), "%s/global/pg_control", checkdir);
357 fp = AllocateFile(path, PG_BINARY_R);
361 gettext("%s could not find the database system.\n"
362 "Expected to find it in the PGDATA directory \"%s\",\n"
363 "but failed to open file \"%s\": %s\n"),
364 progname, checkdir, path, strerror(errno));
371 #ifdef USE_RENDEZVOUS
373 /* reg_reply -- empty callback function for DNSServiceRegistrationCreate() */
375 reg_reply(DNSServiceRegistrationReplyErrorType errorCode, void *context)
382 PostmasterMain(int argc, char *argv[])
386 char original_extraoptions[MAXPGPATH];
387 char *potential_DataDir = NULL;
390 *original_extraoptions = '\0';
394 IsPostmasterEnvironment = true;
397 * Catch standard options before doing much else. This even works on
398 * systems without getopt_long.
402 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
407 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
409 puts("postmaster (PostgreSQL) " PG_VERSION);
415 * for security, no dir or file created can be group or other
418 umask((mode_t) 0077);
420 MyProcPid = getpid();
423 * Fire up essential subsystems: memory management
428 * By default, palloc() requests in the postmaster will be allocated
429 * in the PostmasterContext, which is space that can be recycled by
430 * backends. Allocated data that needs to be available to backends
431 * should be allocated in TopMemoryContext.
433 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
435 ALLOCSET_DEFAULT_MINSIZE,
436 ALLOCSET_DEFAULT_INITSIZE,
437 ALLOCSET_DEFAULT_MAXSIZE);
438 MemoryContextSwitchTo(PostmasterContext);
440 IgnoreSystemIndexes(false);
445 InitializeGUCOptions();
447 potential_DataDir = getenv("PGDATA"); /* default value */
451 while ((opt = getopt(argc, argv, "A:a:B:b:c:D:d:Fh:ik:lm:MN:no:p:Ss-:")) != -1)
456 #ifdef USE_ASSERT_CHECKING
457 SetConfigOption("debug_assertions", optarg, PGC_POSTMASTER, PGC_S_ARGV);
459 postmaster_error("assert checking is not compiled in");
463 /* Can no longer set authentication method. */
466 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
469 /* Can no longer set the backend executable file to use. */
472 potential_DataDir = optarg;
476 /* Turn on debugging for the postmaster. */
477 char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
479 sprintf(debugstr, "debug%s", optarg);
480 SetConfigOption("log_min_messages", debugstr,
481 PGC_POSTMASTER, PGC_S_ARGV);
483 debug_flag = atoi(optarg);
487 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
490 SetConfigOption("virtual_host", optarg, PGC_POSTMASTER, PGC_S_ARGV);
493 SetConfigOption("tcpip_socket", "true", PGC_POSTMASTER, PGC_S_ARGV);
496 SetConfigOption("unix_socket_directory", optarg, PGC_POSTMASTER, PGC_S_ARGV);
500 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
504 /* Multiplexed backends no longer supported. */
509 * ignore this flag. This may be passed in because the
510 * program was run as 'postgres -M' instead of
515 /* The max number of backends to start. */
516 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
519 /* Don't reinit shared mem after abnormal exit */
525 * Other options to pass to the backend on the command
526 * line -- useful only for debugging.
528 strcat(ExtraOptions, " ");
529 strcat(ExtraOptions, optarg);
530 strcpy(original_extraoptions, optarg);
533 SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
538 * Start in 'S'ilent mode (disassociate from controlling
539 * tty). You may also think of this as 'S'ysV mode since
540 * it's most badly needed on SysV-derived systems like
543 SetConfigOption("silent_mode", "true", PGC_POSTMASTER, PGC_S_ARGV);
548 * In the event that some backend dumps core, send
549 * SIGSTOP, rather than SIGQUIT, to all its peers. This
550 * lets the wily post_hacker collect core dumps from
561 ParseLongOption(optarg, &name, &value);
566 (errcode(ERRCODE_SYNTAX_ERROR),
567 errmsg("--%s requires a value",
571 (errcode(ERRCODE_SYNTAX_ERROR),
572 errmsg("-c %s requires a value",
576 SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
585 gettext("Try '%s --help' for more information.\n"),
592 * Postmaster accepts no non-option switch arguments.
596 postmaster_error("invalid argument: \"%s\"", argv[optind]);
598 gettext("Try '%s --help' for more information.\n"),
604 * Now we can set the data directory, and then read postgresql.conf.
606 checkDataDir(potential_DataDir); /* issues error messages */
607 SetDataDir(potential_DataDir);
609 ProcessConfigFile(PGC_POSTMASTER);
611 write_nondefault_variables(PGC_POSTMASTER);
615 * Check for invalid combinations of GUC settings.
617 if (NBuffers < 2 * MaxBackends || NBuffers < 16)
620 * Do not accept -B so small that backends are likely to starve
621 * for lack of buffers. The specific choices here are somewhat
624 postmaster_error("the number of buffers (-B) must be at least twice the number of allowed connections (-N) and at least 16");
628 if (ReservedBackends >= MaxBackends)
630 postmaster_error("superuser_reserved_connections must be less than max_connections");
635 * Other one-time internal sanity checks can go here.
637 if (!CheckDateTokenTables())
639 postmaster_error("invalid datetoken tables, please fix");
644 * Now that we are done processing the postmaster arguments, reset
645 * getopt(3) library so that it will work correctly in subprocesses.
648 #ifdef HAVE_INT_OPTRESET
649 optreset = 1; /* some systems need this too */
652 /* For debugging: display postmaster environment */
654 extern char **environ;
657 elog(DEBUG3, "%s: PostmasterMain: initial environ dump:", progname);
658 elog(DEBUG3, "-----------------------------------------");
659 for (p = environ; *p; ++p)
660 elog(DEBUG3, "\t%s", *p);
661 elog(DEBUG3, "-----------------------------------------");
665 * On some systems our dynloader code needs the executable's pathname.
667 if (FindExec(pg_pathname, progname, "postgres") < 0)
669 (errmsg("%s: could not locate postgres executable",
673 * Initialize SSL library, if specified.
676 if (EnableSSL && !NetServer)
678 postmaster_error("for SSL, TCP/IP connections must be enabled");
686 * process any libraries that should be preloaded and optionally
689 if (preload_libraries_string)
690 process_preload_libraries(preload_libraries_string);
693 * Fork away from controlling terminal, if -S specified.
695 * Must do this before we grab any interlock files, else the interlocks
696 * will show the wrong PID.
699 pmdaemonize(argc, argv);
702 * Create lockfile for data directory.
704 * We want to do this before we try to grab the input sockets, because
705 * the data directory interlock is more reliable than the socket-file
706 * interlock (thanks to whoever decided to put socket files in /tmp
707 * :-(). For the same reason, it's best to grab the TCP socket before
710 CreateDataDirLockFile(DataDir, true);
713 * Remove old temporary files. At this point there can be no other
714 * Postgres processes running in this directory, so this should be
720 * Establish input sockets.
722 for (i = 0; i < MAXLISTEN; i++)
723 ListenSocket[i] = -1;
727 if (VirtualHost && VirtualHost[0])
733 curhost = VirtualHost;
736 while (*curhost == ' ') /* skip any extra spaces */
738 if (*curhost == '\0')
740 endptr = strchr(curhost, ' ');
746 status = StreamServerPort(AF_UNSPEC, curhost,
747 (unsigned short) PostPortNumber,
749 ListenSocket, MAXLISTEN);
750 if (status != STATUS_OK)
752 (errmsg("could not create listen socket for \"%s\"",
757 curhost = endptr + 1;
765 status = StreamServerPort(AF_UNSPEC, NULL,
766 (unsigned short) PostPortNumber,
768 ListenSocket, MAXLISTEN);
769 if (status != STATUS_OK)
771 (errmsg("could not create TCP/IP listen socket")));
774 #ifdef USE_RENDEZVOUS
775 if (rendezvous_name != NULL)
777 DNSServiceRegistrationCreate(rendezvous_name,
780 htonl(PostPortNumber),
782 (DNSServiceRegistrationReply) reg_reply,
788 #ifdef HAVE_UNIX_SOCKETS
789 status = StreamServerPort(AF_UNIX, NULL,
790 (unsigned short) PostPortNumber,
792 ListenSocket, MAXLISTEN);
793 if (status != STATUS_OK)
795 (errmsg("could not create UNIX stream port")));
801 * Set up shared memory and semaphores.
803 reset_shared(PostPortNumber);
806 * Initialize the list of active backends.
808 BackendList = DLNewList();
811 * Record postmaster options. We delay this till now to avoid
812 * recording bogus options (eg, NBuffers too high for available
815 if (!CreateOptsFile(argc, argv))
819 * Set up signal handlers for the postmaster process.
821 * CAUTION: when changing this list, check for side-effects on the signal
822 * handling setup of child processes. See tcop/postgres.c,
823 * bootstrap/bootstrap.c, and postmaster/pgstat.c.
826 PG_SETMASK(&BlockSig);
828 pqsignal(SIGHUP, SIGHUP_handler); /* reread config file and have
829 * children do same */
830 pqsignal(SIGINT, pmdie); /* send SIGTERM and ShutdownDataBase */
831 pqsignal(SIGQUIT, pmdie); /* send SIGQUIT and die */
832 pqsignal(SIGTERM, pmdie); /* wait for children and ShutdownDataBase */
833 pqsignal(SIGALRM, SIG_IGN); /* ignored */
834 pqsignal(SIGPIPE, SIG_IGN); /* ignored */
835 pqsignal(SIGUSR1, sigusr1_handler); /* message from child process */
836 pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
837 pqsignal(SIGCHLD, reaper); /* handle child termination */
838 pqsignal(SIGTTIN, SIG_IGN); /* ignored */
839 pqsignal(SIGTTOU, SIG_IGN); /* ignored */
840 /* ignore SIGXFSZ, so that ulimit violations work like disk full */
842 pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
846 * Reset whereToSendOutput from Debug (its starting state) to None.
847 * This prevents ereport from sending log messages to stderr unless
848 * the syslog/stderr switch permits. We don't do this until the
849 * postmaster is fully launched, since startup failures may as well be
850 * reported to stderr.
852 whereToSendOutput = None;
855 * On many platforms, the first call of localtime() incurs significant
856 * overhead to load timezone info from the system configuration files.
857 * By doing it once in the postmaster, we avoid having to do it in
858 * every started child process. The savings are not huge, but they
862 time_t now = time(NULL);
864 (void) localtime(&now);
868 * Initialize and try to startup the statistics collector process
874 * Load cached files for client authentication.
882 * We're ready to rock and roll...
884 StartupPID = StartupDataBase();
886 status = ServerLoop();
889 * ServerLoop probably shouldn't ever return, but if it does, close
892 ExitPostmaster(status != STATUS_OK);
894 return 0; /* not reached */
898 pmdaemonize(int argc, char *argv[])
904 struct itimerval prof_itimer;
908 /* see comments in BackendStartup */
909 getitimer(ITIMER_PROF, &prof_itimer);
913 if (pid == (pid_t) -1)
915 postmaster_error("could not fork background process: %s",
921 /* Parent should just exit, without doing any atexit cleanup */
926 setitimer(ITIMER_PROF, &prof_itimer, NULL);
929 MyProcPid = getpid(); /* reset MyProcPid to child */
931 /* GH: If there's no setsid(), we hopefully don't need silent mode.
932 * Until there's a better solution.
937 postmaster_error("could not disassociate from controlling TTY: %s",
942 i = open(NULL_DEV, O_RDWR | PG_BINARY);
952 * Print out help message
955 usage(const char *progname)
957 printf(gettext("%s is the PostgreSQL server.\n\n"), progname);
958 printf(gettext("Usage:\n %s [OPTION]...\n\n"), progname);
959 printf(gettext("Options:\n"));
960 #ifdef USE_ASSERT_CHECKING
961 printf(gettext(" -A 1|0 enable/disable run-time assert checking\n"));
963 printf(gettext(" -B NBUFFERS number of shared buffers\n"));
964 printf(gettext(" -c NAME=VALUE set run-time parameter\n"));
965 printf(gettext(" -d 1-5 debugging level\n"));
966 printf(gettext(" -D DATADIR database directory\n"));
967 printf(gettext(" -F turn fsync off\n"));
968 printf(gettext(" -h HOSTNAME host name or IP address to listen on\n"));
969 printf(gettext(" -i enable TCP/IP connections\n"));
970 printf(gettext(" -k DIRECTORY Unix-domain socket location\n"));
972 printf(gettext(" -l enable SSL connections\n"));
974 printf(gettext(" -N MAX-CONNECT maximum number of allowed connections\n"));
975 printf(gettext(" -o OPTIONS pass 'OPTIONS' to each backend server\n"));
976 printf(gettext(" -p PORT port number to listen on\n"));
977 printf(gettext(" -S silent mode (start in background without logging output)\n"));
978 printf(gettext(" --help show this help, then exit\n"));
979 printf(gettext(" --version output version information, then exit\n"));
981 printf(gettext("\nDeveloper options:\n"));
982 printf(gettext(" -n do not reinitialize shared memory after abnormal exit\n"));
983 printf(gettext(" -s send SIGSTOP to all backend servers if one dies\n"));
985 printf(gettext("\nPlease read the documentation for the complete list of run-time\n"
986 "configuration settings and how to set them on the command line or in\n"
987 "the configuration file.\n\n"
988 "Report bugs to <pgsql-bugs@postgresql.org>.\n"));
1001 gettimeofday(&now, &tz);
1003 nSockets = initMasks(&readmask);
1009 struct timeval timeout;
1012 * The timeout for the select() below is normally set on the basis
1013 * of the time to the next checkpoint. However, if for some
1014 * reason we don't have a next-checkpoint time, time out after 60
1015 * seconds. This keeps checkpoint scheduling from locking up when
1016 * we get new connection requests infrequently (since we are
1017 * likely to detect checkpoint completion just after enabling
1018 * signals below, after we've already made the decision about how
1019 * long to wait this time).
1021 timeout.tv_sec = 60;
1022 timeout.tv_usec = 0;
1024 if (CheckPointPID == 0 && checkpointed &&
1025 Shutdown == NoShutdown && !FatalError && random_seed != 0)
1027 time_t now = time(NULL);
1029 if (CheckPointTimeout + checkpointed > now)
1032 * Not time for checkpoint yet, so set select timeout
1034 timeout.tv_sec = CheckPointTimeout + checkpointed - now;
1038 /* Time to make the checkpoint... */
1039 CheckPointPID = CheckPointDataBase();
1042 * if fork failed, schedule another try at 0.1 normal
1045 if (CheckPointPID == 0)
1047 timeout.tv_sec = CheckPointTimeout / 10;
1048 checkpointed = now + timeout.tv_sec - CheckPointTimeout;
1054 * Wait for something to happen.
1056 memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
1058 PG_SETMASK(&UnBlockSig);
1060 if (select(nSockets, &rmask, (fd_set *) NULL,
1061 (fd_set *) NULL, &timeout) < 0)
1063 PG_SETMASK(&BlockSig);
1064 if (errno == EINTR || errno == EWOULDBLOCK)
1067 (errcode_for_socket_access(),
1068 errmsg("select failed in postmaster: %m")));
1069 return STATUS_ERROR;
1073 * Block all signals until we wait again. (This makes it safe for
1074 * our signal handlers to do nontrivial work.)
1076 PG_SETMASK(&BlockSig);
1079 * Select a random seed at the time of first receiving a request.
1081 while (random_seed == 0)
1083 gettimeofday(&later, &tz);
1086 * We are not sure how much precision is in tv_usec, so we
1087 * swap the nibbles of 'later' and XOR them with 'now'. On the
1088 * off chance that the result is 0, we loop until it isn't.
1090 random_seed = now.tv_usec ^
1091 ((later.tv_usec << 16) |
1092 ((later.tv_usec >> 16) & 0xffff));
1096 * New connection pending on any of our sockets? If so, fork a
1097 * child process to deal with it.
1099 for (i = 0; i < MAXLISTEN; i++)
1101 if (ListenSocket[i] == -1)
1103 if (FD_ISSET(ListenSocket[i], &rmask))
1105 port = ConnCreate(ListenSocket[i]);
1108 BackendStartup(port);
1111 * We no longer need the open socket or port structure
1114 StreamClose(port->sock);
1120 /* If we have lost the stats collector, try to start a new one */
1121 if (!pgstat_is_running)
1128 * Initialise the masks for select() for the ports
1129 * we are listening on. Return the number of sockets to listen on.
1133 initMasks(fd_set *rmask)
1140 for (i = 0; i < MAXLISTEN; i++)
1142 int fd = ListenSocket[i];
1156 * Read the startup packet and do something according to it.
1158 * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
1159 * not return at all.
1161 * (Note that ereport(FATAL) stuff is sent to the client, so only use it
1162 * if that's what you want. Return STATUS_ERROR if you don't want to
1163 * send anything to the client, which would typically be appropriate
1164 * if we detect a communications failure.)
1167 ProcessStartupPacket(Port *port, bool SSLdone)
1172 ProtocolVersion proto;
1173 MemoryContext oldcontext;
1175 if (pq_getbytes((char *) &len, 4) == EOF)
1178 * EOF after SSLdone probably means the client didn't like our
1179 * response to NEGOTIATE_SSL_CODE. That's not an error condition,
1180 * so don't clutter the log with a complaint.
1184 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1185 errmsg("incomplete startup packet")));
1186 return STATUS_ERROR;
1192 if (len < (int32) sizeof(ProtocolVersion) ||
1193 len > MAX_STARTUP_PACKET_LENGTH)
1196 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1197 errmsg("invalid length of startup packet")));
1198 return STATUS_ERROR;
1202 * Allocate at least the size of an old-style startup packet, plus one
1203 * extra byte, and make sure all are zeroes. This ensures we will
1204 * have null termination of all strings, in both fixed- and
1205 * variable-length packet layouts.
1207 if (len <= (int32) sizeof(StartupPacket))
1208 buf = palloc0(sizeof(StartupPacket) + 1);
1210 buf = palloc0(len + 1);
1212 if (pq_getbytes(buf, len) == EOF)
1215 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1216 errmsg("incomplete startup packet")));
1217 return STATUS_ERROR;
1221 * The first field is either a protocol version number or a special
1224 port->proto = proto = ntohl(*((ProtocolVersion *) buf));
1226 if (proto == CANCEL_REQUEST_CODE)
1228 processCancelRequest(port, buf);
1229 return 127; /* XXX */
1232 if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
1237 /* No SSL when disabled or on Unix sockets */
1238 if (!EnableSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
1241 SSLok = 'S'; /* Support for SSL */
1243 SSLok = 'N'; /* No support for SSL */
1245 if (send(port->sock, &SSLok, 1, 0) != 1)
1248 (errcode_for_socket_access(),
1249 errmsg("failed to send SSL negotiation response: %m")));
1250 return STATUS_ERROR; /* close the connection */
1254 if (SSLok == 'S' && secure_open_server(port) == -1)
1255 return STATUS_ERROR;
1257 /* regular startup packet, cancel, etc packet should follow... */
1258 /* but not another SSL negotiation request */
1259 return ProcessStartupPacket(port, true);
1262 /* Could add additional special packet types here */
1265 * Set FrontendProtocol now so that ereport() knows what format to
1266 * send if we fail during startup.
1268 FrontendProtocol = proto;
1270 /* Check we can handle the protocol the frontend is using. */
1272 if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
1273 PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
1274 (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
1275 PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
1277 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1278 errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
1279 PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
1280 PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST),
1281 PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST),
1282 PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))));
1285 * Now fetch parameters out of startup packet and save them into the
1286 * Port structure. All data structures attached to the Port struct
1287 * must be allocated in TopMemoryContext so that they won't disappear
1288 * when we pass them to PostgresMain (see BackendFork). We need not
1289 * worry about leaking this storage on failure, since we aren't in the
1290 * postmaster process anymore.
1292 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1294 if (PG_PROTOCOL_MAJOR(proto) >= 3)
1296 int32 offset = sizeof(ProtocolVersion);
1299 * Scan packet body for name/option pairs. We can assume any
1300 * string beginning within the packet body is null-terminated,
1301 * thanks to zeroing extra byte above.
1303 port->guc_options = NIL;
1305 while (offset < len)
1307 char *nameptr = ((char *) buf) + offset;
1311 if (*nameptr == '\0')
1312 break; /* found packet terminator */
1313 valoffset = offset + strlen(nameptr) + 1;
1314 if (valoffset >= len)
1315 break; /* missing value, will complain below */
1316 valptr = ((char *) buf) + valoffset;
1318 if (strcmp(nameptr, "database") == 0)
1319 port->database_name = pstrdup(valptr);
1320 else if (strcmp(nameptr, "user") == 0)
1321 port->user_name = pstrdup(valptr);
1322 else if (strcmp(nameptr, "options") == 0)
1323 port->cmdline_options = pstrdup(valptr);
1326 /* Assume it's a generic GUC option */
1327 port->guc_options = lappend(port->guc_options,
1329 port->guc_options = lappend(port->guc_options,
1332 offset = valoffset + strlen(valptr) + 1;
1336 * If we didn't find a packet terminator exactly at the end of the
1337 * given packet length, complain.
1339 if (offset != len - 1)
1341 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1342 errmsg("invalid startup packet layout: expected terminator as last byte")));
1347 * Get the parameters from the old-style, fixed-width-fields
1348 * startup packet as C strings. The packet destination was
1349 * cleared first so a short packet has zeros silently added. We
1350 * have to be prepared to truncate the pstrdup result for oversize
1353 StartupPacket *packet = (StartupPacket *) buf;
1355 port->database_name = pstrdup(packet->database);
1356 if (strlen(port->database_name) > sizeof(packet->database))
1357 port->database_name[sizeof(packet->database)] = '\0';
1358 port->user_name = pstrdup(packet->user);
1359 if (strlen(port->user_name) > sizeof(packet->user))
1360 port->user_name[sizeof(packet->user)] = '\0';
1361 port->cmdline_options = pstrdup(packet->options);
1362 if (strlen(port->cmdline_options) > sizeof(packet->options))
1363 port->cmdline_options[sizeof(packet->options)] = '\0';
1364 port->guc_options = NIL;
1367 /* Check a user name was given. */
1368 if (port->user_name == NULL || port->user_name[0] == '\0')
1370 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1371 errmsg("no PostgreSQL user name specified in startup packet")));
1373 /* The database defaults to the user name. */
1374 if (port->database_name == NULL || port->database_name[0] == '\0')
1375 port->database_name = pstrdup(port->user_name);
1377 if (Db_user_namespace)
1380 * If user@, it is a global user, remove '@'. We only want to do
1381 * this if there is an '@' at the end and no earlier in the user
1382 * string or they may fake as a local user of another database
1383 * attaching to this database.
1385 if (strchr(port->user_name, '@') ==
1386 port->user_name + strlen(port->user_name) - 1)
1387 *strchr(port->user_name, '@') = '\0';
1390 /* Append '@' and dbname */
1393 db_user = palloc(strlen(port->user_name) +
1394 strlen(port->database_name) + 2);
1395 sprintf(db_user, "%s@%s", port->user_name, port->database_name);
1396 port->user_name = db_user;
1401 * Truncate given database and user names to length of a Postgres
1402 * name. This avoids lookup failures when overlength names are given.
1404 if (strlen(port->database_name) >= NAMEDATALEN)
1405 port->database_name[NAMEDATALEN - 1] = '\0';
1406 if (strlen(port->user_name) >= NAMEDATALEN)
1407 port->user_name[NAMEDATALEN - 1] = '\0';
1410 * Done putting stuff in TopMemoryContext.
1412 MemoryContextSwitchTo(oldcontext);
1415 * If we're going to reject the connection due to database state, say
1416 * so now instead of wasting cycles on an authentication exchange.
1417 * (This also allows a pg_ping utility to be written.)
1419 cac = canAcceptConnections();
1425 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1426 errmsg("the database system is starting up")));
1430 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1431 errmsg("the database system is shutting down")));
1435 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1436 errmsg("the database system is in recovery mode")));
1440 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
1441 errmsg("sorry, too many clients already")));
1453 * The client has sent a cancel request packet, not a normal
1454 * start-a-new-connection packet. Perform the necessary processing.
1455 * Nothing is sent back to the client.
1458 processCancelRequest(Port *port, void *pkt)
1460 CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
1462 long cancelAuthCode;
1466 backendPID = (int) ntohl(canc->backendPID);
1467 cancelAuthCode = (long) ntohl(canc->cancelAuthCode);
1469 if (backendPID == CheckPointPID)
1471 elog(DEBUG2, "ignoring cancel request for checkpoint process %d",
1475 else if (ExecBackend)
1476 AttachSharedMemoryAndSemaphores();
1478 /* See if we have a matching backend */
1480 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
1482 bp = (Backend *) DLE_VAL(curr);
1483 if (bp->pid == backendPID)
1485 if (bp->cancel_key == cancelAuthCode)
1487 /* Found a match; signal that backend to cancel current op */
1488 elog(DEBUG2, "processing cancel request: sending SIGINT to process %d",
1490 kill(bp->pid, SIGINT);
1493 /* Right PID, wrong key: no way, Jose */
1494 elog(DEBUG2, "bad key in cancel request for process %d",
1500 /* No matching backend */
1501 elog(DEBUG2, "bad pid in cancel request for process %d", backendPID);
1505 * canAcceptConnections --- check to see if database state allows connections.
1507 static enum CAC_state
1508 canAcceptConnections(void)
1510 /* Can't start backends when in startup/shutdown/recovery state. */
1511 if (Shutdown > NoShutdown)
1512 return CAC_SHUTDOWN;
1516 return CAC_RECOVERY;
1519 * Don't start too many children.
1521 * We allow more connections than we can have backends here because some
1522 * might still be authenticating; they might fail auth, or some
1523 * existing backend might exit before the auth cycle is completed. The
1524 * exact MaxBackends limit is enforced when a new backend tries to
1525 * join the shared-inval backend array.
1527 if (CountChildren() >= 2 * MaxBackends)
1535 * ConnCreate -- create a local connection data structure
1538 ConnCreate(int serverFd)
1542 if (!(port = (Port *) calloc(1, sizeof(Port))))
1545 (errcode(ERRCODE_OUT_OF_MEMORY),
1546 errmsg("out of memory")));
1550 if (StreamConnection(serverFd, port) != STATUS_OK)
1552 StreamClose(port->sock);
1559 * Precompute password salt values to use for this connection.
1560 * It's slightly annoying to do this long in advance of knowing
1561 * whether we'll need 'em or not, but we must do the random()
1562 * calls before we fork, not after. Else the postmaster's random
1563 * sequence won't get advanced, and all backends would end up
1564 * using the same salt...
1566 RandomSalt(port->cryptSalt, port->md5Salt);
1574 * ConnFree -- free a local connection data structure
1577 ConnFree(Port *conn)
1587 * ClosePostmasterPorts -- close all the postmaster's open sockets
1589 * This is called during child process startup to release file descriptors
1590 * that are not needed by that child process. The postmaster still has
1591 * them open, of course.
1594 ClosePostmasterPorts(bool pgstat_too)
1598 /* Close the listen sockets */
1599 for (i = 0; i < MAXLISTEN; i++)
1601 if (ListenSocket[i] != -1)
1603 StreamClose(ListenSocket[i]);
1604 ListenSocket[i] = -1;
1608 /* Close pgstat control sockets, unless we're starting pgstat itself */
1610 pgstat_close_sockets();
1615 * reset_shared -- reset shared memory and semaphores
1618 reset_shared(unsigned short port)
1621 * Create or re-create shared memory and semaphores.
1623 * Note: in each "cycle of life" we will normally assign the same IPC
1624 * keys (if using SysV shmem and/or semas), since the port number is
1625 * used to determine IPC keys. This helps ensure that we will clean
1626 * up dead IPC objects if the postmaster crashes and is restarted.
1628 CreateSharedMemoryAndSemaphores(false, MaxBackends, port);
1633 * SIGHUP -- reread config files, and tell children to do same
1636 SIGHUP_handler(SIGNAL_ARGS)
1638 int save_errno = errno;
1640 PG_SETMASK(&BlockSig);
1642 if (Shutdown <= SmartShutdown)
1645 (errmsg("received SIGHUP, reloading configuration files")));
1646 ProcessConfigFile(PGC_SIGHUP);
1648 write_nondefault_variables(PGC_SIGHUP);
1650 SignalChildren(SIGHUP);
1655 PG_SETMASK(&UnBlockSig);
1663 * pmdie -- signal handler for processing various postmaster signals.
1668 int save_errno = errno;
1670 PG_SETMASK(&BlockSig);
1672 elog(DEBUG2, "postmaster received signal %d", postgres_signal_arg);
1674 switch (postgres_signal_arg)
1681 * Wait for children to end their work and ShutdownDataBase.
1683 if (Shutdown >= SmartShutdown)
1685 Shutdown = SmartShutdown;
1687 (errmsg("received smart shutdown request")));
1688 if (DLGetHead(BackendList)) /* let reaper() handle this */
1692 * No children left. Shutdown data base system.
1694 if (StartupPID > 0 || FatalError) /* let reaper() handle
1697 if (ShutdownPID > 0)
1699 elog(PANIC, "shutdown process %d already running",
1704 ShutdownPID = ShutdownDataBase();
1712 * abort all children with SIGTERM (rollback active transactions
1713 * and exit) and ShutdownDataBase when they are gone.
1715 if (Shutdown >= FastShutdown)
1718 (errmsg("received fast shutdown request")));
1719 if (DLGetHead(BackendList)) /* let reaper() handle this */
1721 Shutdown = FastShutdown;
1725 (errmsg("aborting any active transactions")));
1726 SignalChildren(SIGTERM);
1730 if (Shutdown > NoShutdown)
1732 Shutdown = FastShutdown;
1735 Shutdown = FastShutdown;
1738 * No children left. Shutdown data base system.
1740 if (StartupPID > 0 || FatalError) /* let reaper() handle
1743 if (ShutdownPID > 0)
1745 elog(PANIC, "shutdown process %d already running",
1750 ShutdownPID = ShutdownDataBase();
1756 * Immediate Shutdown:
1758 * abort all children with SIGQUIT and exit without attempt to
1759 * properly shutdown data base system.
1762 (errmsg("received immediate shutdown request")));
1763 if (ShutdownPID > 0)
1764 kill(ShutdownPID, SIGQUIT);
1766 kill(StartupPID, SIGQUIT);
1767 if (DLGetHead(BackendList))
1768 SignalChildren(SIGQUIT);
1773 PG_SETMASK(&UnBlockSig);
1779 * Reaper -- signal handler to cleanup after a backend (child) dies.
1784 int save_errno = errno;
1787 #warning fix waidpid for Win32
1790 int status; /* backend exit status */
1793 union wait status; /* backend exit status */
1796 int pid; /* process id of dead backend */
1798 PG_SETMASK(&BlockSig);
1800 elog(DEBUG4, "reaping dead processes");
1802 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1804 exitstatus = status;
1806 while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
1808 exitstatus = status.w_status;
1812 * Check if this child was the statistics collector. If so, try to
1813 * start a new one. (If fail, we'll try again in future cycles of
1816 if (pgstat_ispgstat(pid))
1818 LogChildExit(LOG, gettext("statistics collector process"),
1825 * Check if this child was a shutdown or startup process.
1827 if (ShutdownPID > 0 && pid == ShutdownPID)
1829 if (exitstatus != 0)
1831 LogChildExit(LOG, gettext("shutdown process"),
1835 /* Normal postmaster exit is here */
1839 if (StartupPID > 0 && pid == StartupPID)
1841 if (exitstatus != 0)
1843 LogChildExit(LOG, gettext("startup process"),
1846 (errmsg("aborting startup due to startup process failure")));
1852 * Startup succeeded - remember its ID and RedoRecPtr.
1854 * NB: this MUST happen before we fork a checkpoint or shutdown
1855 * subprocess, else they will have wrong local ThisStartUpId.
1859 FatalError = false; /* done with recovery */
1862 * Arrange for first checkpoint to occur after standard delay.
1865 checkpointed = time(NULL);
1868 * Go to shutdown mode if a shutdown request was pending.
1870 if (Shutdown > NoShutdown)
1872 if (ShutdownPID > 0)
1874 elog(PANIC, "startup process %d died while shutdown process %d already running",
1875 pid, (int) ShutdownPID);
1878 ShutdownPID = ShutdownDataBase();
1885 * Else do standard child cleanup.
1887 CleanupProc(pid, exitstatus);
1889 } /* loop over pending child-death reports */
1895 * Wait for all children exit, then reset shmem and
1898 if (DLGetHead(BackendList) || StartupPID > 0 || ShutdownPID > 0)
1901 (errmsg("all server processes terminated; reinitializing")));
1904 reset_shared(PostPortNumber);
1906 StartupPID = StartupDataBase();
1911 if (Shutdown > NoShutdown)
1913 if (DLGetHead(BackendList))
1915 if (StartupPID > 0 || ShutdownPID > 0)
1917 ShutdownPID = ShutdownDataBase();
1921 PG_SETMASK(&UnBlockSig);
1927 * CleanupProc -- cleanup after terminated backend.
1929 * Remove all local state associated with backend.
1932 CleanupProc(int pid,
1933 int exitstatus) /* child's exit status. */
1939 LogChildExit(DEBUG2, gettext("child process"), pid, exitstatus);
1942 * If a backend dies in an ugly way (i.e. exit status not 0) then we
1943 * must signal all other backends to quickdie. If exit status is zero
1944 * we assume everything is hunky dory and simply remove the backend
1945 * from the active backend list.
1947 if (exitstatus == 0)
1949 curr = DLGetHead(BackendList);
1952 bp = (Backend *) DLE_VAL(curr);
1960 curr = DLGetSucc(curr);
1963 if (pid == CheckPointPID)
1968 checkpointed = time(NULL);
1969 /* Update RedoRecPtr for future child backends */
1970 GetSavedRedoRecPtr();
1979 /* below here we're dealing with a non-normal exit */
1981 /* Make log entry unless we did so already */
1985 (pid == CheckPointPID) ? gettext("checkpoint process") :
1986 gettext("server process"),
1989 (errmsg("terminating any other active server processes")));
1992 curr = DLGetHead(BackendList);
1995 next = DLGetSucc(curr);
1996 bp = (Backend *) DLE_VAL(curr);
2000 * This backend is still alive. Unless we did so already,
2001 * tell it to commit hara-kiri.
2003 * SIGQUIT is the special signal that says exit without proc_exit
2004 * and let the user know what's going on. But if SendStop is
2005 * set (-s on command line), then we send SIGSTOP instead, so
2006 * that we can get core dumps from all backends by hand.
2010 elog(DEBUG2, "sending %s to process %d",
2011 (SendStop ? "SIGSTOP" : "SIGQUIT"), (int) bp->pid);
2012 kill(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
2018 * Found entry for freshly-dead backend, so remove it.
2027 if (pid == CheckPointPID)
2035 * Tell the collector about backend termination
2044 * Log the death of a child process.
2047 LogChildExit(int lev, const char *procname, int pid, int exitstatus)
2049 if (WIFEXITED(exitstatus))
2053 * translator: %s is a noun phrase describing a child process,
2054 * such as "server process"
2056 (errmsg("%s (pid %d) exited with exit code %d",
2057 procname, pid, WEXITSTATUS(exitstatus))));
2058 else if (WIFSIGNALED(exitstatus))
2062 * translator: %s is a noun phrase describing a child process,
2063 * such as "server process"
2065 (errmsg("%s (pid %d) was terminated by signal %d",
2066 procname, pid, WTERMSIG(exitstatus))));
2071 * translator: %s is a noun phrase describing a child process,
2072 * such as "server process"
2074 (errmsg("%s (pid %d) exited with unexpected status %d",
2075 procname, pid, exitstatus)));
2079 * Send a signal to all backend children.
2082 SignalChildren(int signal)
2088 curr = DLGetHead(BackendList);
2091 next = DLGetSucc(curr);
2092 bp = (Backend *) DLE_VAL(curr);
2094 if (bp->pid != MyProcPid)
2096 elog(DEBUG2, "sending signal %d to process %d",
2097 signal, (int) bp->pid);
2098 kill(bp->pid, signal);
2106 * BackendStartup -- start backend process
2108 * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
2111 BackendStartup(Port *port)
2113 Backend *bn; /* for backend cleanup */
2116 #ifdef LINUX_PROFILE
2117 struct itimerval prof_itimer;
2121 * Compute the cancel key that will be assigned to this backend. The
2122 * backend will have its own copy in the forked-off process' value of
2123 * MyCancelKey, so that it can transmit the key to the frontend.
2125 MyCancelKey = PostmasterRandom();
2128 * Make room for backend data structure. Better before the fork() so
2129 * we can handle failure cleanly.
2131 bn = (Backend *) malloc(sizeof(Backend));
2135 (errcode(ERRCODE_OUT_OF_MEMORY),
2136 errmsg("out of memory")));
2137 return STATUS_ERROR;
2141 * Flush stdio channels just before fork, to avoid double-output
2142 * problems. Ideally we'd use fflush(NULL) here, but there are still a
2143 * few non-ANSI stdio libraries out there (like SunOS 4.1.x) that
2144 * coredump if we do. Presently stdout and stderr are the only stdio
2145 * output channels used by the postmaster, so fflush'ing them should
2151 #ifdef LINUX_PROFILE
2154 * Linux's fork() resets the profiling timer in the child process. If
2155 * we want to profile child processes then we need to save and restore
2156 * the timer setting. This is a waste of time if not profiling,
2157 * however, so only do it if commanded by specific -DLINUX_PROFILE
2160 getitimer(ITIMER_PROF, &prof_itimer);
2164 /* Specific beos actions before backend startup */
2165 beos_before_backend_startup();
2170 if (pid == 0) /* child */
2174 #ifdef LINUX_PROFILE
2175 setitimer(ITIMER_PROF, &prof_itimer, NULL);
2179 /* Specific beos backend startup actions */
2180 beos_backend_startup();
2184 status = BackendFork(port);
2188 (errmsg("connection startup failed")));
2192 /* in parent, error */
2195 int save_errno = errno;
2198 /* Specific beos backend startup actions */
2199 beos_backend_startup_failed();
2204 (errmsg("could not fork new process for connection: %m")));
2205 report_fork_failure_to_client(port, save_errno);
2206 return STATUS_ERROR;
2209 /* in parent, normal */
2210 elog(DEBUG2, "forked new backend, pid=%d socket=%d",
2211 (int) pid, port->sock);
2214 * Everything's been successful, it's safe to add this backend to our
2218 bn->cancel_key = MyCancelKey;
2219 DLAddHead(BackendList, DLNewElem(bn));
2225 * Try to report backend fork() failure to client before we close the
2226 * connection. Since we do not care to risk blocking the postmaster on
2227 * this connection, we set the connection to non-blocking and try only once.
2229 * This is grungy special-purpose code; we cannot use backend libpq since
2230 * it's not up and running.
2233 report_fork_failure_to_client(Port *port, int errnum)
2237 /* Format the error message packet (always V2 protocol) */
2238 snprintf(buffer, sizeof(buffer), "E%s%s\n",
2239 gettext("could not fork new process for connection: "),
2242 /* Set port to non-blocking. Don't do send() if this fails */
2243 if (FCNTL_NONBLOCK(port->sock) < 0)
2246 send(port->sock, buffer, strlen(buffer) + 1, 0);
2251 * split_opts -- split a string of options and append it to an argv array
2253 * NB: the string is destructively modified!
2255 * Since no current POSTGRES arguments require any quoting characters,
2256 * we can use the simple-minded tactic of assuming each set of space-
2257 * delimited characters is a separate argv element.
2259 * If you don't like that, well, we *used* to pass the whole option string
2260 * as ONE argument to execl(), which was even less intelligent...
2263 split_opts(char **argv, int *argcp, char *s)
2267 while (isspace((unsigned char) *s))
2271 argv[(*argcp)++] = s;
2272 while (*s && !isspace((unsigned char) *s))
2280 * BackendFork -- perform authentication, and if successful, set up the
2281 * backend's argument list and invoke backend main().
2283 * This used to perform an execv() but we no longer exec the backend;
2284 * it's the same executable as the postmaster.
2287 * Shouldn't return at all.
2288 * If PostgresMain() fails, return status.
2291 BackendFork(Port *port)
2300 char pbuf[NAMEDATALEN + 256];
2306 char remote_host[NI_MAXHOST];
2307 char remote_port[NI_MAXSERV];
2310 * Let's clean up ourselves as the postmaster child
2313 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
2315 ClientAuthInProgress = true; /* limit visibility of log messages */
2317 /* We don't want the postmaster's proc_exit() handlers */
2321 * Signal handlers setting is moved to tcop/postgres...
2324 /* Close the postmaster's other sockets */
2325 ClosePostmasterPorts(true);
2327 /* Save port etc. for ps status */
2330 /* Reset MyProcPid to new backend's pid */
2331 MyProcPid = getpid();
2334 * Initialize libpq and enable reporting of ereport errors to the
2335 * client. Must do this now because authentication uses libpq to send
2338 pq_init(); /* initialize libpq to talk to client */
2339 whereToSendOutput = Remote; /* now safe to ereport to client */
2342 * We arrange for a simple exit(0) if we receive SIGTERM or SIGQUIT
2343 * during any client authentication related communication. Otherwise
2344 * the postmaster cannot shutdown the database FAST or IMMED cleanly
2345 * if a buggy client blocks a backend during authentication.
2347 pqsignal(SIGTERM, authdie);
2348 pqsignal(SIGQUIT, authdie);
2349 pqsignal(SIGALRM, authdie);
2350 PG_SETMASK(&AuthBlockSig);
2353 * Get the remote host name and port for logging and status display.
2355 remote_host[0] = '\0';
2356 remote_port[0] = '\0';
2357 if (getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2358 remote_host, sizeof(remote_host),
2359 remote_port, sizeof(remote_port),
2360 (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV))
2362 getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2363 remote_host, sizeof(remote_host),
2364 remote_port, sizeof(remote_port),
2365 NI_NUMERICHOST | NI_NUMERICSERV);
2368 if (Log_connections)
2370 (errmsg("connection received: host=%s port=%s",
2371 remote_host, remote_port)));
2375 /* modify remote_host for use in ps status */
2376 char tmphost[NI_MAXHOST];
2378 snprintf(tmphost, sizeof(tmphost), "%s:%s", remote_host, remote_port);
2379 StrNCpy(remote_host, tmphost, sizeof(remote_host));
2383 * PreAuthDelay is a debugging aid for investigating problems in the
2384 * authentication cycle: it can be set in postgresql.conf to allow
2385 * time to attach to the newly-forked backend with a debugger. (See
2386 * also the -W backend switch, which we allow clients to pass through
2387 * PGOPTIONS, but it is not honored until after authentication.)
2389 if (PreAuthDelay > 0)
2390 sleep(PreAuthDelay);
2393 * Ready to begin client interaction. We will give up and exit(0)
2394 * after a time delay, so that a broken client can't hog a connection
2395 * indefinitely. PreAuthDelay doesn't count against the time limit.
2397 if (!enable_sig_alarm(AuthenticationTimeout * 1000, false))
2398 elog(FATAL, "could not set timer for authorization timeout");
2401 * Receive the startup packet (which might turn out to be a cancel
2404 status = ProcessStartupPacket(port, false);
2406 if (status != STATUS_OK)
2407 return 0; /* cancel request processed, or error */
2410 * Now that we have the user and database name, we can set the process
2411 * title for ps. It's good to do this as early as possible in
2414 init_ps_display(port->user_name, port->database_name, remote_host);
2415 set_ps_display("authentication");
2418 * Now perform authentication exchange.
2420 ClientAuthentication(port); /* might not return, if failure */
2423 * Done with authentication. Disable timeout, and prevent
2424 * SIGTERM/SIGQUIT again until backend startup is complete.
2426 if (!disable_sig_alarm(false))
2427 elog(FATAL, "could not disable timer for authorization timeout");
2428 PG_SETMASK(&BlockSig);
2430 if (Log_connections)
2432 (errmsg("connection authorized: user=%s database=%s",
2433 port->user_name, port->database_name)));
2436 * Don't want backend to be able to see the postmaster random number
2437 * generator state. We have to clobber the static random_seed *and*
2438 * start a new random sequence in the random() library function.
2441 gettimeofday(&now, &tz);
2442 srandom((unsigned int) now.tv_usec);
2445 * Now, build the argv vector that will be given to PostgresMain.
2447 * The layout of the command line is
2448 * postgres [secure switches] -p databasename [insecure switches]
2449 * where the switches after -p come from the client request.
2451 * The maximum possible number of commandline arguments that could come
2452 * from ExtraOptions or port->cmdline_options is (strlen + 1) / 2; see
2456 maxac = 10; /* for fixed args supplied below */
2457 maxac += (strlen(ExtraOptions) + 1) / 2;
2458 if (port->cmdline_options)
2459 maxac += (strlen(port->cmdline_options) + 1) / 2;
2461 av = (char **) MemoryContextAlloc(TopMemoryContext,
2462 maxac * sizeof(char *));
2465 av[ac++] = "postgres";
2468 * Pass the requested debugging level along to the backend.
2472 snprintf(debugbuf, sizeof(debugbuf), "-d%d", debug_flag);
2473 av[ac++] = debugbuf;
2477 * Pass any backend switches specified with -o in the postmaster's own
2478 * command line. We assume these are secure. (It's OK to mangle
2479 * ExtraOptions since we are now in the child process; this won't
2480 * change the postmaster's copy.)
2482 split_opts(av, &ac, ExtraOptions);
2484 /* Tell the backend what protocol the frontend is using. */
2485 snprintf(protobuf, sizeof(protobuf), "-v%u", port->proto);
2486 av[ac++] = protobuf;
2489 * Tell the backend it is being called from the postmaster, and which
2490 * database to use. -p marks the end of secure switches.
2494 Assert(UsedShmemSegID != 0 && UsedShmemSegAddr != NULL);
2495 /* database name at the end because it might contain commas */
2496 snprintf(pbuf, NAMEDATALEN + 256, "%d,%d,%d,%p,%s", port->sock, canAcceptConnections(),
2497 UsedShmemSegID, UsedShmemSegAddr, port->database_name);
2500 av[ac++] = port->database_name;
2504 * Pass the (insecure) option switches from the connection request.
2505 * (It's OK to mangle port->cmdline_options now.)
2507 if (port->cmdline_options)
2508 split_opts(av, &ac, port->cmdline_options);
2510 av[ac] = (char *) NULL;
2515 * Release postmaster's working memory context so that backend can
2516 * recycle the space. Note this does not trash *MyProcPort, because
2517 * ConnCreate() allocated that space with malloc() ... else we'd need
2518 * to copy the Port data here. Also, subsidiary data such as the
2519 * username isn't lost either; see ProcessStartupPacket().
2521 MemoryContextSwitchTo(TopMemoryContext);
2522 MemoryContextDelete(PostmasterContext);
2523 PostmasterContext = NULL;
2526 * Debug: print arguments being passed to backend
2528 elog(DEBUG3, "%s child[%d]: starting with (", progname, MyProcPid);
2529 for (i = 0; i < ac; ++i)
2530 elog(DEBUG3, "\t%s", av[i]);
2533 ClientAuthInProgress = false; /* client_min_messages is active
2536 return (PostgresMain(ac, av, port->user_name));
2540 * ExitPostmaster -- cleanup
2542 * Do NOT call exit() directly --- always go through here!
2545 ExitPostmaster(int status)
2547 /* should cleanup shared memory and kill all backends */
2550 * Not sure of the semantics here. When the Postmaster dies, should
2551 * the backends all be killed? probably not.
2553 * MUST -- vadim 05-10-1999
2555 /* Should I use true instead? */
2556 ClosePostmasterPorts(false);
2562 * sigusr1_handler - handle signal conditions from child processes
2565 sigusr1_handler(SIGNAL_ARGS)
2567 int save_errno = errno;
2569 PG_SETMASK(&BlockSig);
2571 if (CheckPostmasterSignal(PMSIGNAL_DO_CHECKPOINT))
2573 if (CheckPointWarning != 0)
2576 * This only times checkpoints forced by running out of
2577 * segment files. Other checkpoints could reduce the
2578 * frequency of forced checkpoints.
2580 time_t now = time(NULL);
2582 if (LastSignalledCheckpoint != 0)
2584 int elapsed_secs = now - LastSignalledCheckpoint;
2586 if (elapsed_secs < CheckPointWarning)
2588 (errmsg("checkpoints are occurring too frequently (%d seconds apart)",
2590 errhint("Consider increasing CHECKPOINT_SEGMENTS.")));
2592 LastSignalledCheckpoint = now;
2596 * Request to schedule a checkpoint
2598 * Ignore request if checkpoint is already running or checkpointing
2599 * is currently disabled
2601 if (CheckPointPID == 0 && checkpointed &&
2602 Shutdown == NoShutdown && !FatalError && random_seed != 0)
2604 CheckPointPID = CheckPointDataBase();
2605 /* note: if fork fails, CheckPointPID stays 0; nothing happens */
2609 if (CheckPostmasterSignal(PMSIGNAL_PASSWORD_CHANGE))
2612 * Password or group file has changed.
2618 if (CheckPostmasterSignal(PMSIGNAL_WAKEN_CHILDREN))
2621 * Send SIGUSR2 to all children (triggers AsyncNotifyHandler). See
2622 * storage/ipc/sinvaladt.c for the use of this.
2624 if (Shutdown == NoShutdown)
2625 SignalChildren(SIGUSR2);
2628 PG_SETMASK(&UnBlockSig);
2635 * Dummy signal handler
2637 * We use this for signals that we don't actually use in the postmaster,
2638 * but we do use in backends. If we SIG_IGN such signals in the postmaster,
2639 * then a newly started backend might drop a signal that arrives before it's
2640 * able to reconfigure its signal processing. (See notes in postgres.c.)
2643 dummy_handler(SIGNAL_ARGS)
2649 * CharRemap: given an int in range 0..61, produce textual encoding of it
2650 * per crypt(3) conventions.
2674 RandomSalt(char *cryptSalt, char *md5Salt)
2676 long rand = PostmasterRandom();
2678 cryptSalt[0] = CharRemap(rand % 62);
2679 cryptSalt[1] = CharRemap(rand / 62);
2682 * It's okay to reuse the first random value for one of the MD5 salt
2683 * bytes, since only one of the two salts will be sent to the client.
2684 * After that we need to compute more random bits.
2686 * We use % 255, sacrificing one possible byte value, so as to ensure
2687 * that all bits of the random() value participate in the result.
2688 * While at it, add one to avoid generating any null bytes.
2690 md5Salt[0] = (rand % 255) + 1;
2691 rand = PostmasterRandom();
2692 md5Salt[1] = (rand % 255) + 1;
2693 rand = PostmasterRandom();
2694 md5Salt[2] = (rand % 255) + 1;
2695 rand = PostmasterRandom();
2696 md5Salt[3] = (rand % 255) + 1;
2703 PostmasterRandom(void)
2705 static bool initialized = false;
2709 Assert(random_seed != 0);
2710 srandom(random_seed);
2718 * Count up number of child processes.
2727 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2729 bp = (Backend *) DLE_VAL(curr);
2730 if (bp->pid != MyProcPid)
2733 if (CheckPointPID != 0)
2739 * Fire off a subprocess for startup/shutdown/checkpoint.
2741 * Return value is subprocess' PID, or 0 if failed to start subprocess
2742 * (0 is returned only for checkpoint case).
2745 SSDataBase(int xlop)
2750 #ifdef LINUX_PROFILE
2751 struct itimerval prof_itimer;
2757 #ifdef LINUX_PROFILE
2758 /* see comments in BackendStartup */
2759 getitimer(ITIMER_PROF, &prof_itimer);
2763 /* Specific beos actions before backend startup */
2764 beos_before_backend_startup();
2767 if ((pid = fork()) == 0) /* child */
2769 const char *statmsg;
2776 char pbuf[NAMEDATALEN + 256];
2779 #ifdef LINUX_PROFILE
2780 setitimer(ITIMER_PROF, &prof_itimer, NULL);
2784 /* Specific beos actions after backend startup */
2785 beos_backend_startup();
2788 IsUnderPostmaster = true; /* we are a postmaster subprocess
2791 /* Lose the postmaster's on-exit routines and port connections */
2794 /* Close the postmaster's sockets */
2795 ClosePostmasterPorts(true);
2798 * Identify myself via ps
2802 case BS_XLOG_STARTUP:
2803 statmsg = "startup subprocess";
2805 case BS_XLOG_CHECKPOINT:
2806 statmsg = "checkpoint subprocess";
2808 case BS_XLOG_SHUTDOWN:
2809 statmsg = "shutdown subprocess";
2812 statmsg = "??? subprocess";
2815 init_ps_display(statmsg, "", "");
2818 /* Set up command-line arguments for subprocess */
2819 av[ac++] = "postgres";
2821 snprintf(nbbuf, sizeof(nbbuf), "-B%d", NBuffers);
2824 snprintf(xlbuf, sizeof(xlbuf), "-x%d", xlop);
2829 Assert(UsedShmemSegID != 0 && UsedShmemSegAddr != NULL);
2830 /* database name at the end because it might contain commas */
2831 snprintf(pbuf, NAMEDATALEN + 256, "%d,%p,%s", UsedShmemSegID,
2832 UsedShmemSegAddr, "template1");
2835 av[ac++] = "template1";
2838 av[ac] = (char *) NULL;
2840 Assert(ac < lengthof(av));
2842 BootstrapMain(ac, av);
2850 /* Specific beos actions before backend startup */
2851 beos_backend_startup_failed();
2856 case BS_XLOG_STARTUP:
2858 (errmsg("could not fork startup process: %m")));
2860 case BS_XLOG_CHECKPOINT:
2862 (errmsg("could not fork checkpoint process: %m")));
2864 case BS_XLOG_SHUTDOWN:
2866 (errmsg("could not fork shutdown process: %m")));
2870 (errmsg("could not fork process: %m")));
2875 * fork failure is fatal during startup/shutdown, but there's no
2876 * need to choke if a routine checkpoint fails.
2878 if (xlop == BS_XLOG_CHECKPOINT)
2884 * The startup and shutdown processes are not considered normal
2885 * backends, but the checkpoint process is. Checkpoint must be added
2886 * to the list of backends.
2888 if (xlop == BS_XLOG_CHECKPOINT)
2890 if (!(bn = (Backend *) malloc(sizeof(Backend))))
2893 (errcode(ERRCODE_OUT_OF_MEMORY),
2894 errmsg("out of memory")));
2899 bn->cancel_key = PostmasterRandom();
2900 DLAddHead(BackendList, DLNewElem(bn));
2903 * Since this code is executed periodically, it's a fine place to
2904 * do other actions that should happen every now and then on no
2905 * particular schedule. Such as...
2908 TouchSocketLockFile();
2916 * Create the opts file
2919 CreateOptsFile(int argc, char *argv[])
2921 char fullprogname[MAXPGPATH];
2922 char filename[MAXPGPATH];
2926 if (FindExec(fullprogname, argv[0], "postmaster") < 0)
2929 snprintf(filename, sizeof(filename), "%s/postmaster.opts", DataDir);
2931 if ((fp = fopen(filename, "w")) == NULL)
2933 elog(LOG, "could not create file \"%s\": %m", filename);
2937 fprintf(fp, "%s", fullprogname);
2938 for (i = 1; i < argc; i++)
2939 fprintf(fp, " '%s'", argv[i]);
2945 elog(LOG, "could not write file \"%s\": %m", filename);
2955 * This should be used only for reporting "interactive" errors (essentially,
2956 * bogus arguments on the command line). Once the postmaster is launched,
2957 * use ereport. In particular, don't use this for anything that occurs
2958 * after pmdaemonize.
2961 postmaster_error(const char *fmt,...)
2965 fprintf(stderr, "%s: ", progname);
2967 vfprintf(stderr, gettext(fmt), ap);
2969 fprintf(stderr, "\n");