1 /*-------------------------------------------------------------------------
4 * This program acts as a clearing house for requests to the
5 * POSTGRES system. Frontend programs send a startup message
6 * to the Postmaster and the postmaster uses the info in the
7 * message to setup a backend process.
9 * The postmaster also manages system-wide operations such as
10 * startup and shutdown. The postmaster itself doesn't do those
11 * operations, mind you --- it just forks off a subprocess to do them
12 * at the right times. It also takes care of resetting the system
13 * if a backend crashes.
15 * The postmaster process creates the shared memory and semaphore
16 * pools during startup, but as a rule does not touch them itself.
17 * In particular, it is not a member of the PGPROC array of backends
18 * and so it cannot participate in lock-manager operations. Keeping
19 * the postmaster away from shared memory operations makes it simpler
20 * and more reliable. The postmaster is almost always able to recover
21 * from crashes of individual backends by resetting shared memory;
22 * if it did much with shared memory then it would be prone to crashing
23 * along with the backends.
25 * When a request message is received, we now fork() immediately.
26 * The child process performs authentication of the request, and
27 * then becomes a backend if successful. This allows the auth code
28 * to be written in a simple single-threaded style (as opposed to the
29 * crufty "poor man's multitasking" code that used to be needed).
30 * More importantly, it ensures that blockages in non-multithreaded
31 * libraries like SSL or PAM cannot cause denial of service to other
35 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
36 * Portions Copyright (c) 1994, Regents of the University of California
40 * $PostgreSQL: pgsql/src/backend/postmaster/postmaster.c,v 1.407 2004/07/11 00:18:43 momjian Exp $
45 * The Postmaster sets up shared memory data structures
49 * The Postmaster shares memory with the backends but should avoid
50 * touching shared memory, so as not to become stuck if a crashing
51 * backend screws up locks or shared memory. Likewise, the Postmaster
52 * should never block on messages from frontend clients.
55 * The Postmaster cleans up after backends if they have an emergency
56 * exit and/or core dump.
59 * Use write_stderr() only for reporting "interactive" errors
60 * (essentially, bogus arguments on the command line). Once the
61 * postmaster is launched, use ereport(). In particular, don't use
62 * write_stderr() for anything that occurs after pmdaemonize.
64 *-------------------------------------------------------------------------
75 #include <sys/socket.h>
78 #include <sys/param.h>
79 #include <netinet/in.h>
80 #include <arpa/inet.h>
84 #ifdef HAVE_SYS_SELECT_H
85 #include <sys/select.h>
93 #include <DNSServiceDiscovery/DNSServiceDiscovery.h>
96 #include "catalog/pg_database.h"
97 #include "commands/async.h"
98 #include "lib/dllist.h"
99 #include "libpq/auth.h"
100 #include "libpq/crypt.h"
101 #include "libpq/libpq.h"
102 #include "libpq/pqcomm.h"
103 #include "libpq/pqsignal.h"
104 #include "miscadmin.h"
105 #include "nodes/nodes.h"
106 #include "postmaster/postmaster.h"
107 #include "storage/fd.h"
108 #include "storage/ipc.h"
109 #include "storage/pg_shmem.h"
110 #include "storage/pmsignal.h"
111 #include "storage/proc.h"
112 #include "storage/bufmgr.h"
113 #include "access/xlog.h"
114 #include "tcop/tcopprot.h"
115 #include "utils/guc.h"
116 #include "utils/memutils.h"
117 #include "utils/ps_status.h"
118 #include "bootstrap/bootstrap.h"
123 * List of active backends (or child processes anyway; we don't actually
124 * know whether a given child has become a backend or is still in the
125 * authorization phase). This is used mainly to keep track of how many
126 * children we have and send them appropriate signals when necessary.
128 * "Special" children such as the startup and bgwriter tasks are not in
133 pid_t pid; /* process id of backend */
134 long cancel_key; /* cancel key for cancels for this backend */
137 static Dllist *BackendList;
140 #define NUM_BACKENDARRAY_ELEMS (2*MaxBackends)
141 static Backend *ShmemBackendArray;
144 /* The socket number we are listening for connections on */
147 char *ListenAddresses;
150 * ReservedBackends is the number of backends reserved for superuser use.
151 * This number is taken out of the pool size given by MaxBackends so
152 * number of backend slots available to non-superusers is
153 * (MaxBackends - ReservedBackends). Note what this really means is
154 * "if there are <= ReservedBackends connections available, only superusers
155 * can make new connections" --- pre-existing superuser connections don't
156 * count against the limit.
158 int ReservedBackends;
161 static const char *progname = NULL;
163 /* The socket(s) we're listening to. */
165 static int ListenSocket[MAXLISTEN];
168 * Set by the -o option
170 static char ExtraOptions[MAXPGPATH];
173 * These globals control the behavior of the postmaster in case some
174 * backend dumps core. Normally, it kills all peers of the dead backend
175 * and reinitializes shared memory. By specifying -s or -n, we can have
176 * the postmaster stop (rather than kill) peers and not reinitialize
177 * shared data structures.
179 static bool Reinit = true;
180 static int SendStop = false;
182 /* still more option variables */
183 bool EnableSSL = false;
184 bool SilentMode = false; /* silent mode (-S) */
186 int PreAuthDelay = 0;
187 int AuthenticationTimeout = 60;
189 bool log_hostname; /* for ps display and logging */
190 bool Log_connections = false;
191 bool Db_user_namespace = false;
193 char *rendezvous_name;
195 /* list of library:init-function to be preloaded */
196 char *preload_libraries_string = NULL;
198 /* PIDs of special child processes; 0 when not running */
199 static pid_t StartupPID = 0,
203 /* Startup/shutdown state */
205 #define SmartShutdown 1
206 #define FastShutdown 2
208 static int Shutdown = NoShutdown;
210 static bool FatalError = false; /* T if recovering from backend crash */
212 bool ClientAuthInProgress = false; /* T during new-client
216 * State for assigning random salts and cancel keys.
217 * Also, the global MyCancelKey passes the cancel key assigned to a given
218 * backend from the postmaster to that backend (via fork).
220 static unsigned int random_seed = 0;
222 static int debug_flag = 0;
228 #ifdef HAVE_INT_OPTRESET
233 * postmaster.c - function prototypes
235 static void checkDataDir(const char *checkdir);
236 static bool onlyConfigSpecified(const char *checkdir);
237 #ifdef USE_RENDEZVOUS
238 static void reg_reply(DNSServiceRegistrationReplyErrorType errorCode,
241 static void pmdaemonize(void);
242 static Port *ConnCreate(int serverFd);
243 static void ConnFree(Port *port);
244 static void reset_shared(unsigned short port);
245 static void SIGHUP_handler(SIGNAL_ARGS);
246 static void pmdie(SIGNAL_ARGS);
247 static void reaper(SIGNAL_ARGS);
248 static void sigusr1_handler(SIGNAL_ARGS);
249 static void dummy_handler(SIGNAL_ARGS);
250 static void CleanupProc(int pid, int exitstatus);
251 static void HandleChildCrash(int pid, int exitstatus);
252 static void LogChildExit(int lev, const char *procname,
253 int pid, int exitstatus);
254 static int BackendRun(Port *port);
255 static void ExitPostmaster(int status);
256 static void usage(const char *);
257 static int ServerLoop(void);
258 static int BackendStartup(Port *port);
259 static int ProcessStartupPacket(Port *port, bool SSLdone);
260 static void processCancelRequest(Port *port, void *pkt);
261 static int initMasks(fd_set *rmask);
262 static void report_fork_failure_to_client(Port *port, int errnum);
263 static enum CAC_state canAcceptConnections(void);
264 static long PostmasterRandom(void);
265 static void RandomSalt(char *cryptSalt, char *md5Salt);
266 static void SignalChildren(int signal);
267 static int CountChildren(void);
268 static bool CreateOptsFile(int argc, char *argv[], char *fullprogname);
269 static pid_t StartChildProcess(int xlop);
274 static pid_t win32_forkexec(const char *path, char *argv[]);
275 static void win32_AddChild(pid_t pid, HANDLE handle);
276 static void win32_RemoveChild(pid_t pid);
277 static pid_t win32_waitpid(int *exitstatus);
278 static DWORD WINAPI win32_sigchld_waiter(LPVOID param);
280 static pid_t *win32_childPIDArray;
281 static HANDLE *win32_childHNDArray;
282 static unsigned long win32_numChildren = 0;
284 HANDLE PostmasterHandle;
287 static pid_t backend_forkexec(Port *port);
288 static pid_t internal_forkexec(int argc, char *argv[], Port *port);
290 static void read_backend_variables(char *filename, Port *port);
291 static bool write_backend_variables(char *filename, Port *port);
293 static void ShmemBackendArrayAdd(Backend *bn);
294 static void ShmemBackendArrayRemove(pid_t pid);
296 #endif /* EXEC_BACKEND */
298 #define StartupDataBase() StartChildProcess(BS_XLOG_STARTUP)
299 #define StartBackgroundWriter() StartChildProcess(BS_XLOG_BGWRITER)
303 * Postmaster main entry point
306 PostmasterMain(int argc, char *argv[])
310 char *userPGDATA = NULL;
313 progname = get_progname(argv[0]);
315 MyProcPid = PostmasterPid = getpid();
317 IsPostmasterEnvironment = true;
320 * Catch standard options before doing much else. This even works on
321 * systems without getopt_long.
325 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
330 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
332 puts("postmaster (PostgreSQL) " PG_VERSION);
338 * for security, no dir or file created can be group or other
341 umask((mode_t) 0077);
344 * Fire up essential subsystems: memory management
349 * By default, palloc() requests in the postmaster will be allocated
350 * in the PostmasterContext, which is space that can be recycled by
351 * backends. Allocated data that needs to be available to backends
352 * should be allocated in TopMemoryContext.
354 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
356 ALLOCSET_DEFAULT_MINSIZE,
357 ALLOCSET_DEFAULT_INITSIZE,
358 ALLOCSET_DEFAULT_MAXSIZE);
359 MemoryContextSwitchTo(PostmasterContext);
361 IgnoreSystemIndexes(false);
363 if (find_my_exec(argv[0], my_exec_path) < 0)
364 elog(FATAL, "%s: could not locate my own executable path",
367 get_pkglib_path(my_exec_path, pkglib_path);
372 InitializeGUCOptions();
374 userPGDATA = getenv("PGDATA"); /* default value */
378 while ((opt = getopt(argc, argv, "A:a:B:b:c:D:d:Fh:ik:lm:MN:no:p:Ss-:")) != -1)
383 #ifdef USE_ASSERT_CHECKING
384 SetConfigOption("debug_assertions", optarg, PGC_POSTMASTER, PGC_S_ARGV);
386 write_stderr("%s: assert checking is not compiled in\n", progname);
390 /* Can no longer set authentication method. */
393 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
396 /* Can no longer set the backend executable file to use. */
403 /* Turn on debugging for the postmaster. */
404 char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
406 sprintf(debugstr, "debug%s", optarg);
407 SetConfigOption("log_min_messages", debugstr,
408 PGC_POSTMASTER, PGC_S_ARGV);
410 debug_flag = atoi(optarg);
414 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
417 SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
420 SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
423 SetConfigOption("unix_socket_directory", optarg, PGC_POSTMASTER, PGC_S_ARGV);
427 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
431 /* Multiplexed backends no longer supported. */
436 * ignore this flag. This may be passed in because the
437 * program was run as 'postgres -M' instead of
442 /* The max number of backends to start. */
443 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
446 /* Don't reinit shared mem after abnormal exit */
452 * Other options to pass to the backend on the command line
454 snprintf(ExtraOptions + strlen(ExtraOptions),
455 sizeof(ExtraOptions) - strlen(ExtraOptions),
459 SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
464 * Start in 'S'ilent mode (disassociate from controlling
465 * tty). You may also think of this as 'S'ysV mode since
466 * it's most badly needed on SysV-derived systems like
469 SetConfigOption("silent_mode", "true", PGC_POSTMASTER, PGC_S_ARGV);
474 * In the event that some backend dumps core, send
475 * SIGSTOP, rather than SIGQUIT, to all its peers. This
476 * lets the wily post_hacker collect core dumps from
487 ParseLongOption(optarg, &name, &value);
492 (errcode(ERRCODE_SYNTAX_ERROR),
493 errmsg("--%s requires a value",
497 (errcode(ERRCODE_SYNTAX_ERROR),
498 errmsg("-c %s requires a value",
502 SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
510 write_stderr("Try \"%s --help\" for more information.\n",
517 * Postmaster accepts no non-option switch arguments.
521 write_stderr("%s: invalid argument: \"%s\"\n",
522 progname, argv[optind]);
523 write_stderr("Try \"%s --help\" for more information.\n",
528 if (onlyConfigSpecified(userPGDATA))
531 * It is either a file name or a directory with no
532 * global/pg_control file, and hence not a data directory.
534 user_pgconfig = userPGDATA;
535 ProcessConfigFile(PGC_POSTMASTER);
537 if (!guc_pgdata) /* Got a pgdata from the config file? */
539 write_stderr("%s does not know where to find the database system data.\n"
540 "This should be specified as 'pgdata' in %s%s.\n",
541 progname, userPGDATA,
542 user_pgconfig_is_dir ? "/postgresql.conf" : "");
545 checkDataDir(guc_pgdata);
546 SetDataDir(guc_pgdata);
550 /* Now we can set the data directory, and then read postgresql.conf. */
551 checkDataDir(userPGDATA);
552 SetDataDir(userPGDATA);
553 ProcessConfigFile(PGC_POSTMASTER);
556 if (external_pidfile)
558 FILE *fpidfile = fopen(external_pidfile, "w");
562 fprintf(fpidfile, "%d\n", MyProcPid);
564 /* Should we remove the pid file on postmaster exit? */
568 gettext("%s could not write to external pid file %s\n"),
569 progname, external_pidfile);
572 /* If timezone is not set, determine what the OS uses */
573 pg_timezone_initialize();
576 write_nondefault_variables(PGC_POSTMASTER);
580 * Check for invalid combinations of GUC settings.
582 if (NBuffers < 2 * MaxBackends || NBuffers < 16)
585 * Do not accept -B so small that backends are likely to starve
586 * for lack of buffers. The specific choices here are somewhat
589 write_stderr("%s: the number of buffers (-B) must be at least twice the number of allowed connections (-N) and at least 16\n", progname);
593 if (ReservedBackends >= MaxBackends)
595 write_stderr("%s: superuser_reserved_connections must be less than max_connections\n", progname);
600 * Other one-time internal sanity checks can go here.
602 if (!CheckDateTokenTables())
604 write_stderr("%s: invalid datetoken tables, please fix\n", progname);
609 * Now that we are done processing the postmaster arguments, reset
610 * getopt(3) library so that it will work correctly in subprocesses.
613 #ifdef HAVE_INT_OPTRESET
614 optreset = 1; /* some systems need this too */
617 /* For debugging: display postmaster environment */
619 extern char **environ;
623 (errmsg_internal("%s: PostmasterMain: initial environ dump:",
626 (errmsg_internal("-----------------------------------------")));
627 for (p = environ; *p; ++p)
629 (errmsg_internal("\t%s", *p)));
631 (errmsg_internal("-----------------------------------------")));
635 if (find_other_exec(argv[0], "postgres", PG_VERSIONSTR,
636 postgres_exec_path) < 0)
638 (errmsg("%s: could not locate matching postgres executable",
643 * Initialize SSL library, if specified.
651 * process any libraries that should be preloaded and optionally
654 if (preload_libraries_string)
655 process_preload_libraries(preload_libraries_string);
658 * Fork away from controlling terminal, if -S specified.
660 * Must do this before we grab any interlock files, else the interlocks
661 * will show the wrong PID.
667 * Create lockfile for data directory.
669 * We want to do this before we try to grab the input sockets, because
670 * the data directory interlock is more reliable than the socket-file
671 * interlock (thanks to whoever decided to put socket files in /tmp
672 * :-(). For the same reason, it's best to grab the TCP socket(s) before
675 CreateDataDirLockFile(DataDir, true);
678 * Remove old temporary files. At this point there can be no other
679 * Postgres processes running in this directory, so this should be
685 * Establish input sockets.
687 for (i = 0; i < MAXLISTEN; i++)
688 ListenSocket[i] = -1;
696 curhost = ListenAddresses;
699 /* ignore whitespace */
700 while (isspace((unsigned char) *curhost))
702 if (*curhost == '\0')
705 while (*endptr != '\0' && !isspace((unsigned char) *endptr))
709 if (strcmp(curhost, "*") == 0)
710 status = StreamServerPort(AF_UNSPEC, NULL,
711 (unsigned short) PostPortNumber,
713 ListenSocket, MAXLISTEN);
715 status = StreamServerPort(AF_UNSPEC, curhost,
716 (unsigned short) PostPortNumber,
718 ListenSocket, MAXLISTEN);
719 if (status != STATUS_OK)
721 (errmsg("could not create listen socket for \"%s\"",
725 curhost = endptr + 1;
731 #ifdef USE_RENDEZVOUS
732 /* Register for Rendezvous only if we opened TCP socket(s) */
733 if (ListenSocket[0] != -1 && rendezvous_name != NULL)
735 DNSServiceRegistrationCreate(rendezvous_name,
738 htonl(PostPortNumber),
740 (DNSServiceRegistrationReply) reg_reply,
745 #ifdef HAVE_UNIX_SOCKETS
746 status = StreamServerPort(AF_UNIX, NULL,
747 (unsigned short) PostPortNumber,
749 ListenSocket, MAXLISTEN);
750 if (status != STATUS_OK)
752 (errmsg("could not create Unix-domain socket")));
756 * check that we have some socket to listen on
758 if (ListenSocket[0] == -1)
760 (errmsg("no socket created for listening")));
765 * Set up shared memory and semaphores.
767 reset_shared(PostPortNumber);
770 * Estimate number of openable files. This must happen after setting
771 * up semaphores, because on some platforms semaphores count as open
777 * Initialize the list of active backends.
779 BackendList = DLNewList();
783 * Initialize the child pid/HANDLE arrays for signal handling.
785 win32_childPIDArray = (pid_t *)
786 malloc(NUM_BACKENDARRAY_ELEMS * sizeof(pid_t));
787 win32_childHNDArray = (HANDLE *)
788 malloc(NUM_BACKENDARRAY_ELEMS * sizeof(HANDLE));
789 if (!win32_childPIDArray || !win32_childHNDArray)
791 (errcode(ERRCODE_OUT_OF_MEMORY),
792 errmsg("out of memory")));
795 * Set up a handle that child processes can use to check whether the
796 * postmaster is still running.
798 if (DuplicateHandle(GetCurrentProcess(),
804 DUPLICATE_SAME_ACCESS) == 0)
806 (errmsg_internal("could not duplicate postmaster handle: %d",
807 (int) GetLastError())));
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, my_exec_path))
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, postmaster/bgwriter.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 shut down */
831 pqsignal(SIGQUIT, pmdie); /* send SIGQUIT and die */
832 pqsignal(SIGTERM, pmdie); /* wait for children and shut down */
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 * Initialize the statistics collector stuff
860 * Load cached files for client authentication.
868 * We're ready to rock and roll...
870 StartupPID = StartupDataBase();
873 write_nondefault_variables(PGC_POSTMASTER);
876 status = ServerLoop();
879 * ServerLoop probably shouldn't ever return, but if it does, close
882 ExitPostmaster(status != STATUS_OK);
884 return 0; /* not reached */
890 onlyConfigSpecified(const char *checkdir)
892 char path[MAXPGPATH];
893 struct stat stat_buf;
895 if (checkdir == NULL) /* checkDataDir handles this */
898 if (stat(checkdir, &stat_buf) == -1) /* ditto */
901 if (S_ISREG(stat_buf.st_mode)) /* It's a regular file, so assume it's explict */
903 else if (S_ISDIR(stat_buf.st_mode)) /* It's a directory, is it a config or system dir? */
905 snprintf(path, MAXPGPATH, "%s/global/pg_control", checkdir);
906 /* If this is not found, it is a config-only directory */
907 if (stat(path, &stat_buf) == -1)
915 * Validate the proposed data directory
918 checkDataDir(const char *checkdir)
920 char path[MAXPGPATH];
922 struct stat stat_buf;
924 if (checkdir == NULL)
926 write_stderr("%s does not know where to find the database system data.\n"
927 "You must specify the directory that contains the database system\n"
928 "or configuration files by either specifying the -D invocation option\n"
929 "or by setting the PGDATA environment variable.\n",
934 if (stat(checkdir, &stat_buf) == -1)
938 (errcode_for_file_access(),
939 errmsg("data or configuration location \"%s\" does not exist",
943 (errcode_for_file_access(),
944 errmsg("could not read permissions of \"%s\": %m",
949 * Check if the directory has group or world access. If so, reject.
951 * XXX temporarily suppress check when on Windows, because there may not
952 * be proper support for Unix-y file permissions. Need to think of a
953 * reasonable check to apply on Windows.
955 #if !defined(__CYGWIN__) && !defined(WIN32)
956 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
958 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
959 errmsg("data directory \"%s\" has group or world access",
961 errdetail("Permissions should be u=rwx (0700).")));
964 /* Look for PG_VERSION before looking for pg_control */
965 ValidatePgVersion(checkdir);
967 snprintf(path, sizeof(path), "%s/global/pg_control", checkdir);
969 fp = AllocateFile(path, PG_BINARY_R);
972 write_stderr("%s: could not find the database system\n"
973 "Expected to find it in the directory \"%s\",\n"
974 "but could not open file \"%s\": %s\n",
975 progname, checkdir, path, strerror(errno));
982 #ifdef USE_RENDEZVOUS
985 * empty callback function for DNSServiceRegistrationCreate()
988 reg_reply(DNSServiceRegistrationReplyErrorType errorCode, void *context)
993 #endif /* USE_RENDEZVOUS */
997 * Fork away from the controlling terminal (-S option)
1006 #ifdef LINUX_PROFILE
1007 struct itimerval prof_itimer;
1010 #ifdef LINUX_PROFILE
1011 /* see comments in BackendStartup */
1012 getitimer(ITIMER_PROF, &prof_itimer);
1016 if (pid == (pid_t) -1)
1018 write_stderr("%s: could not fork background process: %s\n",
1019 progname, strerror(errno));
1024 /* Parent should just exit, without doing any atexit cleanup */
1028 #ifdef LINUX_PROFILE
1029 setitimer(ITIMER_PROF, &prof_itimer, NULL);
1032 MyProcPid = PostmasterPid = getpid(); /* reset PID vars to child */
1034 /* GH: If there's no setsid(), we hopefully don't need silent mode.
1035 * Until there's a better solution.
1040 write_stderr("%s: could not dissociate from controlling TTY: %s\n",
1041 progname, strerror(errno));
1045 i = open(NULL_DEV, O_RDWR | PG_BINARY);
1052 elog(FATAL, "SilentMode not supported under WIN32");
1058 * Print out help message
1061 usage(const char *progname)
1063 printf(gettext("%s is the PostgreSQL server.\n\n"), progname);
1064 printf(gettext("Usage:\n %s [OPTION]...\n\n"), progname);
1065 printf(gettext("Options:\n"));
1066 #ifdef USE_ASSERT_CHECKING
1067 printf(gettext(" -A 1|0 enable/disable run-time assert checking\n"));
1069 printf(gettext(" -B NBUFFERS number of shared buffers\n"));
1070 printf(gettext(" -c NAME=VALUE set run-time parameter\n"));
1071 printf(gettext(" -d 1-5 debugging level\n"));
1072 printf(gettext(" -D DATADIR database directory\n"));
1073 printf(gettext(" -F turn fsync off\n"));
1074 printf(gettext(" -h HOSTNAME host name or IP address to listen on\n"));
1075 printf(gettext(" -i enable TCP/IP connections\n"));
1076 printf(gettext(" -k DIRECTORY Unix-domain socket location\n"));
1078 printf(gettext(" -l enable SSL connections\n"));
1080 printf(gettext(" -N MAX-CONNECT maximum number of allowed connections\n"));
1081 printf(gettext(" -o OPTIONS pass \"OPTIONS\" to each server process\n"));
1082 printf(gettext(" -p PORT port number to listen on\n"));
1083 printf(gettext(" -S silent mode (start in background without logging output)\n"));
1084 printf(gettext(" --help show this help, then exit\n"));
1085 printf(gettext(" --version output version information, then exit\n"));
1087 printf(gettext("\nDeveloper options:\n"));
1088 printf(gettext(" -n do not reinitialize shared memory after abnormal exit\n"));
1089 printf(gettext(" -s send SIGSTOP to all backend servers if one dies\n"));
1091 printf(gettext("\nPlease read the documentation for the complete list of run-time\n"
1092 "configuration settings and how to set them on the command line or in\n"
1093 "the configuration file.\n\n"
1094 "Report bugs to <pgsql-bugs@postgresql.org>.\n"));
1099 * Main idle loop of postmaster
1108 struct timeval earlier,
1112 gettimeofday(&earlier, &tz);
1113 last_touch_time = time(NULL);
1115 nSockets = initMasks(&readmask);
1121 struct timeval timeout;
1126 * Wait for something to happen.
1128 * We wait at most one minute, to ensure that the other background
1129 * tasks handled below get done even when no requests are arriving.
1131 memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
1133 timeout.tv_sec = 60;
1134 timeout.tv_usec = 0;
1136 PG_SETMASK(&UnBlockSig);
1138 selres = select(nSockets, &rmask, NULL, NULL, &timeout);
1141 * Block all signals until we wait again. (This makes it safe for
1142 * our signal handlers to do nontrivial work.)
1144 PG_SETMASK(&BlockSig);
1148 if (errno == EINTR || errno == EWOULDBLOCK)
1151 (errcode_for_socket_access(),
1152 errmsg("select() failed in postmaster: %m")));
1153 return STATUS_ERROR;
1157 * New connection pending on any of our sockets? If so, fork a
1158 * child process to deal with it.
1163 * Select a random seed at the time of first receiving a request.
1165 while (random_seed == 0)
1167 gettimeofday(&later, &tz);
1170 * We are not sure how much precision is in tv_usec, so we
1171 * swap the nibbles of 'later' and XOR them with 'earlier'. On
1172 * the off chance that the result is 0, we loop until it isn't.
1174 random_seed = earlier.tv_usec ^
1175 ((later.tv_usec << 16) |
1176 ((later.tv_usec >> 16) & 0xffff));
1179 for (i = 0; i < MAXLISTEN; i++)
1181 if (ListenSocket[i] == -1)
1183 if (FD_ISSET(ListenSocket[i], &rmask))
1185 port = ConnCreate(ListenSocket[i]);
1188 BackendStartup(port);
1191 * We no longer need the open socket or port structure
1194 StreamClose(port->sock);
1202 * If no background writer process is running, and we are not in
1203 * a state that prevents it, start one. It doesn't matter if this
1204 * fails, we'll just try again later.
1206 if (BgWriterPID == 0 && StartupPID == 0 && !FatalError)
1208 BgWriterPID = StartBackgroundWriter();
1209 /* If shutdown is pending, set it going */
1210 if (Shutdown > NoShutdown && BgWriterPID != 0)
1211 kill(BgWriterPID, SIGUSR2);
1214 /* If we have lost the stats collector, try to start a new one */
1215 if (PgStatPID == 0 &&
1216 StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
1217 PgStatPID = pgstat_start();
1220 * Touch the socket and lock file at least every ten minutes, to ensure
1221 * that they are not removed by overzealous /tmp-cleaning tasks.
1224 if (now - last_touch_time >= 10 * 60)
1227 TouchSocketLockFile();
1228 last_touch_time = now;
1235 * Initialise the masks for select() for the ports we are listening on.
1236 * Return the number of sockets to listen on.
1239 initMasks(fd_set *rmask)
1246 for (i = 0; i < MAXLISTEN; i++)
1248 int fd = ListenSocket[i];
1262 * Read the startup packet and do something according to it.
1264 * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
1265 * not return at all.
1267 * (Note that ereport(FATAL) stuff is sent to the client, so only use it
1268 * if that's what you want. Return STATUS_ERROR if you don't want to
1269 * send anything to the client, which would typically be appropriate
1270 * if we detect a communications failure.)
1273 ProcessStartupPacket(Port *port, bool SSLdone)
1277 ProtocolVersion proto;
1278 MemoryContext oldcontext;
1280 if (pq_getbytes((char *) &len, 4) == EOF)
1283 * EOF after SSLdone probably means the client didn't like our
1284 * response to NEGOTIATE_SSL_CODE. That's not an error condition,
1285 * so don't clutter the log with a complaint.
1289 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1290 errmsg("incomplete startup packet")));
1291 return STATUS_ERROR;
1297 if (len < (int32) sizeof(ProtocolVersion) ||
1298 len > MAX_STARTUP_PACKET_LENGTH)
1301 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1302 errmsg("invalid length of startup packet")));
1303 return STATUS_ERROR;
1307 * Allocate at least the size of an old-style startup packet, plus one
1308 * extra byte, and make sure all are zeroes. This ensures we will
1309 * have null termination of all strings, in both fixed- and
1310 * variable-length packet layouts.
1312 if (len <= (int32) sizeof(StartupPacket))
1313 buf = palloc0(sizeof(StartupPacket) + 1);
1315 buf = palloc0(len + 1);
1317 if (pq_getbytes(buf, len) == EOF)
1320 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1321 errmsg("incomplete startup packet")));
1322 return STATUS_ERROR;
1326 * The first field is either a protocol version number or a special
1329 port->proto = proto = ntohl(*((ProtocolVersion *) buf));
1331 if (proto == CANCEL_REQUEST_CODE)
1333 processCancelRequest(port, buf);
1334 return 127; /* XXX */
1337 if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
1342 /* No SSL when disabled or on Unix sockets */
1343 if (!EnableSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
1346 SSLok = 'S'; /* Support for SSL */
1348 SSLok = 'N'; /* No support for SSL */
1350 if (send(port->sock, &SSLok, 1, 0) != 1)
1353 (errcode_for_socket_access(),
1354 errmsg("failed to send SSL negotiation response: %m")));
1355 return STATUS_ERROR; /* close the connection */
1359 if (SSLok == 'S' && secure_open_server(port) == -1)
1360 return STATUS_ERROR;
1362 /* regular startup packet, cancel, etc packet should follow... */
1363 /* but not another SSL negotiation request */
1364 return ProcessStartupPacket(port, true);
1367 /* Could add additional special packet types here */
1370 * Set FrontendProtocol now so that ereport() knows what format to
1371 * send if we fail during startup.
1373 FrontendProtocol = proto;
1375 /* Check we can handle the protocol the frontend is using. */
1377 if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
1378 PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
1379 (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
1380 PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
1382 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1383 errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
1384 PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
1385 PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST),
1386 PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST),
1387 PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))));
1390 * Now fetch parameters out of startup packet and save them into the
1391 * Port structure. All data structures attached to the Port struct
1392 * must be allocated in TopMemoryContext so that they won't disappear
1393 * when we pass them to PostgresMain (see BackendRun). We need not
1394 * worry about leaking this storage on failure, since we aren't in the
1395 * postmaster process anymore.
1397 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1399 if (PG_PROTOCOL_MAJOR(proto) >= 3)
1401 int32 offset = sizeof(ProtocolVersion);
1404 * Scan packet body for name/option pairs. We can assume any
1405 * string beginning within the packet body is null-terminated,
1406 * thanks to zeroing extra byte above.
1408 port->guc_options = NIL;
1410 while (offset < len)
1412 char *nameptr = ((char *) buf) + offset;
1416 if (*nameptr == '\0')
1417 break; /* found packet terminator */
1418 valoffset = offset + strlen(nameptr) + 1;
1419 if (valoffset >= len)
1420 break; /* missing value, will complain below */
1421 valptr = ((char *) buf) + valoffset;
1423 if (strcmp(nameptr, "database") == 0)
1424 port->database_name = pstrdup(valptr);
1425 else if (strcmp(nameptr, "user") == 0)
1426 port->user_name = pstrdup(valptr);
1427 else if (strcmp(nameptr, "options") == 0)
1428 port->cmdline_options = pstrdup(valptr);
1431 /* Assume it's a generic GUC option */
1432 port->guc_options = lappend(port->guc_options,
1434 port->guc_options = lappend(port->guc_options,
1437 offset = valoffset + strlen(valptr) + 1;
1441 * If we didn't find a packet terminator exactly at the end of the
1442 * given packet length, complain.
1444 if (offset != len - 1)
1446 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1447 errmsg("invalid startup packet layout: expected terminator as last byte")));
1452 * Get the parameters from the old-style, fixed-width-fields
1453 * startup packet as C strings. The packet destination was
1454 * cleared first so a short packet has zeros silently added. We
1455 * have to be prepared to truncate the pstrdup result for oversize
1458 StartupPacket *packet = (StartupPacket *) buf;
1460 port->database_name = pstrdup(packet->database);
1461 if (strlen(port->database_name) > sizeof(packet->database))
1462 port->database_name[sizeof(packet->database)] = '\0';
1463 port->user_name = pstrdup(packet->user);
1464 if (strlen(port->user_name) > sizeof(packet->user))
1465 port->user_name[sizeof(packet->user)] = '\0';
1466 port->cmdline_options = pstrdup(packet->options);
1467 if (strlen(port->cmdline_options) > sizeof(packet->options))
1468 port->cmdline_options[sizeof(packet->options)] = '\0';
1469 port->guc_options = NIL;
1472 /* Check a user name was given. */
1473 if (port->user_name == NULL || port->user_name[0] == '\0')
1475 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1476 errmsg("no PostgreSQL user name specified in startup packet")));
1478 /* The database defaults to the user name. */
1479 if (port->database_name == NULL || port->database_name[0] == '\0')
1480 port->database_name = pstrdup(port->user_name);
1482 if (Db_user_namespace)
1485 * If user@, it is a global user, remove '@'. We only want to do
1486 * this if there is an '@' at the end and no earlier in the user
1487 * string or they may fake as a local user of another database
1488 * attaching to this database.
1490 if (strchr(port->user_name, '@') ==
1491 port->user_name + strlen(port->user_name) - 1)
1492 *strchr(port->user_name, '@') = '\0';
1495 /* Append '@' and dbname */
1498 db_user = palloc(strlen(port->user_name) +
1499 strlen(port->database_name) + 2);
1500 sprintf(db_user, "%s@%s", port->user_name, port->database_name);
1501 port->user_name = db_user;
1506 * Truncate given database and user names to length of a Postgres
1507 * name. This avoids lookup failures when overlength names are given.
1509 if (strlen(port->database_name) >= NAMEDATALEN)
1510 port->database_name[NAMEDATALEN - 1] = '\0';
1511 if (strlen(port->user_name) >= NAMEDATALEN)
1512 port->user_name[NAMEDATALEN - 1] = '\0';
1515 * Done putting stuff in TopMemoryContext.
1517 MemoryContextSwitchTo(oldcontext);
1520 * If we're going to reject the connection due to database state, say
1521 * so now instead of wasting cycles on an authentication exchange.
1522 * (This also allows a pg_ping utility to be written.)
1524 switch (port->canAcceptConnections)
1528 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1529 errmsg("the database system is starting up")));
1533 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1534 errmsg("the database system is shutting down")));
1538 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1539 errmsg("the database system is in recovery mode")));
1543 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
1544 errmsg("sorry, too many clients already")));
1556 * The client has sent a cancel request packet, not a normal
1557 * start-a-new-connection packet. Perform the necessary processing.
1558 * Nothing is sent back to the client.
1561 processCancelRequest(Port *port, void *pkt)
1563 CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
1565 long cancelAuthCode;
1567 #ifndef EXEC_BACKEND
1573 backendPID = (int) ntohl(canc->backendPID);
1574 cancelAuthCode = (long) ntohl(canc->cancelAuthCode);
1577 * See if we have a matching backend. In the EXEC_BACKEND case, we
1578 * can no longer access the postmaster's own backend list, and must
1579 * rely on the duplicate array in shared memory.
1581 #ifndef EXEC_BACKEND
1582 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
1584 bp = (Backend *) DLE_VAL(curr);
1586 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
1588 bp = (Backend *) &ShmemBackendArray[i];
1590 if (bp->pid == backendPID)
1592 if (bp->cancel_key == cancelAuthCode)
1594 /* Found a match; signal that backend to cancel current op */
1596 (errmsg_internal("processing cancel request: sending SIGINT to process %d",
1598 kill(bp->pid, SIGINT);
1601 /* Right PID, wrong key: no way, Jose */
1603 (errmsg_internal("bad key in cancel request for process %d",
1609 /* No matching backend */
1611 (errmsg_internal("bad pid in cancel request for process %d",
1616 * canAcceptConnections --- check to see if database state allows connections.
1618 static enum CAC_state
1619 canAcceptConnections(void)
1621 /* Can't start backends when in startup/shutdown/recovery state. */
1622 if (Shutdown > NoShutdown)
1623 return CAC_SHUTDOWN;
1627 return CAC_RECOVERY;
1630 * Don't start too many children.
1632 * We allow more connections than we can have backends here because some
1633 * might still be authenticating; they might fail auth, or some
1634 * existing backend might exit before the auth cycle is completed. The
1635 * exact MaxBackends limit is enforced when a new backend tries to
1636 * join the shared-inval backend array.
1638 if (CountChildren() >= 2 * MaxBackends)
1646 * ConnCreate -- create a local connection data structure
1649 ConnCreate(int serverFd)
1653 if (!(port = (Port *) calloc(1, sizeof(Port))))
1656 (errcode(ERRCODE_OUT_OF_MEMORY),
1657 errmsg("out of memory")));
1661 if (StreamConnection(serverFd, port) != STATUS_OK)
1663 StreamClose(port->sock);
1670 * Precompute password salt values to use for this connection.
1671 * It's slightly annoying to do this long in advance of knowing
1672 * whether we'll need 'em or not, but we must do the random()
1673 * calls before we fork, not after. Else the postmaster's random
1674 * sequence won't get advanced, and all backends would end up
1675 * using the same salt...
1677 RandomSalt(port->cryptSalt, port->md5Salt);
1685 * ConnFree -- free a local connection data structure
1688 ConnFree(Port *conn)
1698 * ClosePostmasterPorts -- close all the postmaster's open sockets
1700 * This is called during child process startup to release file descriptors
1701 * that are not needed by that child process. The postmaster still has
1702 * them open, of course.
1705 ClosePostmasterPorts(void)
1709 /* Close the listen sockets */
1710 for (i = 0; i < MAXLISTEN; i++)
1712 if (ListenSocket[i] != -1)
1714 StreamClose(ListenSocket[i]);
1715 ListenSocket[i] = -1;
1722 * reset_shared -- reset shared memory and semaphores
1725 reset_shared(unsigned short port)
1728 * Create or re-create shared memory and semaphores.
1730 * Note: in each "cycle of life" we will normally assign the same IPC
1731 * keys (if using SysV shmem and/or semas), since the port number is
1732 * used to determine IPC keys. This helps ensure that we will clean
1733 * up dead IPC objects if the postmaster crashes and is restarted.
1735 CreateSharedMemoryAndSemaphores(false, MaxBackends, port);
1740 * SIGHUP -- reread config files, and tell children to do same
1743 SIGHUP_handler(SIGNAL_ARGS)
1745 int save_errno = errno;
1747 PG_SETMASK(&BlockSig);
1749 if (Shutdown <= SmartShutdown)
1752 (errmsg("received SIGHUP, reloading configuration files")));
1753 ProcessConfigFile(PGC_SIGHUP);
1754 SignalChildren(SIGHUP);
1755 if (BgWriterPID != 0)
1756 kill(BgWriterPID, SIGHUP);
1757 /* PgStatPID does not currently need SIGHUP */
1762 /* Update the starting-point file for future children */
1763 write_nondefault_variables(PGC_SIGHUP);
1767 PG_SETMASK(&UnBlockSig);
1774 * pmdie -- signal handler for processing various postmaster signals.
1779 int save_errno = errno;
1781 PG_SETMASK(&BlockSig);
1784 (errmsg_internal("postmaster received signal %d",
1785 postgres_signal_arg)));
1787 switch (postgres_signal_arg)
1793 * Wait for children to end their work, then shut down.
1795 if (Shutdown >= SmartShutdown)
1797 Shutdown = SmartShutdown;
1799 (errmsg("received smart shutdown request")));
1801 if (DLGetHead(BackendList))
1802 break; /* let reaper() handle this */
1805 * No children left. Begin shutdown of data base system.
1807 if (StartupPID != 0 || FatalError)
1808 break; /* let reaper() handle this */
1809 /* Start the bgwriter if not running */
1810 if (BgWriterPID == 0)
1811 BgWriterPID = StartBackgroundWriter();
1812 /* And tell it to shut down */
1813 if (BgWriterPID != 0)
1814 kill(BgWriterPID, SIGUSR2);
1815 /* Tell pgstat to shut down too; nothing left for it to do */
1817 kill(PgStatPID, SIGQUIT);
1824 * Abort all children with SIGTERM (rollback active transactions
1825 * and exit) and shut down when they are gone.
1827 if (Shutdown >= FastShutdown)
1829 Shutdown = FastShutdown;
1831 (errmsg("received fast shutdown request")));
1833 if (DLGetHead(BackendList))
1838 (errmsg("aborting any active transactions")));
1839 SignalChildren(SIGTERM);
1840 /* reaper() does the rest */
1846 * No children left. Begin shutdown of data base system.
1848 * Note: if we previously got SIGTERM then we may send SIGUSR2
1849 * to the bgwriter a second time here. This should be harmless.
1851 if (StartupPID != 0 || FatalError)
1852 break; /* let reaper() handle this */
1853 /* Start the bgwriter if not running */
1854 if (BgWriterPID == 0)
1855 BgWriterPID = StartBackgroundWriter();
1856 /* And tell it to shut down */
1857 if (BgWriterPID != 0)
1858 kill(BgWriterPID, SIGUSR2);
1859 /* Tell pgstat to shut down too; nothing left for it to do */
1861 kill(PgStatPID, SIGQUIT);
1866 * Immediate Shutdown:
1868 * abort all children with SIGQUIT and exit without attempt to
1869 * properly shut down data base system.
1872 (errmsg("received immediate shutdown request")));
1873 if (StartupPID != 0)
1874 kill(StartupPID, SIGQUIT);
1875 if (BgWriterPID != 0)
1876 kill(BgWriterPID, SIGQUIT);
1878 kill(PgStatPID, SIGQUIT);
1879 if (DLGetHead(BackendList))
1880 SignalChildren(SIGQUIT);
1885 PG_SETMASK(&UnBlockSig);
1891 * Reaper -- signal handler to cleanup after a backend (child) dies.
1896 int save_errno = errno;
1899 int status; /* backend exit status */
1903 union wait status; /* backend exit status */
1907 int pid; /* process id of dead backend */
1909 PG_SETMASK(&BlockSig);
1912 (errmsg_internal("reaping dead processes")));
1914 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1916 exitstatus = status;
1919 while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
1921 exitstatus = status.w_status;
1923 while ((pid = win32_waitpid(&exitstatus)) > 0)
1926 * We need to do this here, and not in CleanupProc, since this is
1927 * to be called on all children when we are done with them. Could
1928 * move to LogChildExit, but that seems like asking for future
1931 win32_RemoveChild(pid);
1933 #endif /* HAVE_WAITPID */
1936 * Check if this child was a startup process.
1938 if (StartupPID != 0 && pid == StartupPID)
1941 if (exitstatus != 0)
1943 LogChildExit(LOG, gettext("startup process"),
1946 (errmsg("aborting startup due to startup process failure")));
1951 * Startup succeeded - we are done with system startup or recovery.
1956 * Crank up the background writer. It doesn't matter if this
1957 * fails, we'll just try again later.
1959 Assert(BgWriterPID == 0);
1960 BgWriterPID = StartBackgroundWriter();
1963 * Go to shutdown mode if a shutdown request was pending.
1964 * Otherwise, try to start the stats collector too.
1966 if (Shutdown > NoShutdown && BgWriterPID != 0)
1967 kill(BgWriterPID, SIGUSR2);
1968 else if (PgStatPID == 0 && Shutdown == NoShutdown)
1969 PgStatPID = pgstat_start();
1975 * Was it the bgwriter?
1977 if (BgWriterPID != 0 && pid == BgWriterPID)
1980 if (exitstatus == 0 && Shutdown > NoShutdown &&
1981 !FatalError && !DLGetHead(BackendList))
1984 * Normal postmaster exit is here: we've seen normal
1985 * exit of the bgwriter after it's been told to shut down.
1986 * We expect that it wrote a shutdown checkpoint. (If
1987 * for some reason it didn't, recovery will occur on next
1988 * postmaster start.)
1993 * Any unexpected exit of the bgwriter is treated as a crash.
1995 LogChildExit(LOG, gettext("background writer process"),
1997 HandleChildCrash(pid, exitstatus);
2002 * Was it the statistics collector? If so, just try to start a new
2003 * one; no need to force reset of the rest of the system. (If fail,
2004 * we'll try again in future cycles of the main loop.)
2006 if (PgStatPID != 0 && pid == PgStatPID)
2009 if (exitstatus != 0)
2010 LogChildExit(LOG, gettext("statistics collector process"),
2012 if (StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
2013 PgStatPID = pgstat_start();
2018 * Else do standard backend child cleanup.
2020 CleanupProc(pid, exitstatus);
2021 } /* loop over pending child-death reports */
2026 * Wait for all children exit, then reset shmem and
2029 if (DLGetHead(BackendList) || StartupPID != 0 || BgWriterPID != 0)
2032 (errmsg("all server processes terminated; reinitializing")));
2035 reset_shared(PostPortNumber);
2037 StartupPID = StartupDataBase();
2042 if (Shutdown > NoShutdown)
2044 if (DLGetHead(BackendList) || StartupPID != 0)
2046 /* Start the bgwriter if not running */
2047 if (BgWriterPID == 0)
2048 BgWriterPID = StartBackgroundWriter();
2049 /* And tell it to shut down */
2050 if (BgWriterPID != 0)
2051 kill(BgWriterPID, SIGUSR2);
2055 PG_SETMASK(&UnBlockSig);
2062 * CleanupProc -- cleanup after terminated backend.
2064 * Remove all local state associated with backend.
2067 CleanupProc(int pid,
2068 int exitstatus) /* child's exit status. */
2072 LogChildExit(DEBUG2, gettext("server process"), pid, exitstatus);
2075 * If a backend dies in an ugly way (i.e. exit status not 0) then we
2076 * must signal all other backends to quickdie. If exit status is zero
2077 * we assume everything is hunky dory and simply remove the backend
2078 * from the active backend list.
2080 if (exitstatus != 0)
2082 HandleChildCrash(pid, exitstatus);
2086 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2088 Backend *bp = (Backend *) DLE_VAL(curr);
2096 ShmemBackendArrayRemove(pid);
2098 /* Tell the collector about backend termination */
2106 * HandleChildCrash -- cleanup after failed backend or bgwriter.
2108 * The objectives here are to clean up our local state about the child
2109 * process, and to signal all other remaining children to quickdie.
2112 HandleChildCrash(int pid,
2113 int exitstatus) /* child's exit status. */
2120 * Make log entry unless there was a previous crash (if so, nonzero
2121 * exit status is to be expected in SIGQUIT response; don't clutter log)
2126 (pid == BgWriterPID) ?
2127 gettext("background writer process") :
2128 gettext("server process"),
2131 (errmsg("terminating any other active server processes")));
2134 /* Process regular backends */
2135 for (curr = DLGetHead(BackendList); curr; curr = next)
2137 next = DLGetSucc(curr);
2138 bp = (Backend *) DLE_VAL(curr);
2142 * Found entry for freshly-dead backend, so remove it.
2148 ShmemBackendArrayRemove(pid);
2150 /* Tell the collector about backend termination */
2152 /* Keep looping so we can signal remaining backends */
2157 * This backend is still alive. Unless we did so already,
2158 * tell it to commit hara-kiri.
2160 * SIGQUIT is the special signal that says exit without proc_exit
2161 * and let the user know what's going on. But if SendStop is
2162 * set (-s on command line), then we send SIGSTOP instead, so
2163 * that we can get core dumps from all backends by hand.
2168 (errmsg_internal("sending %s to process %d",
2169 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2171 kill(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
2176 /* Take care of the bgwriter too */
2177 if (pid == BgWriterPID)
2179 else if (BgWriterPID != 0 && !FatalError)
2182 (errmsg_internal("sending %s to process %d",
2183 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2184 (int) BgWriterPID)));
2185 kill(BgWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
2188 /* Force a power-cycle of the pgstat processes too */
2189 /* (Shouldn't be necessary, but just for luck) */
2190 if (PgStatPID != 0 && !FatalError)
2193 (errmsg_internal("sending %s to process %d",
2196 kill(PgStatPID, SIGQUIT);
2203 * Log the death of a child process.
2206 LogChildExit(int lev, const char *procname, int pid, int exitstatus)
2208 if (WIFEXITED(exitstatus))
2212 * translator: %s is a noun phrase describing a child process,
2213 * such as "server process"
2215 (errmsg("%s (PID %d) exited with exit code %d",
2216 procname, pid, WEXITSTATUS(exitstatus))));
2217 else if (WIFSIGNALED(exitstatus))
2221 * translator: %s is a noun phrase describing a child process,
2222 * such as "server process"
2224 (errmsg("%s (PID %d) was terminated by signal %d",
2225 procname, pid, WTERMSIG(exitstatus))));
2230 * translator: %s is a noun phrase describing a child process,
2231 * such as "server process"
2233 (errmsg("%s (PID %d) exited with unexpected status %d",
2234 procname, pid, exitstatus)));
2238 * Send a signal to all backend children (but NOT special children)
2241 SignalChildren(int signal)
2245 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2247 Backend *bp = (Backend *) DLE_VAL(curr);
2250 (errmsg_internal("sending signal %d to process %d",
2251 signal, (int) bp->pid)));
2252 kill(bp->pid, signal);
2257 * BackendStartup -- start backend process
2259 * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
2262 BackendStartup(Port *port)
2264 Backend *bn; /* for backend cleanup */
2267 #ifdef LINUX_PROFILE
2268 struct itimerval prof_itimer;
2272 * Compute the cancel key that will be assigned to this backend. The
2273 * backend will have its own copy in the forked-off process' value of
2274 * MyCancelKey, so that it can transmit the key to the frontend.
2276 MyCancelKey = PostmasterRandom();
2279 * Make room for backend data structure. Better before the fork() so
2280 * we can handle failure cleanly.
2282 bn = (Backend *) malloc(sizeof(Backend));
2286 (errcode(ERRCODE_OUT_OF_MEMORY),
2287 errmsg("out of memory")));
2288 return STATUS_ERROR;
2291 /* Pass down canAcceptConnections state (kluge for EXEC_BACKEND case) */
2292 port->canAcceptConnections = canAcceptConnections();
2295 * Flush stdio channels just before fork, to avoid double-output
2296 * problems. Ideally we'd use fflush(NULL) here, but there are still a
2297 * few non-ANSI stdio libraries out there (like SunOS 4.1.x) that
2298 * coredump if we do. Presently stdout and stderr are the only stdio
2299 * output channels used by the postmaster, so fflush'ing them should
2307 pid = backend_forkexec(port);
2309 #else /* !EXEC_BACKEND */
2311 #ifdef LINUX_PROFILE
2314 * Linux's fork() resets the profiling timer in the child process. If
2315 * we want to profile child processes then we need to save and restore
2316 * the timer setting. This is a waste of time if not profiling,
2317 * however, so only do it if commanded by specific -DLINUX_PROFILE
2320 getitimer(ITIMER_PROF, &prof_itimer);
2324 /* Specific beos actions before backend startup */
2325 beos_before_backend_startup();
2330 if (pid == 0) /* child */
2332 #ifdef LINUX_PROFILE
2333 setitimer(ITIMER_PROF, &prof_itimer, NULL);
2337 /* Specific beos backend startup actions */
2338 beos_backend_startup();
2342 proc_exit(BackendRun(port));
2345 #endif /* EXEC_BACKEND */
2349 /* in parent, fork failed */
2350 int save_errno = errno;
2353 /* Specific beos backend startup actions */
2354 beos_backend_startup_failed();
2359 (errmsg("could not fork new process for connection: %m")));
2360 report_fork_failure_to_client(port, save_errno);
2361 return STATUS_ERROR;
2364 /* in parent, successful fork */
2366 (errmsg_internal("forked new backend, pid=%d socket=%d",
2367 (int) pid, port->sock)));
2370 * Everything's been successful, it's safe to add this backend to our
2374 bn->cancel_key = MyCancelKey;
2375 DLAddHead(BackendList, DLNewElem(bn));
2377 ShmemBackendArrayAdd(bn);
2384 * Try to report backend fork() failure to client before we close the
2385 * connection. Since we do not care to risk blocking the postmaster on
2386 * this connection, we set the connection to non-blocking and try only once.
2388 * This is grungy special-purpose code; we cannot use backend libpq since
2389 * it's not up and running.
2392 report_fork_failure_to_client(Port *port, int errnum)
2396 /* Format the error message packet (always V2 protocol) */
2397 snprintf(buffer, sizeof(buffer), "E%s%s\n",
2398 gettext("could not fork new process for connection: "),
2401 /* Set port to non-blocking. Don't do send() if this fails */
2402 if (!set_noblock(port->sock))
2405 send(port->sock, buffer, strlen(buffer) + 1, 0);
2410 * split_opts -- split a string of options and append it to an argv array
2412 * NB: the string is destructively modified!
2414 * Since no current POSTGRES arguments require any quoting characters,
2415 * we can use the simple-minded tactic of assuming each set of space-
2416 * delimited characters is a separate argv element.
2418 * If you don't like that, well, we *used* to pass the whole option string
2419 * as ONE argument to execl(), which was even less intelligent...
2422 split_opts(char **argv, int *argcp, char *s)
2426 while (isspace((unsigned char) *s))
2430 argv[(*argcp)++] = s;
2431 while (*s && !isspace((unsigned char) *s))
2440 * BackendRun -- perform authentication, and if successful,
2441 * set up the backend's argument list and invoke PostgresMain()
2444 * Shouldn't return at all.
2445 * If PostgresMain() fails, return status.
2448 BackendRun(Port *port)
2453 char remote_host[NI_MAXHOST];
2454 char remote_port[NI_MAXSERV];
2455 char remote_ps_data[NI_MAXHOST];
2463 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
2466 * Let's clean up ourselves as the postmaster child, and close the
2467 * postmaster's listen sockets
2469 ClosePostmasterPorts();
2471 /* We don't want the postmaster's proc_exit() handlers */
2475 * Signal handlers setting is moved to tcop/postgres...
2478 /* Save port etc. for ps status */
2481 /* Reset MyProcPid to new backend's pid */
2482 MyProcPid = getpid();
2485 * PreAuthDelay is a debugging aid for investigating problems in the
2486 * authentication cycle: it can be set in postgresql.conf to allow
2487 * time to attach to the newly-forked backend with a debugger. (See
2488 * also the -W backend switch, which we allow clients to pass through
2489 * PGOPTIONS, but it is not honored until after authentication.)
2491 if (PreAuthDelay > 0)
2492 pg_usleep(PreAuthDelay * 1000000L);
2494 ClientAuthInProgress = true; /* limit visibility of log messages */
2496 /* save start time for end of session reporting */
2497 gettimeofday(&(port->session_start), NULL);
2499 /* set these to empty in case they are needed before we set them up */
2500 port->remote_host = "";
2501 port->remote_port = "";
2502 port->commandTag = "";
2505 * Initialize libpq and enable reporting of ereport errors to the
2506 * client. Must do this now because authentication uses libpq to send
2509 pq_init(); /* initialize libpq to talk to client */
2510 whereToSendOutput = Remote; /* now safe to ereport to client */
2513 * We arrange for a simple exit(0) if we receive SIGTERM or SIGQUIT
2514 * during any client authentication related communication. Otherwise
2515 * the postmaster cannot shutdown the database FAST or IMMED cleanly
2516 * if a buggy client blocks a backend during authentication.
2518 pqsignal(SIGTERM, authdie);
2519 pqsignal(SIGQUIT, authdie);
2520 pqsignal(SIGALRM, authdie);
2521 PG_SETMASK(&AuthBlockSig);
2524 * Get the remote host name and port for logging and status display.
2526 remote_host[0] = '\0';
2527 remote_port[0] = '\0';
2528 if (getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2529 remote_host, sizeof(remote_host),
2530 remote_port, sizeof(remote_port),
2531 (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV))
2533 int ret = getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2534 remote_host, sizeof(remote_host),
2535 remote_port, sizeof(remote_port),
2536 NI_NUMERICHOST | NI_NUMERICSERV);
2540 (errmsg("getnameinfo_all() failed: %s",
2541 gai_strerror(ret))));
2543 snprintf(remote_ps_data, sizeof(remote_ps_data),
2544 remote_port[0] == '\0' ? "%s" : "%s(%s)",
2545 remote_host, remote_port);
2547 if (Log_connections)
2549 (errmsg("connection received: host=%s port=%s",
2550 remote_host, remote_port)));
2553 * save remote_host and remote_port in port stucture
2555 port->remote_host = strdup(remote_host);
2556 port->remote_port = strdup(remote_port);
2559 * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.c
2560 * etcetera from the postmaster, and have to load them ourselves.
2561 * Build the PostmasterContext (which didn't exist before, in this
2562 * process) to contain the data.
2564 * FIXME: [fork/exec] Ugh. Is there a way around this overhead?
2567 Assert(PostmasterContext == NULL);
2568 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
2570 ALLOCSET_DEFAULT_MINSIZE,
2571 ALLOCSET_DEFAULT_INITSIZE,
2572 ALLOCSET_DEFAULT_MAXSIZE);
2573 MemoryContextSwitchTo(PostmasterContext);
2582 * Ready to begin client interaction. We will give up and exit(0)
2583 * after a time delay, so that a broken client can't hog a connection
2584 * indefinitely. PreAuthDelay doesn't count against the time limit.
2586 if (!enable_sig_alarm(AuthenticationTimeout * 1000, false))
2587 elog(FATAL, "could not set timer for authorization timeout");
2590 * Receive the startup packet (which might turn out to be a cancel
2593 status = ProcessStartupPacket(port, false);
2595 if (status != STATUS_OK)
2599 * Now that we have the user and database name, we can set the process
2600 * title for ps. It's good to do this as early as possible in
2603 init_ps_display(port->user_name, port->database_name, remote_ps_data);
2604 set_ps_display("authentication");
2607 * Now perform authentication exchange.
2609 ClientAuthentication(port); /* might not return, if failure */
2612 * Done with authentication. Disable timeout, and prevent
2613 * SIGTERM/SIGQUIT again until backend startup is complete.
2615 if (!disable_sig_alarm(false))
2616 elog(FATAL, "could not disable timer for authorization timeout");
2617 PG_SETMASK(&BlockSig);
2619 if (Log_connections)
2621 (errmsg("connection authorized: user=%s database=%s",
2622 port->user_name, port->database_name)));
2625 * Don't want backend to be able to see the postmaster random number
2626 * generator state. We have to clobber the static random_seed *and*
2627 * start a new random sequence in the random() library function.
2630 gettimeofday(&now, &tz);
2631 srandom((unsigned int) now.tv_usec);
2635 * Now, build the argv vector that will be given to PostgresMain.
2637 * The layout of the command line is
2638 * postgres [secure switches] -p databasename [insecure switches]
2639 * where the switches after -p come from the client request.
2641 * The maximum possible number of commandline arguments that could come
2642 * from ExtraOptions or port->cmdline_options is (strlen + 1) / 2; see
2646 maxac = 10; /* for fixed args supplied below */
2647 maxac += (strlen(ExtraOptions) + 1) / 2;
2648 if (port->cmdline_options)
2649 maxac += (strlen(port->cmdline_options) + 1) / 2;
2651 av = (char **) MemoryContextAlloc(TopMemoryContext,
2652 maxac * sizeof(char *));
2655 av[ac++] = "postgres";
2658 * Pass the requested debugging level along to the backend.
2662 snprintf(debugbuf, sizeof(debugbuf), "-d%d", debug_flag);
2663 av[ac++] = debugbuf;
2667 * Pass any backend switches specified with -o in the postmaster's own
2668 * command line. We assume these are secure. (It's OK to mangle
2669 * ExtraOptions now, since we're safely inside a subprocess.)
2671 split_opts(av, &ac, ExtraOptions);
2673 /* Tell the backend what protocol the frontend is using. */
2674 snprintf(protobuf, sizeof(protobuf), "-v%u", port->proto);
2675 av[ac++] = protobuf;
2678 * Tell the backend it is being called from the postmaster, and which
2679 * database to use. -p marks the end of secure switches.
2682 av[ac++] = port->database_name;
2685 * Pass the (insecure) option switches from the connection request.
2686 * (It's OK to mangle port->cmdline_options now.)
2688 if (port->cmdline_options)
2689 split_opts(av, &ac, port->cmdline_options);
2696 * Release postmaster's working memory context so that backend can
2697 * recycle the space. Note this does not trash *MyProcPort, because
2698 * ConnCreate() allocated that space with malloc() ... else we'd need
2699 * to copy the Port data here. Also, subsidiary data such as the
2700 * username isn't lost either; see ProcessStartupPacket().
2702 MemoryContextSwitchTo(TopMemoryContext);
2703 MemoryContextDelete(PostmasterContext);
2704 PostmasterContext = NULL;
2707 * Debug: print arguments being passed to backend
2710 (errmsg_internal("%s child[%d]: starting with (",
2711 progname, getpid())));
2712 for (i = 0; i < ac; ++i)
2714 (errmsg_internal("\t%s", av[i])));
2716 (errmsg_internal(")")));
2718 ClientAuthInProgress = false; /* client_min_messages is active
2721 return (PostgresMain(ac, av, port->user_name));
2728 * postmaster_forkexec -- fork and exec a postmaster subprocess
2730 * The caller must have set up the argv array already, except for argv[2]
2731 * which will be filled with the name of the temp variable file.
2733 * Returns the child process PID, or -1 on fork failure (a suitable error
2734 * message has been logged on failure).
2736 * All uses of this routine will dispatch to SubPostmasterMain in the
2740 postmaster_forkexec(int argc, char *argv[])
2744 /* This entry point passes dummy values for the Port variables */
2745 memset(&port, 0, sizeof(port));
2746 return internal_forkexec(argc, argv, &port);
2750 * backend_forkexec -- fork/exec off a backend process
2752 * returns the pid of the fork/exec'd process, or -1 on failure
2755 backend_forkexec(Port *port)
2760 av[ac++] = "postgres";
2761 av[ac++] = "-forkbackend";
2762 av[ac++] = NULL; /* filled in by internal_forkexec */
2765 Assert(ac < lengthof(av));
2767 return internal_forkexec(ac, av, port);
2771 internal_forkexec(int argc, char *argv[], Port *port)
2774 char tmpfilename[MAXPGPATH];
2776 if (!write_backend_variables(tmpfilename, port))
2777 return -1; /* log made by write_backend_variables */
2779 /* Make sure caller set up argv properly */
2781 Assert(argv[argc] == NULL);
2782 Assert(strncmp(argv[1], "-fork", 5) == 0);
2783 Assert(argv[2] == NULL);
2785 /* Insert temp file name after -fork argument */
2786 argv[2] = tmpfilename;
2789 pid = win32_forkexec(postgres_exec_path, argv);
2791 /* Fire off execv in child */
2792 if ((pid = fork()) == 0)
2794 if (execv(postgres_exec_path, argv) < 0)
2797 (errmsg("could not exec backend process \"%s\": %m",
2798 postgres_exec_path)));
2799 /* We're already in the child process here, can't return */
2805 return pid; /* Parent returns pid, or -1 on fork failure */
2809 * SubPostmasterMain -- Get the fork/exec'd process into a state equivalent
2810 * to what it would be if we'd simply forked on Unix, and then
2811 * dispatch to the appropriate place.
2813 * The first two command line arguments are expected to be "-forkFOO"
2814 * (where FOO indicates which postmaster child we are to become), and
2815 * the name of a variables file that we can read to load data that would
2816 * have been inherited by fork() on Unix. Remaining arguments go to the
2817 * subprocess FooMain() routine.
2820 SubPostmasterMain(int argc, char *argv[])
2824 /* Do this sooner rather than later... */
2825 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
2827 MyProcPid = getpid(); /* reset MyProcPid */
2829 /* In EXEC_BACKEND case we will not have inherited these settings */
2830 IsPostmasterEnvironment = true;
2831 whereToSendOutput = None;
2833 PG_SETMASK(&BlockSig);
2835 /* Setup essential subsystems */
2836 MemoryContextInit();
2837 InitializeGUCOptions();
2839 /* Check we got appropriate args */
2841 elog(FATAL, "invalid subpostmaster invocation");
2843 /* Read in file-based context */
2844 memset(&port, 0, sizeof(Port));
2845 read_backend_variables(argv[2], &port);
2846 read_nondefault_variables();
2848 /* Run backend or appropriate child */
2849 if (strcmp(argv[1], "-forkbackend") == 0)
2851 /* BackendRun will close sockets */
2853 /* Attach process to shared segments */
2854 CreateSharedMemoryAndSemaphores(false, MaxBackends, 0);
2856 Assert(argc == 3); /* shouldn't be any more args */
2857 proc_exit(BackendRun(&port));
2859 if (strcmp(argv[1], "-forkboot") == 0)
2861 /* Close the postmaster's sockets */
2862 ClosePostmasterPorts();
2864 /* Attach process to shared segments */
2865 CreateSharedMemoryAndSemaphores(false, MaxBackends, 0);
2867 BootstrapMain(argc - 2, argv + 2);
2870 if (strcmp(argv[1], "-forkbuf") == 0)
2872 /* Close the postmaster's sockets */
2873 ClosePostmasterPorts();
2875 /* Do not want to attach to shared memory */
2877 PgstatBufferMain(argc, argv);
2880 if (strcmp(argv[1], "-forkcol") == 0)
2883 * Do NOT close postmaster sockets here, because we are forking from
2884 * pgstat buffer process, which already did it.
2887 /* Do not want to attach to shared memory */
2889 PgstatCollectorMain(argc, argv);
2893 return 1; /* shouldn't get here */
2896 #endif /* EXEC_BACKEND */
2900 * ExitPostmaster -- cleanup
2902 * Do NOT call exit() directly --- always go through here!
2905 ExitPostmaster(int status)
2907 /* should cleanup shared memory and kill all backends */
2910 * Not sure of the semantics here. When the Postmaster dies, should
2911 * the backends all be killed? probably not.
2913 * MUST -- vadim 05-10-1999
2920 * sigusr1_handler - handle signal conditions from child processes
2923 sigusr1_handler(SIGNAL_ARGS)
2925 int save_errno = errno;
2927 PG_SETMASK(&BlockSig);
2929 if (CheckPostmasterSignal(PMSIGNAL_PASSWORD_CHANGE))
2932 * Password or group file has changed.
2938 if (CheckPostmasterSignal(PMSIGNAL_WAKEN_CHILDREN))
2941 * Send SIGUSR1 to all children (triggers
2942 * CatchupInterruptHandler). See storage/ipc/sinval[adt].c for the
2945 if (Shutdown <= SmartShutdown)
2946 SignalChildren(SIGUSR1);
2949 PG_SETMASK(&UnBlockSig);
2956 * Dummy signal handler
2958 * We use this for signals that we don't actually use in the postmaster,
2959 * but we do use in backends. If we were to SIG_IGN such signals in the
2960 * postmaster, then a newly started backend might drop a signal that arrives
2961 * before it's able to reconfigure its signal processing. (See notes in
2965 dummy_handler(SIGNAL_ARGS)
2971 * CharRemap: given an int in range 0..61, produce textual encoding of it
2972 * per crypt(3) conventions.
2996 RandomSalt(char *cryptSalt, char *md5Salt)
2998 long rand = PostmasterRandom();
3000 cryptSalt[0] = CharRemap(rand % 62);
3001 cryptSalt[1] = CharRemap(rand / 62);
3004 * It's okay to reuse the first random value for one of the MD5 salt
3005 * bytes, since only one of the two salts will be sent to the client.
3006 * After that we need to compute more random bits.
3008 * We use % 255, sacrificing one possible byte value, so as to ensure
3009 * that all bits of the random() value participate in the result.
3010 * While at it, add one to avoid generating any null bytes.
3012 md5Salt[0] = (rand % 255) + 1;
3013 rand = PostmasterRandom();
3014 md5Salt[1] = (rand % 255) + 1;
3015 rand = PostmasterRandom();
3016 md5Salt[2] = (rand % 255) + 1;
3017 rand = PostmasterRandom();
3018 md5Salt[3] = (rand % 255) + 1;
3025 PostmasterRandom(void)
3027 static bool initialized = false;
3031 Assert(random_seed != 0);
3032 srandom(random_seed);
3040 * Count up number of child processes (regular backends only)
3048 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
3057 * StartChildProcess -- start a non-backend child process for the postmaster
3059 * xlog determines what kind of child will be started. All child types
3060 * initially go to BootstrapMain, which will handle common setup.
3062 * Return value of StartChildProcess is subprocess' PID, or 0 if failed
3063 * to start subprocess.
3066 StartChildProcess(int xlop)
3072 #ifdef LINUX_PROFILE
3073 struct itimerval prof_itimer;
3077 * Set up command-line arguments for subprocess
3079 av[ac++] = "postgres";
3082 av[ac++] = "-forkboot";
3083 av[ac++] = NULL; /* filled in by postmaster_forkexec */
3086 snprintf(xlbuf, sizeof(xlbuf), "-x%d", xlop);
3090 av[ac++] = "template1";
3093 Assert(ac < lengthof(av));
3096 * Flush stdio channels (see comments in BackendStartup)
3103 pid = postmaster_forkexec(ac, av);
3105 #else /* !EXEC_BACKEND */
3107 #ifdef LINUX_PROFILE
3108 /* see comments in BackendStartup */
3109 getitimer(ITIMER_PROF, &prof_itimer);
3113 /* Specific beos actions before backend startup */
3114 beos_before_backend_startup();
3119 if (pid == 0) /* child */
3121 #ifdef LINUX_PROFILE
3122 setitimer(ITIMER_PROF, &prof_itimer, NULL);
3126 /* Specific beos actions after backend startup */
3127 beos_backend_startup();
3130 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
3132 /* Close the postmaster's sockets */
3133 ClosePostmasterPorts();
3135 /* Lose the postmaster's on-exit routines and port connections */
3138 BootstrapMain(ac, av);
3142 #endif /* EXEC_BACKEND */
3146 /* in parent, fork failed */
3147 int save_errno = errno;
3150 /* Specific beos actions before backend startup */
3151 beos_backend_startup_failed();
3156 case BS_XLOG_STARTUP:
3158 (errmsg("could not fork startup process: %m")));
3160 case BS_XLOG_BGWRITER:
3162 (errmsg("could not fork background writer process: %m")));
3166 (errmsg("could not fork process: %m")));
3171 * fork failure is fatal during startup, but there's no need
3172 * to choke immediately if starting other child types fails.
3174 if (xlop == BS_XLOG_STARTUP)
3180 * in parent, successful fork
3187 * Create the opts file
3190 CreateOptsFile(int argc, char *argv[], char *fullprogname)
3192 char filename[MAXPGPATH];
3196 snprintf(filename, sizeof(filename), "%s/postmaster.opts", DataDir);
3198 if ((fp = fopen(filename, "w")) == NULL)
3200 elog(LOG, "could not create file \"%s\": %m", filename);
3204 fprintf(fp, "%s", fullprogname);
3205 for (i = 1; i < argc; i++)
3206 fprintf(fp, " '%s'", argv[i]);
3211 elog(LOG, "could not write file \"%s\": %m", filename);
3222 * The following need to be available to the read/write_backend_variables
3225 #include "storage/spin.h"
3227 extern slock_t *ShmemLock;
3228 extern slock_t *ShmemIndexLock;
3229 extern void *ShmemIndexAlloc;
3230 typedef struct LWLock LWLock;
3231 extern LWLock *LWLockArray;
3232 extern slock_t *ProcStructLock;
3233 extern int pgStatSock;
3235 #define write_var(var,fp) fwrite((void*)&(var),sizeof(var),1,fp)
3236 #define read_var(var,fp) fread((void*)&(var),sizeof(var),1,fp)
3237 #define write_array_var(var,fp) fwrite((void*)(var),sizeof(var),1,fp)
3238 #define read_array_var(var,fp) fread((void*)(var),sizeof(var),1,fp)
3241 write_backend_variables(char *filename, Port *port)
3243 static unsigned long tmpBackendFileNum = 0;
3245 char str_buf[MAXPGPATH];
3247 /* Calculate name for temp file in caller's buffer */
3249 snprintf(filename, MAXPGPATH, "%s/%s/%s.backend_var.%d.%lu",
3250 DataDir, PG_TEMP_FILES_DIR, PG_TEMP_FILE_PREFIX,
3251 MyProcPid, ++tmpBackendFileNum);
3254 fp = AllocateFile(filename, PG_BINARY_W);
3257 /* As per OpenTemporaryFile... */
3258 char dirname[MAXPGPATH];
3260 snprintf(dirname, MAXPGPATH, "%s/%s", DataDir, PG_TEMP_FILES_DIR);
3261 mkdir(dirname, S_IRWXU);
3263 fp = AllocateFile(filename, PG_BINARY_W);
3267 (errcode_for_file_access(),
3268 errmsg("could not create file \"%s\": %m",
3275 write_var(port->sock, fp);
3276 write_var(port->proto, fp);
3277 write_var(port->laddr, fp);
3278 write_var(port->raddr, fp);
3279 write_var(port->canAcceptConnections, fp);
3280 write_var(port->cryptSalt, fp);
3281 write_var(port->md5Salt, fp);
3284 * XXX FIXME later: writing these strings as MAXPGPATH bytes always is
3285 * probably a waste of resources
3288 StrNCpy(str_buf, DataDir, MAXPGPATH);
3289 write_array_var(str_buf, fp);
3291 write_array_var(ListenSocket, fp);
3293 write_var(MyCancelKey, fp);
3295 write_var(UsedShmemSegID, fp);
3296 write_var(UsedShmemSegAddr, fp);
3298 write_var(ShmemLock, fp);
3299 write_var(ShmemIndexLock, fp);
3300 write_var(ShmemVariableCache, fp);
3301 write_var(ShmemIndexAlloc, fp);
3302 write_var(ShmemBackendArray, fp);
3304 write_var(LWLockArray, fp);
3305 write_var(ProcStructLock, fp);
3306 write_var(pgStatSock, fp);
3308 write_var(debug_flag, fp);
3309 write_var(PostmasterPid, fp);
3311 write_var(PostmasterHandle, fp);
3314 StrNCpy(str_buf, my_exec_path, MAXPGPATH);
3315 write_array_var(str_buf, fp);
3317 write_array_var(ExtraOptions, fp);
3319 StrNCpy(str_buf, setlocale(LC_COLLATE, NULL), MAXPGPATH);
3320 write_array_var(str_buf, fp);
3321 StrNCpy(str_buf, setlocale(LC_CTYPE, NULL), MAXPGPATH);
3322 write_array_var(str_buf, fp);
3328 (errcode_for_file_access(),
3329 errmsg("could not write to file \"%s\": %m", filename)));
3337 read_backend_variables(char *filename, Port *port)
3340 char str_buf[MAXPGPATH];
3343 fp = AllocateFile(filename, PG_BINARY_R);
3346 (errcode_for_file_access(),
3347 errmsg("could not read from backend variables file \"%s\": %m",
3351 read_var(port->sock, fp);
3352 read_var(port->proto, fp);
3353 read_var(port->laddr, fp);
3354 read_var(port->raddr, fp);
3355 read_var(port->canAcceptConnections, fp);
3356 read_var(port->cryptSalt, fp);
3357 read_var(port->md5Salt, fp);
3359 read_array_var(str_buf, fp);
3360 SetDataDir(str_buf);
3362 read_array_var(ListenSocket, fp);
3364 read_var(MyCancelKey, fp);
3366 read_var(UsedShmemSegID, fp);
3367 read_var(UsedShmemSegAddr, fp);
3369 read_var(ShmemLock, fp);
3370 read_var(ShmemIndexLock, fp);
3371 read_var(ShmemVariableCache, fp);
3372 read_var(ShmemIndexAlloc, fp);
3373 read_var(ShmemBackendArray, fp);
3375 read_var(LWLockArray, fp);
3376 read_var(ProcStructLock, fp);
3377 read_var(pgStatSock, fp);
3379 read_var(debug_flag, fp);
3380 read_var(PostmasterPid, fp);
3382 read_var(PostmasterHandle, fp);
3385 read_array_var(str_buf, fp);
3386 StrNCpy(my_exec_path, str_buf, MAXPGPATH);
3388 read_array_var(ExtraOptions, fp);
3390 read_array_var(str_buf, fp);
3391 setlocale(LC_COLLATE, str_buf);
3392 read_array_var(str_buf, fp);
3393 setlocale(LC_CTYPE, str_buf);
3397 if (unlink(filename) != 0)
3399 (errcode_for_file_access(),
3400 errmsg("could not remove file \"%s\": %m", filename)));
3405 ShmemBackendArraySize(void)
3407 return (NUM_BACKENDARRAY_ELEMS * sizeof(Backend));
3411 ShmemBackendArrayAllocation(void)
3413 size_t size = ShmemBackendArraySize();
3415 ShmemBackendArray = (Backend *) ShmemAlloc(size);
3416 /* Mark all slots as empty */
3417 memset(ShmemBackendArray, 0, size);
3421 ShmemBackendArrayAdd(Backend *bn)
3425 /* Find an empty slot */
3426 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
3428 if (ShmemBackendArray[i].pid == 0)
3430 ShmemBackendArray[i] = *bn;
3436 (errmsg_internal("no free slots in shmem backend array")));
3440 ShmemBackendArrayRemove(pid_t pid)
3444 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
3446 if (ShmemBackendArray[i].pid == pid)
3448 /* Mark the slot as empty */
3449 ShmemBackendArray[i].pid = 0;
3455 (errmsg_internal("could not find backend entry with pid %d",
3459 #endif /* EXEC_BACKEND */
3465 win32_forkexec(const char *path, char *argv[])
3468 PROCESS_INFORMATION pi;
3471 char cmdLine[MAXPGPATH * 2];
3472 HANDLE childHandleCopy;
3473 HANDLE waiterThread;
3475 /* Format the cmd line */
3476 cmdLine[sizeof(cmdLine)-1] = '\0';
3477 cmdLine[sizeof(cmdLine)-2] = '\0';
3478 snprintf(cmdLine, sizeof(cmdLine)-1, "\"%s\"", path);
3480 while (argv[++i] != NULL)
3482 j = strlen(cmdLine);
3483 snprintf(cmdLine+j, sizeof(cmdLine)-1-j, " \"%s\"", argv[i]);
3485 if (cmdLine[sizeof(cmdLine)-2] != '\0')
3487 elog(LOG, "subprocess command line too long");
3491 memset(&pi, 0, sizeof(pi));
3492 memset(&si, 0, sizeof(si));
3494 if (!CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
3496 elog(LOG, "CreateProcess call failed (%d): %m", (int) GetLastError());
3500 if (!IsUnderPostmaster)
3502 /* We are the Postmaster creating a child... */
3503 win32_AddChild(pi.dwProcessId, pi.hProcess);
3506 if (DuplicateHandle(GetCurrentProcess(),
3508 GetCurrentProcess(),
3512 DUPLICATE_SAME_ACCESS) == 0)
3514 (errmsg_internal("could not duplicate child handle: %d",
3515 (int) GetLastError())));
3517 waiterThread = CreateThread(NULL, 64 * 1024, win32_sigchld_waiter,
3518 (LPVOID) childHandleCopy, 0, NULL);
3521 (errmsg_internal("could not create sigchld waiter thread: %d",
3522 (int) GetLastError())));
3523 CloseHandle(waiterThread);
3525 if (IsUnderPostmaster)
3526 CloseHandle(pi.hProcess);
3527 CloseHandle(pi.hThread);
3529 return pi.dwProcessId;
3533 * Note: The following three functions must not be interrupted (eg. by
3534 * signals). As the Postgres Win32 signalling architecture (currently)
3535 * requires polling, or APC checking functions which aren't used here, this
3538 * We keep two separate arrays, instead of a single array of pid/HANDLE
3539 * structs, to avoid having to re-create a handle array for
3540 * WaitForMultipleObjects on each call to win32_waitpid.
3544 win32_AddChild(pid_t pid, HANDLE handle)
3546 Assert(win32_childPIDArray && win32_childHNDArray);
3547 if (win32_numChildren < NUM_BACKENDARRAY_ELEMS)
3549 win32_childPIDArray[win32_numChildren] = pid;
3550 win32_childHNDArray[win32_numChildren] = handle;
3551 ++win32_numChildren;
3555 (errmsg_internal("no room for child entry with pid %lu",
3556 (unsigned long) pid)));
3560 win32_RemoveChild(pid_t pid)
3564 Assert(win32_childPIDArray && win32_childHNDArray);
3566 for (i = 0; i < win32_numChildren; i++)
3568 if (win32_childPIDArray[i] == pid)
3570 CloseHandle(win32_childHNDArray[i]);
3572 /* Swap last entry into the "removed" one */
3573 --win32_numChildren;
3574 win32_childPIDArray[i] = win32_childPIDArray[win32_numChildren];
3575 win32_childHNDArray[i] = win32_childHNDArray[win32_numChildren];
3581 (errmsg_internal("could not find child entry with pid %lu",
3582 (unsigned long) pid)));
3586 win32_waitpid(int *exitstatus)
3588 Assert(win32_childPIDArray && win32_childHNDArray);
3589 elog(DEBUG3, "waiting on %lu children", win32_numChildren);
3591 if (win32_numChildren > 0)
3594 * Note: Do NOT use WaitForMultipleObjectsEx, as we don't want to
3595 * run queued APCs here.
3601 ret = WaitForMultipleObjects(win32_numChildren, win32_childHNDArray,
3607 (errmsg_internal("failed to wait on %lu children: %d",
3608 win32_numChildren, (int) GetLastError())));
3612 /* No children have finished */
3618 * Get the exit code, and return the PID of, the
3619 * respective process
3621 index = ret - WAIT_OBJECT_0;
3622 Assert(index >= 0 && index < win32_numChildren);
3623 if (!GetExitCodeProcess(win32_childHNDArray[index], &exitCode))
3626 * If we get this far, this should never happen, but,
3627 * then again... No choice other than to assume a
3628 * catastrophic failure.
3631 (errmsg_internal("failed to get exit code for child %lu",
3632 win32_childPIDArray[index])));
3634 *exitstatus = (int) exitCode;
3635 return win32_childPIDArray[index];
3644 * Note! Code below executes on separate threads, one for
3645 * each child process created
3648 win32_sigchld_waiter(LPVOID param)
3650 HANDLE procHandle = (HANDLE) param;
3652 DWORD r = WaitForSingleObject(procHandle, INFINITE);
3654 if (r == WAIT_OBJECT_0)
3655 pg_queue_signal(SIGCHLD);
3657 write_stderr("ERROR: failed to wait on child process handle: %d\n",
3658 (int) GetLastError());
3659 CloseHandle(procHandle);