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-2004, 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.438 2004/11/14 19:35:30 tgl Exp $
45 * The Postmaster sets up shared memory data structures
49 * The Postmaster shares memory with the backends but should avoid
50 * touching shared memory, so as not to become stuck if a crashing
51 * backend screws up locks or shared memory. Likewise, the Postmaster
52 * should never block on messages from frontend clients.
55 * The Postmaster cleans up after backends if they have an emergency
56 * exit and/or core dump.
59 * Use write_stderr() only for reporting "interactive" errors
60 * (essentially, bogus arguments on the command line). Once the
61 * postmaster is launched, use ereport(). In particular, don't use
62 * write_stderr() for anything that occurs after pmdaemonize.
64 *-------------------------------------------------------------------------
75 #include <sys/socket.h>
77 #include <sys/param.h>
78 #include <netinet/in.h>
79 #include <arpa/inet.h>
83 #ifdef HAVE_SYS_SELECT_H
84 #include <sys/select.h>
92 #include <DNSServiceDiscovery/DNSServiceDiscovery.h>
95 #include "catalog/pg_database.h"
96 #include "commands/async.h"
97 #include "lib/dllist.h"
98 #include "libpq/auth.h"
99 #include "libpq/crypt.h"
100 #include "libpq/libpq.h"
101 #include "libpq/pqcomm.h"
102 #include "libpq/pqsignal.h"
103 #include "miscadmin.h"
104 #include "nodes/nodes.h"
105 #include "postmaster/postmaster.h"
106 #include "postmaster/pgarch.h"
107 #include "postmaster/syslogger.h"
108 #include "storage/fd.h"
109 #include "storage/ipc.h"
110 #include "storage/pg_shmem.h"
111 #include "storage/pmsignal.h"
112 #include "storage/proc.h"
113 #include "storage/bufmgr.h"
114 #include "access/xlog.h"
115 #include "tcop/tcopprot.h"
116 #include "utils/builtins.h"
117 #include "utils/guc.h"
118 #include "utils/memutils.h"
119 #include "utils/ps_status.h"
120 #include "bootstrap/bootstrap.h"
125 * List of active backends (or child processes anyway; we don't actually
126 * know whether a given child has become a backend or is still in the
127 * authorization phase). This is used mainly to keep track of how many
128 * children we have and send them appropriate signals when necessary.
130 * "Special" children such as the startup and bgwriter tasks are not in
135 pid_t pid; /* process id of backend */
136 long cancel_key; /* cancel key for cancels for this backend */
139 static Dllist *BackendList;
142 #define NUM_BACKENDARRAY_ELEMS (2*MaxBackends)
143 static Backend *ShmemBackendArray;
146 /* The socket number we are listening for connections on */
149 char *ListenAddresses;
152 * ReservedBackends is the number of backends reserved for superuser use.
153 * This number is taken out of the pool size given by MaxBackends so
154 * number of backend slots available to non-superusers is
155 * (MaxBackends - ReservedBackends). Note what this really means is
156 * "if there are <= ReservedBackends connections available, only superusers
157 * can make new connections" --- pre-existing superuser connections don't
158 * count against the limit.
160 int ReservedBackends;
163 static const char *progname = NULL;
165 /* The socket(s) we're listening to. */
167 static int ListenSocket[MAXLISTEN];
170 * Set by the -o option
172 static char ExtraOptions[MAXPGPATH];
175 * These globals control the behavior of the postmaster in case some
176 * backend dumps core. Normally, it kills all peers of the dead backend
177 * and reinitializes shared memory. By specifying -s or -n, we can have
178 * the postmaster stop (rather than kill) peers and not reinitialize
179 * shared data structures.
181 static bool Reinit = true;
182 static int SendStop = false;
184 /* still more option variables */
185 bool EnableSSL = false;
186 bool SilentMode = false; /* silent mode (-S) */
188 int PreAuthDelay = 0;
189 int AuthenticationTimeout = 60;
191 bool log_hostname; /* for ps display and logging */
192 bool Log_connections = false;
193 bool Db_user_namespace = false;
195 char *rendezvous_name;
197 /* list of library:init-function to be preloaded */
198 char *preload_libraries_string = NULL;
200 /* PIDs of special child processes; 0 when not running */
201 static pid_t StartupPID = 0,
207 /* Startup/shutdown state */
209 #define SmartShutdown 1
210 #define FastShutdown 2
212 static int Shutdown = NoShutdown;
214 static bool FatalError = false; /* T if recovering from backend crash */
216 bool ClientAuthInProgress = false; /* T during new-client
220 * State for assigning random salts and cancel keys.
221 * Also, the global MyCancelKey passes the cancel key assigned to a given
222 * backend from the postmaster to that backend (via fork).
224 static unsigned int random_seed = 0;
230 #ifdef HAVE_INT_OPTRESET
235 * postmaster.c - function prototypes
237 static void checkDataDir(void);
239 #ifdef USE_RENDEZVOUS
240 static void reg_reply(DNSServiceRegistrationReplyErrorType errorCode,
243 static void pmdaemonize(void);
244 static Port *ConnCreate(int serverFd);
245 static void ConnFree(Port *port);
246 static void reset_shared(unsigned short port);
247 static void SIGHUP_handler(SIGNAL_ARGS);
248 static void pmdie(SIGNAL_ARGS);
249 static void reaper(SIGNAL_ARGS);
250 static void sigusr1_handler(SIGNAL_ARGS);
251 static void dummy_handler(SIGNAL_ARGS);
252 static void CleanupBackend(int pid, int exitstatus);
253 static void HandleChildCrash(int pid, int exitstatus, const char *procname);
254 static void LogChildExit(int lev, const char *procname,
255 int pid, int exitstatus);
256 static int BackendRun(Port *port);
257 static void ExitPostmaster(int status);
258 static void usage(const char *);
259 static int ServerLoop(void);
260 static int BackendStartup(Port *port);
261 static int ProcessStartupPacket(Port *port, bool SSLdone);
262 static void processCancelRequest(Port *port, void *pkt);
263 static int initMasks(fd_set *rmask);
264 static void report_fork_failure_to_client(Port *port, int errnum);
265 static enum CAC_state canAcceptConnections(void);
266 static long PostmasterRandom(void);
267 static void RandomSalt(char *cryptSalt, char *md5Salt);
268 static void SignalChildren(int signal);
269 static int CountChildren(void);
270 static bool CreateOptsFile(int argc, char *argv[], char *fullprogname);
271 static pid_t StartChildProcess(int xlop);
276 static pid_t win32_forkexec(const char *path, char *argv[]);
277 static void win32_AddChild(pid_t pid, HANDLE handle);
278 static void win32_RemoveChild(pid_t pid);
279 static pid_t win32_waitpid(int *exitstatus);
280 static DWORD WINAPI win32_sigchld_waiter(LPVOID param);
282 static pid_t *win32_childPIDArray;
283 static HANDLE *win32_childHNDArray;
284 static unsigned long win32_numChildren = 0;
286 HANDLE PostmasterHandle;
289 static pid_t backend_forkexec(Port *port);
290 static pid_t internal_forkexec(int argc, char *argv[], Port *port);
292 static void read_backend_variables(char *filename, Port *port);
293 static bool write_backend_variables(char *filename, Port *port);
295 static void ShmemBackendArrayAdd(Backend *bn);
296 static void ShmemBackendArrayRemove(pid_t pid);
297 #endif /* EXEC_BACKEND */
299 #define StartupDataBase() StartChildProcess(BS_XLOG_STARTUP)
300 #define StartBackgroundWriter() StartChildProcess(BS_XLOG_BGWRITER)
304 * Postmaster main entry point
307 PostmasterMain(int argc, char *argv[])
311 char *userDoption = NULL;
314 /* This will call exit() if strdup() fails. */
315 progname = get_progname(argv[0]);
317 MyProcPid = PostmasterPid = getpid();
319 IsPostmasterEnvironment = true;
322 * Catch standard options before doing much else. This even works on
323 * systems without getopt_long.
327 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
332 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
334 puts("postmaster (PostgreSQL) " PG_VERSION);
340 * for security, no dir or file created can be group or other
343 umask((mode_t) 0077);
346 * Fire up essential subsystems: memory management
351 * By default, palloc() requests in the postmaster will be allocated
352 * in the PostmasterContext, which is space that can be recycled by
353 * backends. Allocated data that needs to be available to backends
354 * should be allocated in TopMemoryContext.
356 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
358 ALLOCSET_DEFAULT_MINSIZE,
359 ALLOCSET_DEFAULT_INITSIZE,
360 ALLOCSET_DEFAULT_MAXSIZE);
361 MemoryContextSwitchTo(PostmasterContext);
363 IgnoreSystemIndexes(false);
365 if (find_my_exec(argv[0], my_exec_path) < 0)
366 elog(FATAL, "%s: could not locate my own executable path",
369 get_pkglib_path(my_exec_path, pkglib_path);
374 InitializeGUCOptions();
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. */
399 userDoption = optarg;
402 set_debug_options(atoi(optarg), PGC_POSTMASTER, PGC_S_ARGV);
405 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
408 SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
411 SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
414 SetConfigOption("unix_socket_directory", optarg, PGC_POSTMASTER, PGC_S_ARGV);
418 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
422 /* Multiplexed backends no longer supported. */
427 * ignore this flag. This may be passed in because the
428 * program was run as 'postgres -M' instead of
433 /* The max number of backends to start. */
434 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
437 /* Don't reinit shared mem after abnormal exit */
443 * Other options to pass to the backend on the command
446 snprintf(ExtraOptions + strlen(ExtraOptions),
447 sizeof(ExtraOptions) - strlen(ExtraOptions),
451 SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
456 * Start in 'S'ilent mode (disassociate from controlling
457 * tty). You may also think of this as 'S'ysV mode since
458 * it's most badly needed on SysV-derived systems like
461 SetConfigOption("silent_mode", "true", PGC_POSTMASTER, PGC_S_ARGV);
466 * In the event that some backend dumps core, send
467 * SIGSTOP, rather than SIGQUIT, to all its peers. This
468 * lets the wily post_hacker collect core dumps from
479 ParseLongOption(optarg, &name, &value);
484 (errcode(ERRCODE_SYNTAX_ERROR),
485 errmsg("--%s requires a value",
489 (errcode(ERRCODE_SYNTAX_ERROR),
490 errmsg("-c %s requires a value",
494 SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
502 write_stderr("Try \"%s --help\" for more information.\n",
509 * Postmaster accepts no non-option switch arguments.
513 write_stderr("%s: invalid argument: \"%s\"\n",
514 progname, argv[optind]);
515 write_stderr("Try \"%s --help\" for more information.\n",
521 * Locate the proper configuration files and data directory, and
522 * read postgresql.conf for the first time.
524 if (!SelectConfigFiles(userDoption, progname))
527 /* Verify that DataDir looks reasonable */
531 * Check for invalid combinations of GUC settings.
533 if (NBuffers < 2 * MaxBackends || NBuffers < 16)
536 * Do not accept -B so small that backends are likely to starve
537 * for lack of buffers. The specific choices here are somewhat
540 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);
544 if (ReservedBackends >= MaxBackends)
546 write_stderr("%s: superuser_reserved_connections must be less than max_connections\n", progname);
551 * Other one-time internal sanity checks can go here.
553 if (!CheckDateTokenTables())
555 write_stderr("%s: invalid datetoken tables, please fix\n", progname);
560 * Now that we are done processing the postmaster arguments, reset
561 * getopt(3) library so that it will work correctly in subprocesses.
564 #ifdef HAVE_INT_OPTRESET
565 optreset = 1; /* some systems need this too */
568 /* For debugging: display postmaster environment */
570 extern char **environ;
574 (errmsg_internal("%s: PostmasterMain: initial environ dump:",
577 (errmsg_internal("-----------------------------------------")));
578 for (p = environ; *p; ++p)
580 (errmsg_internal("\t%s", *p)));
582 (errmsg_internal("-----------------------------------------")));
586 if (find_other_exec(argv[0], "postgres", PG_VERSIONSTR,
587 postgres_exec_path) < 0)
589 (errmsg("%s: could not locate matching postgres executable",
594 * Initialize SSL library, if specified.
602 * process any libraries that should be preloaded and optionally
605 if (preload_libraries_string)
606 process_preload_libraries(preload_libraries_string);
609 * Fork away from controlling terminal, if -S specified.
611 * Must do this before we grab any interlock files, else the interlocks
612 * will show the wrong PID.
618 * Create lockfile for data directory.
620 * We want to do this before we try to grab the input sockets, because
621 * the data directory interlock is more reliable than the socket-file
622 * interlock (thanks to whoever decided to put socket files in /tmp
623 * :-(). For the same reason, it's best to grab the TCP socket(s)
624 * before the Unix socket.
626 CreateDataDirLockFile(DataDir, true);
629 * Remove old temporary files. At this point there can be no other
630 * Postgres processes running in this directory, so this should be
636 * Establish input sockets.
638 for (i = 0; i < MAXLISTEN; i++)
639 ListenSocket[i] = -1;
647 /* Need a modifiable copy of ListenAddresses */
648 rawstring = pstrdup(ListenAddresses);
650 /* Parse string into list of identifiers */
651 if (!SplitIdentifierString(rawstring, ',', &elemlist))
653 /* syntax error in list */
655 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
656 errmsg("invalid list syntax for \"listen_addresses\"")));
661 char *curhost = (char *) lfirst(l);
663 if (strcmp(curhost, "*") == 0)
664 status = StreamServerPort(AF_UNSPEC, NULL,
665 (unsigned short) PostPortNumber,
667 ListenSocket, MAXLISTEN);
669 status = StreamServerPort(AF_UNSPEC, curhost,
670 (unsigned short) PostPortNumber,
672 ListenSocket, MAXLISTEN);
673 if (status != STATUS_OK)
675 (errmsg("could not create listen socket for \"%s\"",
683 #ifdef USE_RENDEZVOUS
684 /* Register for Rendezvous only if we opened TCP socket(s) */
685 if (ListenSocket[0] != -1 && rendezvous_name != NULL)
687 DNSServiceRegistrationCreate(rendezvous_name,
690 htonl(PostPortNumber),
692 (DNSServiceRegistrationReply) reg_reply,
697 #ifdef HAVE_UNIX_SOCKETS
698 status = StreamServerPort(AF_UNIX, NULL,
699 (unsigned short) PostPortNumber,
701 ListenSocket, MAXLISTEN);
702 if (status != STATUS_OK)
704 (errmsg("could not create Unix-domain socket")));
708 * check that we have some socket to listen on
710 if (ListenSocket[0] == -1)
712 (errmsg("no socket created for listening")));
717 * Set up shared memory and semaphores.
719 reset_shared(PostPortNumber);
722 * Estimate number of openable files. This must happen after setting
723 * up semaphores, because on some platforms semaphores count as open
729 * Initialize the list of active backends.
731 BackendList = DLNewList();
736 * Initialize the child pid/HANDLE arrays for signal handling.
738 win32_childPIDArray = (pid_t *)
739 malloc(NUM_BACKENDARRAY_ELEMS * sizeof(pid_t));
740 win32_childHNDArray = (HANDLE *)
741 malloc(NUM_BACKENDARRAY_ELEMS * sizeof(HANDLE));
742 if (!win32_childPIDArray || !win32_childHNDArray)
744 (errcode(ERRCODE_OUT_OF_MEMORY),
745 errmsg("out of memory")));
748 * Set up a handle that child processes can use to check whether the
749 * postmaster is still running.
751 if (DuplicateHandle(GetCurrentProcess(),
757 DUPLICATE_SAME_ACCESS) == 0)
759 (errmsg_internal("could not duplicate postmaster handle: %d",
760 (int) GetLastError())));
764 * Record postmaster options. We delay this till now to avoid
765 * recording bogus options (eg, NBuffers too high for available
768 if (!CreateOptsFile(argc, argv, my_exec_path))
772 write_nondefault_variables(PGC_POSTMASTER);
776 * Write the external PID file if requested
778 if (external_pid_file)
780 FILE *fpidfile = fopen(external_pid_file, "w");
784 fprintf(fpidfile, "%d\n", MyProcPid);
786 /* Should we remove the pid file on postmaster exit? */
789 write_stderr("%s: could not write external PID file \"%s\": %s\n",
790 progname, external_pid_file, strerror(errno));
794 * Set up signal handlers for the postmaster process.
796 * CAUTION: when changing this list, check for side-effects on the signal
797 * handling setup of child processes. See tcop/postgres.c,
798 * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/pgarch.c,
799 * postmaster/pgstat.c, and postmaster/syslogger.c.
802 PG_SETMASK(&BlockSig);
804 pqsignal(SIGHUP, SIGHUP_handler); /* reread config file and have
805 * children do same */
806 pqsignal(SIGINT, pmdie); /* send SIGTERM and shut down */
807 pqsignal(SIGQUIT, pmdie); /* send SIGQUIT and die */
808 pqsignal(SIGTERM, pmdie); /* wait for children and shut down */
809 pqsignal(SIGALRM, SIG_IGN); /* ignored */
810 pqsignal(SIGPIPE, SIG_IGN); /* ignored */
811 pqsignal(SIGUSR1, sigusr1_handler); /* message from child process */
812 pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
813 pqsignal(SIGCHLD, reaper); /* handle child termination */
814 pqsignal(SIGTTIN, SIG_IGN); /* ignored */
815 pqsignal(SIGTTOU, SIG_IGN); /* ignored */
816 /* ignore SIGXFSZ, so that ulimit violations work like disk full */
818 pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
822 * If enabled, start up syslogger collection subprocess
824 SysLoggerPID = SysLogger_Start();
827 * Reset whereToSendOutput from Debug (its starting state) to None.
828 * This stops ereport from sending log messages to stderr unless
829 * Log_destination permits. We don't do this until the postmaster is
830 * fully launched, since startup failures may as well be reported to
833 whereToSendOutput = None;
836 * Initialize the statistics collector stuff
841 * Load cached files for client authentication.
849 * We're ready to rock and roll...
851 StartupPID = StartupDataBase();
853 status = ServerLoop();
856 * ServerLoop probably shouldn't ever return, but if it does, close
859 ExitPostmaster(status != STATUS_OK);
861 return 0; /* not reached */
866 * Validate the proposed data directory
871 char path[MAXPGPATH];
873 struct stat stat_buf;
877 if (stat(DataDir, &stat_buf) != 0)
881 (errcode_for_file_access(),
882 errmsg("data directory \"%s\" does not exist",
886 (errcode_for_file_access(),
887 errmsg("could not read permissions of directory \"%s\": %m",
892 * Check if the directory has group or world access. If so, reject.
894 * XXX temporarily suppress check when on Windows, because there may not
895 * be proper support for Unix-y file permissions. Need to think of a
896 * reasonable check to apply on Windows.
898 #if !defined(WIN32) && !defined(__CYGWIN__)
899 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
901 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
902 errmsg("data directory \"%s\" has group or world access",
904 errdetail("Permissions should be u=rwx (0700).")));
907 /* Look for PG_VERSION before looking for pg_control */
908 ValidatePgVersion(DataDir);
910 snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
912 fp = AllocateFile(path, PG_BINARY_R);
915 write_stderr("%s: could not find the database system\n"
916 "Expected to find it in the directory \"%s\",\n"
917 "but could not open file \"%s\": %s\n",
918 progname, DataDir, path, strerror(errno));
925 #ifdef USE_RENDEZVOUS
928 * empty callback function for DNSServiceRegistrationCreate()
931 reg_reply(DNSServiceRegistrationReplyErrorType errorCode, void *context)
935 #endif /* USE_RENDEZVOUS */
939 * Fork away from the controlling terminal (-S option)
949 struct itimerval prof_itimer;
953 /* see comments in BackendStartup */
954 getitimer(ITIMER_PROF, &prof_itimer);
958 if (pid == (pid_t) -1)
960 write_stderr("%s: could not fork background process: %s\n",
961 progname, strerror(errno));
966 /* Parent should just exit, without doing any atexit cleanup */
971 setitimer(ITIMER_PROF, &prof_itimer, NULL);
974 MyProcPid = PostmasterPid = getpid(); /* reset PID vars to child */
976 /* GH: If there's no setsid(), we hopefully don't need silent mode.
977 * Until there's a better solution.
982 write_stderr("%s: could not dissociate from controlling TTY: %s\n",
983 progname, strerror(errno));
987 i = open(NULL_DEV, O_RDWR);
994 elog(FATAL, "SilentMode not supported under WIN32");
1000 * Print out help message
1003 usage(const char *progname)
1005 printf(gettext("%s is the PostgreSQL server.\n\n"), progname);
1006 printf(gettext("Usage:\n %s [OPTION]...\n\n"), progname);
1007 printf(gettext("Options:\n"));
1008 #ifdef USE_ASSERT_CHECKING
1009 printf(gettext(" -A 1|0 enable/disable run-time assert checking\n"));
1011 printf(gettext(" -B NBUFFERS number of shared buffers\n"));
1012 printf(gettext(" -c NAME=VALUE set run-time parameter\n"));
1013 printf(gettext(" -d 1-5 debugging level\n"));
1014 printf(gettext(" -D DATADIR database directory\n"));
1015 printf(gettext(" -F turn fsync off\n"));
1016 printf(gettext(" -h HOSTNAME host name or IP address to listen on\n"));
1017 printf(gettext(" -i enable TCP/IP connections\n"));
1018 printf(gettext(" -k DIRECTORY Unix-domain socket location\n"));
1020 printf(gettext(" -l enable SSL connections\n"));
1022 printf(gettext(" -N MAX-CONNECT maximum number of allowed connections\n"));
1023 printf(gettext(" -o OPTIONS pass \"OPTIONS\" to each server process\n"));
1024 printf(gettext(" -p PORT port number to listen on\n"));
1025 printf(gettext(" -S silent mode (start in background without logging output)\n"));
1026 printf(gettext(" --help show this help, then exit\n"));
1027 printf(gettext(" --version output version information, then exit\n"));
1029 printf(gettext("\nDeveloper options:\n"));
1030 printf(gettext(" -n do not reinitialize shared memory after abnormal exit\n"));
1031 printf(gettext(" -s send SIGSTOP to all backend servers if one dies\n"));
1033 printf(gettext("\nPlease read the documentation for the complete list of run-time\n"
1034 "configuration settings and how to set them on the command line or in\n"
1035 "the configuration file.\n\n"
1036 "Report bugs to <pgsql-bugs@postgresql.org>.\n"));
1041 * Main idle loop of postmaster
1050 struct timeval earlier,
1054 gettimeofday(&earlier, &tz);
1055 last_touch_time = time(NULL);
1057 nSockets = initMasks(&readmask);
1063 struct timeval timeout;
1068 * Wait for something to happen.
1070 * We wait at most one minute, to ensure that the other background
1071 * tasks handled below get done even when no requests are
1074 memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
1076 timeout.tv_sec = 60;
1077 timeout.tv_usec = 0;
1079 PG_SETMASK(&UnBlockSig);
1081 selres = select(nSockets, &rmask, NULL, NULL, &timeout);
1084 * Block all signals until we wait again. (This makes it safe for
1085 * our signal handlers to do nontrivial work.)
1087 PG_SETMASK(&BlockSig);
1091 if (errno != EINTR && errno != EWOULDBLOCK)
1094 (errcode_for_socket_access(),
1095 errmsg("select() failed in postmaster: %m")));
1096 return STATUS_ERROR;
1101 * New connection pending on any of our sockets? If so, fork a
1102 * child process to deal with it.
1107 * Select a random seed at the time of first receiving a
1110 while (random_seed == 0)
1112 gettimeofday(&later, &tz);
1115 * We are not sure how much precision is in tv_usec, so we
1116 * swap the high and low 16 bits of 'later' and XOR them with
1117 * 'earlier'. On the off chance that the result is 0, we
1118 * loop until it isn't.
1120 random_seed = earlier.tv_usec ^
1121 ((later.tv_usec << 16) |
1122 ((later.tv_usec >> 16) & 0xffff));
1125 for (i = 0; i < MAXLISTEN; i++)
1127 if (ListenSocket[i] == -1)
1129 if (FD_ISSET(ListenSocket[i], &rmask))
1131 port = ConnCreate(ListenSocket[i]);
1134 BackendStartup(port);
1137 * We no longer need the open socket or port
1138 * structure in this process
1140 StreamClose(port->sock);
1147 /* If we have lost the system logger, try to start a new one */
1148 if (SysLoggerPID == 0 && Redirect_stderr)
1149 SysLoggerPID = SysLogger_Start();
1152 * If no background writer process is running, and we are not in a
1153 * state that prevents it, start one. It doesn't matter if this
1154 * fails, we'll just try again later.
1156 if (BgWriterPID == 0 && StartupPID == 0 && !FatalError)
1158 BgWriterPID = StartBackgroundWriter();
1159 /* If shutdown is pending, set it going */
1160 if (Shutdown > NoShutdown && BgWriterPID != 0)
1161 kill(BgWriterPID, SIGUSR2);
1164 /* If we have lost the archiver, try to start a new one */
1165 if (XLogArchivingActive() && PgArchPID == 0 &&
1166 StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
1167 PgArchPID = pgarch_start();
1169 /* If we have lost the stats collector, try to start a new one */
1170 if (PgStatPID == 0 &&
1171 StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
1172 PgStatPID = pgstat_start();
1175 * Touch the socket and lock file at least every ten minutes, to
1176 * ensure that they are not removed by overzealous /tmp-cleaning
1180 if (now - last_touch_time >= 10 * 60)
1183 TouchSocketLockFile();
1184 last_touch_time = now;
1191 * Initialise the masks for select() for the ports we are listening on.
1192 * Return the number of sockets to listen on.
1195 initMasks(fd_set *rmask)
1202 for (i = 0; i < MAXLISTEN; i++)
1204 int fd = ListenSocket[i];
1218 * Read the startup packet and do something according to it.
1220 * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
1221 * not return at all.
1223 * (Note that ereport(FATAL) stuff is sent to the client, so only use it
1224 * if that's what you want. Return STATUS_ERROR if you don't want to
1225 * send anything to the client, which would typically be appropriate
1226 * if we detect a communications failure.)
1229 ProcessStartupPacket(Port *port, bool SSLdone)
1233 ProtocolVersion proto;
1234 MemoryContext oldcontext;
1236 if (pq_getbytes((char *) &len, 4) == EOF)
1239 * EOF after SSLdone probably means the client didn't like our
1240 * response to NEGOTIATE_SSL_CODE. That's not an error condition,
1241 * so don't clutter the log with a complaint.
1245 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1246 errmsg("incomplete startup packet")));
1247 return STATUS_ERROR;
1253 if (len < (int32) sizeof(ProtocolVersion) ||
1254 len > MAX_STARTUP_PACKET_LENGTH)
1257 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1258 errmsg("invalid length of startup packet")));
1259 return STATUS_ERROR;
1263 * Allocate at least the size of an old-style startup packet, plus one
1264 * extra byte, and make sure all are zeroes. This ensures we will
1265 * have null termination of all strings, in both fixed- and
1266 * variable-length packet layouts.
1268 if (len <= (int32) sizeof(StartupPacket))
1269 buf = palloc0(sizeof(StartupPacket) + 1);
1271 buf = palloc0(len + 1);
1273 if (pq_getbytes(buf, len) == EOF)
1276 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1277 errmsg("incomplete startup packet")));
1278 return STATUS_ERROR;
1282 * The first field is either a protocol version number or a special
1285 port->proto = proto = ntohl(*((ProtocolVersion *) buf));
1287 if (proto == CANCEL_REQUEST_CODE)
1289 processCancelRequest(port, buf);
1290 return 127; /* XXX */
1293 if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
1298 /* No SSL when disabled or on Unix sockets */
1299 if (!EnableSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
1302 SSLok = 'S'; /* Support for SSL */
1304 SSLok = 'N'; /* No support for SSL */
1306 if (send(port->sock, &SSLok, 1, 0) != 1)
1309 (errcode_for_socket_access(),
1310 errmsg("failed to send SSL negotiation response: %m")));
1311 return STATUS_ERROR; /* close the connection */
1315 if (SSLok == 'S' && secure_open_server(port) == -1)
1316 return STATUS_ERROR;
1318 /* regular startup packet, cancel, etc packet should follow... */
1319 /* but not another SSL negotiation request */
1320 return ProcessStartupPacket(port, true);
1323 /* Could add additional special packet types here */
1326 * Set FrontendProtocol now so that ereport() knows what format to
1327 * send if we fail during startup.
1329 FrontendProtocol = proto;
1331 /* Check we can handle the protocol the frontend is using. */
1333 if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
1334 PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
1335 (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
1336 PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
1338 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1339 errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
1340 PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
1341 PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST),
1342 PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST),
1343 PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))));
1346 * Now fetch parameters out of startup packet and save them into the
1347 * Port structure. All data structures attached to the Port struct
1348 * must be allocated in TopMemoryContext so that they won't disappear
1349 * when we pass them to PostgresMain (see BackendRun). We need not
1350 * worry about leaking this storage on failure, since we aren't in the
1351 * postmaster process anymore.
1353 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1355 if (PG_PROTOCOL_MAJOR(proto) >= 3)
1357 int32 offset = sizeof(ProtocolVersion);
1360 * Scan packet body for name/option pairs. We can assume any
1361 * string beginning within the packet body is null-terminated,
1362 * thanks to zeroing extra byte above.
1364 port->guc_options = NIL;
1366 while (offset < len)
1368 char *nameptr = ((char *) buf) + offset;
1372 if (*nameptr == '\0')
1373 break; /* found packet terminator */
1374 valoffset = offset + strlen(nameptr) + 1;
1375 if (valoffset >= len)
1376 break; /* missing value, will complain below */
1377 valptr = ((char *) buf) + valoffset;
1379 if (strcmp(nameptr, "database") == 0)
1380 port->database_name = pstrdup(valptr);
1381 else if (strcmp(nameptr, "user") == 0)
1382 port->user_name = pstrdup(valptr);
1383 else if (strcmp(nameptr, "options") == 0)
1384 port->cmdline_options = pstrdup(valptr);
1387 /* Assume it's a generic GUC option */
1388 port->guc_options = lappend(port->guc_options,
1390 port->guc_options = lappend(port->guc_options,
1393 offset = valoffset + strlen(valptr) + 1;
1397 * If we didn't find a packet terminator exactly at the end of the
1398 * given packet length, complain.
1400 if (offset != len - 1)
1402 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1403 errmsg("invalid startup packet layout: expected terminator as last byte")));
1408 * Get the parameters from the old-style, fixed-width-fields
1409 * startup packet as C strings. The packet destination was
1410 * cleared first so a short packet has zeros silently added. We
1411 * have to be prepared to truncate the pstrdup result for oversize
1414 StartupPacket *packet = (StartupPacket *) buf;
1416 port->database_name = pstrdup(packet->database);
1417 if (strlen(port->database_name) > sizeof(packet->database))
1418 port->database_name[sizeof(packet->database)] = '\0';
1419 port->user_name = pstrdup(packet->user);
1420 if (strlen(port->user_name) > sizeof(packet->user))
1421 port->user_name[sizeof(packet->user)] = '\0';
1422 port->cmdline_options = pstrdup(packet->options);
1423 if (strlen(port->cmdline_options) > sizeof(packet->options))
1424 port->cmdline_options[sizeof(packet->options)] = '\0';
1425 port->guc_options = NIL;
1428 /* Check a user name was given. */
1429 if (port->user_name == NULL || port->user_name[0] == '\0')
1431 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1432 errmsg("no PostgreSQL user name specified in startup packet")));
1434 /* The database defaults to the user name. */
1435 if (port->database_name == NULL || port->database_name[0] == '\0')
1436 port->database_name = pstrdup(port->user_name);
1438 if (Db_user_namespace)
1441 * If user@, it is a global user, remove '@'. We only want to do
1442 * this if there is an '@' at the end and no earlier in the user
1443 * string or they may fake as a local user of another database
1444 * attaching to this database.
1446 if (strchr(port->user_name, '@') ==
1447 port->user_name + strlen(port->user_name) - 1)
1448 *strchr(port->user_name, '@') = '\0';
1451 /* Append '@' and dbname */
1454 db_user = palloc(strlen(port->user_name) +
1455 strlen(port->database_name) + 2);
1456 sprintf(db_user, "%s@%s", port->user_name, port->database_name);
1457 port->user_name = db_user;
1462 * Truncate given database and user names to length of a Postgres
1463 * name. This avoids lookup failures when overlength names are given.
1465 if (strlen(port->database_name) >= NAMEDATALEN)
1466 port->database_name[NAMEDATALEN - 1] = '\0';
1467 if (strlen(port->user_name) >= NAMEDATALEN)
1468 port->user_name[NAMEDATALEN - 1] = '\0';
1471 * Done putting stuff in TopMemoryContext.
1473 MemoryContextSwitchTo(oldcontext);
1476 * If we're going to reject the connection due to database state, say
1477 * so now instead of wasting cycles on an authentication exchange.
1478 * (This also allows a pg_ping utility to be written.)
1480 switch (port->canAcceptConnections)
1484 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1485 errmsg("the database system is starting up")));
1489 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1490 errmsg("the database system is shutting down")));
1494 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1495 errmsg("the database system is in recovery mode")));
1499 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
1500 errmsg("sorry, too many clients already")));
1512 * The client has sent a cancel request packet, not a normal
1513 * start-a-new-connection packet. Perform the necessary processing.
1514 * Nothing is sent back to the client.
1517 processCancelRequest(Port *port, void *pkt)
1519 CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
1521 long cancelAuthCode;
1524 #ifndef EXEC_BACKEND
1531 backendPID = (int) ntohl(canc->backendPID);
1532 cancelAuthCode = (long) ntohl(canc->cancelAuthCode);
1535 * See if we have a matching backend. In the EXEC_BACKEND case, we
1536 * can no longer access the postmaster's own backend list, and must
1537 * rely on the duplicate array in shared memory.
1539 #ifndef EXEC_BACKEND
1540 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
1542 bp = (Backend *) DLE_VAL(curr);
1544 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
1546 bp = (Backend *) &ShmemBackendArray[i];
1548 if (bp->pid == backendPID)
1550 if (bp->cancel_key == cancelAuthCode)
1552 /* Found a match; signal that backend to cancel current op */
1554 (errmsg_internal("processing cancel request: sending SIGINT to process %d",
1556 kill(bp->pid, SIGINT);
1559 /* Right PID, wrong key: no way, Jose */
1561 (errmsg_internal("bad key in cancel request for process %d",
1567 /* No matching backend */
1569 (errmsg_internal("bad pid in cancel request for process %d",
1574 * canAcceptConnections --- check to see if database state allows connections.
1576 static enum CAC_state
1577 canAcceptConnections(void)
1579 /* Can't start backends when in startup/shutdown/recovery state. */
1580 if (Shutdown > NoShutdown)
1581 return CAC_SHUTDOWN;
1585 return CAC_RECOVERY;
1588 * Don't start too many children.
1590 * We allow more connections than we can have backends here because some
1591 * might still be authenticating; they might fail auth, or some
1592 * existing backend might exit before the auth cycle is completed. The
1593 * exact MaxBackends limit is enforced when a new backend tries to
1594 * join the shared-inval backend array.
1596 if (CountChildren() >= 2 * MaxBackends)
1604 * ConnCreate -- create a local connection data structure
1607 ConnCreate(int serverFd)
1611 if (!(port = (Port *) calloc(1, sizeof(Port))))
1614 (errcode(ERRCODE_OUT_OF_MEMORY),
1615 errmsg("out of memory")));
1619 if (StreamConnection(serverFd, port) != STATUS_OK)
1621 StreamClose(port->sock);
1628 * Precompute password salt values to use for this connection.
1629 * It's slightly annoying to do this long in advance of knowing
1630 * whether we'll need 'em or not, but we must do the random()
1631 * calls before we fork, not after. Else the postmaster's random
1632 * sequence won't get advanced, and all backends would end up
1633 * using the same salt...
1635 RandomSalt(port->cryptSalt, port->md5Salt);
1643 * ConnFree -- free a local connection data structure
1646 ConnFree(Port *conn)
1656 * ClosePostmasterPorts -- close all the postmaster's open sockets
1658 * This is called during child process startup to release file descriptors
1659 * that are not needed by that child process. The postmaster still has
1660 * them open, of course.
1662 * Note: we pass am_syslogger as a boolean because we don't want to set
1663 * the global variable yet when this is called.
1666 ClosePostmasterPorts(bool am_syslogger)
1670 /* Close the listen sockets */
1671 for (i = 0; i < MAXLISTEN; i++)
1673 if (ListenSocket[i] != -1)
1675 StreamClose(ListenSocket[i]);
1676 ListenSocket[i] = -1;
1680 /* If using syslogger, close the read side of the pipe */
1684 if (syslogPipe[0] >= 0)
1685 close(syslogPipe[0]);
1689 CloseHandle(syslogPipe[0]);
1697 * reset_shared -- reset shared memory and semaphores
1700 reset_shared(unsigned short port)
1703 * Create or re-create shared memory and semaphores.
1705 * Note: in each "cycle of life" we will normally assign the same IPC
1706 * keys (if using SysV shmem and/or semas), since the port number is
1707 * used to determine IPC keys. This helps ensure that we will clean
1708 * up dead IPC objects if the postmaster crashes and is restarted.
1710 CreateSharedMemoryAndSemaphores(false, MaxBackends, port);
1715 * SIGHUP -- reread config files, and tell children to do same
1718 SIGHUP_handler(SIGNAL_ARGS)
1720 int save_errno = errno;
1722 PG_SETMASK(&BlockSig);
1724 if (Shutdown <= SmartShutdown)
1727 (errmsg("received SIGHUP, reloading configuration files")));
1728 ProcessConfigFile(PGC_SIGHUP);
1729 SignalChildren(SIGHUP);
1730 if (BgWriterPID != 0)
1731 kill(BgWriterPID, SIGHUP);
1733 kill(PgArchPID, SIGHUP);
1734 if (SysLoggerPID != 0)
1735 kill(SysLoggerPID, SIGHUP);
1736 /* PgStatPID does not currently need SIGHUP */
1741 /* Update the starting-point file for future children */
1742 write_nondefault_variables(PGC_SIGHUP);
1746 PG_SETMASK(&UnBlockSig);
1753 * pmdie -- signal handler for processing various postmaster signals.
1758 int save_errno = errno;
1760 PG_SETMASK(&BlockSig);
1763 (errmsg_internal("postmaster received signal %d",
1764 postgres_signal_arg)));
1766 switch (postgres_signal_arg)
1773 * Wait for children to end their work, then shut down.
1775 if (Shutdown >= SmartShutdown)
1777 Shutdown = SmartShutdown;
1779 (errmsg("received smart shutdown request")));
1781 if (DLGetHead(BackendList))
1782 break; /* let reaper() handle this */
1785 * No children left. Begin shutdown of data base system.
1787 if (StartupPID != 0 || FatalError)
1788 break; /* let reaper() handle this */
1789 /* Start the bgwriter if not running */
1790 if (BgWriterPID == 0)
1791 BgWriterPID = StartBackgroundWriter();
1792 /* And tell it to shut down */
1793 if (BgWriterPID != 0)
1794 kill(BgWriterPID, SIGUSR2);
1795 /* Tell pgarch to shut down too; nothing left for it to do */
1797 kill(PgArchPID, SIGQUIT);
1798 /* Tell pgstat to shut down too; nothing left for it to do */
1800 kill(PgStatPID, SIGQUIT);
1808 * Abort all children with SIGTERM (rollback active transactions
1809 * and exit) and shut down when they are gone.
1811 if (Shutdown >= FastShutdown)
1813 Shutdown = FastShutdown;
1815 (errmsg("received fast shutdown request")));
1817 if (DLGetHead(BackendList))
1822 (errmsg("aborting any active transactions")));
1823 SignalChildren(SIGTERM);
1824 /* reaper() does the rest */
1830 * No children left. Begin shutdown of data base system.
1832 * Note: if we previously got SIGTERM then we may send SIGUSR2 to
1833 * the bgwriter a second time here. This should be harmless.
1835 if (StartupPID != 0 || FatalError)
1836 break; /* let reaper() handle this */
1837 /* Start the bgwriter if not running */
1838 if (BgWriterPID == 0)
1839 BgWriterPID = StartBackgroundWriter();
1840 /* And tell it to shut down */
1841 if (BgWriterPID != 0)
1842 kill(BgWriterPID, SIGUSR2);
1843 /* Tell pgarch to shut down too; nothing left for it to do */
1845 kill(PgArchPID, SIGQUIT);
1846 /* Tell pgstat to shut down too; nothing left for it to do */
1848 kill(PgStatPID, SIGQUIT);
1854 * Immediate Shutdown:
1856 * abort all children with SIGQUIT and exit without attempt to
1857 * properly shut down data base system.
1860 (errmsg("received immediate shutdown request")));
1861 if (StartupPID != 0)
1862 kill(StartupPID, SIGQUIT);
1863 if (BgWriterPID != 0)
1864 kill(BgWriterPID, SIGQUIT);
1866 kill(PgArchPID, SIGQUIT);
1868 kill(PgStatPID, SIGQUIT);
1869 if (DLGetHead(BackendList))
1870 SignalChildren(SIGQUIT);
1875 PG_SETMASK(&UnBlockSig);
1881 * Reaper -- signal handler to cleanup after a backend (child) dies.
1886 int save_errno = errno;
1889 int status; /* backend exit status */
1893 union wait status; /* backend exit status */
1897 int pid; /* process id of dead backend */
1899 PG_SETMASK(&BlockSig);
1902 (errmsg_internal("reaping dead processes")));
1904 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1906 exitstatus = status;
1909 while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
1911 exitstatus = status.w_status;
1913 while ((pid = win32_waitpid(&exitstatus)) > 0)
1916 * We need to do this here, and not in CleanupBackend, since this
1917 * is to be called on all children when we are done with them.
1918 * Could move to LogChildExit, but that seems like asking for
1921 win32_RemoveChild(pid);
1923 #endif /* HAVE_WAITPID */
1926 * Check if this child was a startup process.
1928 if (StartupPID != 0 && pid == StartupPID)
1931 if (exitstatus != 0)
1933 LogChildExit(LOG, gettext("startup process"),
1936 (errmsg("aborting startup due to startup process failure")));
1941 * Startup succeeded - we are done with system startup or
1947 * Crank up the background writer. It doesn't matter if this
1948 * fails, we'll just try again later.
1950 Assert(BgWriterPID == 0);
1951 BgWriterPID = StartBackgroundWriter();
1954 * Go to shutdown mode if a shutdown request was pending.
1955 * Otherwise, try to start the archiver and stats collector
1958 if (Shutdown > NoShutdown && BgWriterPID != 0)
1959 kill(BgWriterPID, SIGUSR2);
1960 else if (Shutdown == NoShutdown)
1962 if (XLogArchivingActive() && PgArchPID == 0)
1963 PgArchPID = pgarch_start();
1965 PgStatPID = pgstat_start();
1972 * Was it the bgwriter?
1974 if (BgWriterPID != 0 && pid == BgWriterPID)
1977 if (exitstatus == 0 && Shutdown > NoShutdown &&
1978 !FatalError && !DLGetHead(BackendList))
1981 * Normal postmaster exit is here: we've seen normal exit
1982 * of the bgwriter after it's been told to shut down. We
1983 * expect that it wrote a shutdown checkpoint. (If for
1984 * some reason it didn't, recovery will occur on next
1985 * postmaster start.)
1987 * Note: we do not wait around for exit of the archiver or
1988 * stats processes. They've been sent SIGQUIT by this
1989 * point, and in any case contain logic to commit
1990 * hara-kiri if they notice the postmaster is gone.
1996 * Any unexpected exit of the bgwriter is treated as a crash.
1998 HandleChildCrash(pid, exitstatus,
1999 gettext("background writer process"));
2004 * Was it the archiver? If so, just try to start a new one; no
2005 * need to force reset of the rest of the system. (If fail, we'll
2006 * try again in future cycles of the main loop.)
2008 if (PgArchPID != 0 && pid == PgArchPID)
2011 if (exitstatus != 0)
2012 LogChildExit(LOG, gettext("archiver process"),
2014 if (XLogArchivingActive() &&
2015 StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
2016 PgArchPID = pgarch_start();
2021 * Was it the statistics collector? If so, just try to start a
2022 * new one; no need to force reset of the rest of the system. (If
2023 * fail, we'll try again in future cycles of the main loop.)
2025 if (PgStatPID != 0 && pid == PgStatPID)
2028 if (exitstatus != 0)
2029 LogChildExit(LOG, gettext("statistics collector process"),
2031 if (StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
2032 PgStatPID = pgstat_start();
2036 /* Was it the system logger? try to start a new one */
2037 if (SysLoggerPID != 0 && pid == SysLoggerPID)
2040 /* for safety's sake, launch new logger *first* */
2041 SysLoggerPID = SysLogger_Start();
2042 if (exitstatus != 0)
2043 LogChildExit(LOG, gettext("system logger process"),
2049 * Else do standard backend child cleanup.
2051 CleanupBackend(pid, exitstatus);
2052 } /* loop over pending child-death reports */
2057 * Wait for all important children to exit, then reset shmem and
2058 * StartupDataBase. (We can ignore the archiver and stats
2059 * processes here since they are not connected to shmem.)
2061 if (DLGetHead(BackendList) || StartupPID != 0 || BgWriterPID != 0)
2064 (errmsg("all server processes terminated; reinitializing")));
2067 reset_shared(PostPortNumber);
2069 StartupPID = StartupDataBase();
2074 if (Shutdown > NoShutdown)
2076 if (DLGetHead(BackendList) || StartupPID != 0)
2078 /* Start the bgwriter if not running */
2079 if (BgWriterPID == 0)
2080 BgWriterPID = StartBackgroundWriter();
2081 /* And tell it to shut down */
2082 if (BgWriterPID != 0)
2083 kill(BgWriterPID, SIGUSR2);
2084 /* Tell pgarch to shut down too; nothing left for it to do */
2086 kill(PgArchPID, SIGQUIT);
2087 /* Tell pgstat to shut down too; nothing left for it to do */
2089 kill(PgStatPID, SIGQUIT);
2093 PG_SETMASK(&UnBlockSig);
2100 * CleanupBackend -- cleanup after terminated backend.
2102 * Remove all local state associated with backend.
2105 CleanupBackend(int pid,
2106 int exitstatus) /* child's exit status. */
2110 LogChildExit(DEBUG2, gettext("server process"), pid, exitstatus);
2113 * If a backend dies in an ugly way (i.e. exit status not 0) then we
2114 * must signal all other backends to quickdie. If exit status is zero
2115 * we assume everything is hunky dory and simply remove the backend
2116 * from the active backend list.
2118 if (exitstatus != 0)
2120 HandleChildCrash(pid, exitstatus, gettext("server process"));
2124 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2126 Backend *bp = (Backend *) DLE_VAL(curr);
2134 ShmemBackendArrayRemove(pid);
2136 /* Tell the collector about backend termination */
2144 * HandleChildCrash -- cleanup after failed backend or bgwriter.
2146 * The objectives here are to clean up our local state about the child
2147 * process, and to signal all other remaining children to quickdie.
2150 HandleChildCrash(int pid, int exitstatus, const char *procname)
2157 * Make log entry unless there was a previous crash (if so, nonzero
2158 * exit status is to be expected in SIGQUIT response; don't clutter
2163 LogChildExit(LOG, procname, pid, exitstatus);
2165 (errmsg("terminating any other active server processes")));
2168 /* Process regular backends */
2169 for (curr = DLGetHead(BackendList); curr; curr = next)
2171 next = DLGetSucc(curr);
2172 bp = (Backend *) DLE_VAL(curr);
2176 * Found entry for freshly-dead backend, so remove it.
2182 ShmemBackendArrayRemove(pid);
2184 /* Tell the collector about backend termination */
2186 /* Keep looping so we can signal remaining backends */
2191 * This backend is still alive. Unless we did so already,
2192 * tell it to commit hara-kiri.
2194 * SIGQUIT is the special signal that says exit without proc_exit
2195 * and let the user know what's going on. But if SendStop is
2196 * set (-s on command line), then we send SIGSTOP instead, so
2197 * that we can get core dumps from all backends by hand.
2202 (errmsg_internal("sending %s to process %d",
2203 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2205 kill(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
2210 /* Take care of the bgwriter too */
2211 if (pid == BgWriterPID)
2213 else if (BgWriterPID != 0 && !FatalError)
2216 (errmsg_internal("sending %s to process %d",
2217 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2218 (int) BgWriterPID)));
2219 kill(BgWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
2222 /* Force a power-cycle of the pgarch process too */
2223 /* (Shouldn't be necessary, but just for luck) */
2224 if (PgArchPID != 0 && !FatalError)
2227 (errmsg_internal("sending %s to process %d",
2230 kill(PgArchPID, SIGQUIT);
2233 /* Force a power-cycle of the pgstat processes too */
2234 /* (Shouldn't be necessary, but just for luck) */
2235 if (PgStatPID != 0 && !FatalError)
2238 (errmsg_internal("sending %s to process %d",
2241 kill(PgStatPID, SIGQUIT);
2244 /* We do NOT restart the syslogger */
2250 * Log the death of a child process.
2253 LogChildExit(int lev, const char *procname, int pid, int exitstatus)
2255 if (WIFEXITED(exitstatus))
2259 * translator: %s is a noun phrase describing a child process,
2260 * such as "server process"
2262 (errmsg("%s (PID %d) exited with exit code %d",
2263 procname, pid, WEXITSTATUS(exitstatus))));
2264 else if (WIFSIGNALED(exitstatus))
2268 * translator: %s is a noun phrase describing a child process,
2269 * such as "server process"
2271 (errmsg("%s (PID %d) was terminated by signal %d",
2272 procname, pid, WTERMSIG(exitstatus))));
2277 * translator: %s is a noun phrase describing a child process,
2278 * such as "server process"
2280 (errmsg("%s (PID %d) exited with unexpected status %d",
2281 procname, pid, exitstatus)));
2285 * Send a signal to all backend children (but NOT special children)
2288 SignalChildren(int signal)
2292 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2294 Backend *bp = (Backend *) DLE_VAL(curr);
2297 (errmsg_internal("sending signal %d to process %d",
2298 signal, (int) bp->pid)));
2299 kill(bp->pid, signal);
2304 * BackendStartup -- start backend process
2306 * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
2309 BackendStartup(Port *port)
2311 Backend *bn; /* for backend cleanup */
2314 #ifdef LINUX_PROFILE
2315 struct itimerval prof_itimer;
2319 * Compute the cancel key that will be assigned to this backend. The
2320 * backend will have its own copy in the forked-off process' value of
2321 * MyCancelKey, so that it can transmit the key to the frontend.
2323 MyCancelKey = PostmasterRandom();
2326 * Make room for backend data structure. Better before the fork() so
2327 * we can handle failure cleanly.
2329 bn = (Backend *) malloc(sizeof(Backend));
2333 (errcode(ERRCODE_OUT_OF_MEMORY),
2334 errmsg("out of memory")));
2335 return STATUS_ERROR;
2338 /* Pass down canAcceptConnections state (kluge for EXEC_BACKEND case) */
2339 port->canAcceptConnections = canAcceptConnections();
2342 * Flush stdio channels just before fork, to avoid double-output
2343 * problems. Ideally we'd use fflush(NULL) here, but there are still a
2344 * few non-ANSI stdio libraries out there (like SunOS 4.1.x) that
2345 * coredump if we do. Presently stdout and stderr are the only stdio
2346 * output channels used by the postmaster, so fflush'ing them should
2354 pid = backend_forkexec(port);
2356 #else /* !EXEC_BACKEND */
2358 #ifdef LINUX_PROFILE
2361 * Linux's fork() resets the profiling timer in the child process. If
2362 * we want to profile child processes then we need to save and restore
2363 * the timer setting. This is a waste of time if not profiling,
2364 * however, so only do it if commanded by specific -DLINUX_PROFILE
2367 getitimer(ITIMER_PROF, &prof_itimer);
2371 /* Specific beos actions before backend startup */
2372 beos_before_backend_startup();
2377 if (pid == 0) /* child */
2379 #ifdef LINUX_PROFILE
2380 setitimer(ITIMER_PROF, &prof_itimer, NULL);
2384 /* Specific beos backend startup actions */
2385 beos_backend_startup();
2389 proc_exit(BackendRun(port));
2391 #endif /* EXEC_BACKEND */
2395 /* in parent, fork failed */
2396 int save_errno = errno;
2399 /* Specific beos backend startup actions */
2400 beos_backend_startup_failed();
2405 (errmsg("could not fork new process for connection: %m")));
2406 report_fork_failure_to_client(port, save_errno);
2407 return STATUS_ERROR;
2410 /* in parent, successful fork */
2412 (errmsg_internal("forked new backend, pid=%d socket=%d",
2413 (int) pid, port->sock)));
2416 * Everything's been successful, it's safe to add this backend to our
2420 bn->cancel_key = MyCancelKey;
2421 DLAddHead(BackendList, DLNewElem(bn));
2423 ShmemBackendArrayAdd(bn);
2430 * Try to report backend fork() failure to client before we close the
2431 * connection. Since we do not care to risk blocking the postmaster on
2432 * this connection, we set the connection to non-blocking and try only once.
2434 * This is grungy special-purpose code; we cannot use backend libpq since
2435 * it's not up and running.
2438 report_fork_failure_to_client(Port *port, int errnum)
2442 /* Format the error message packet (always V2 protocol) */
2443 snprintf(buffer, sizeof(buffer), "E%s%s\n",
2444 gettext("could not fork new process for connection: "),
2447 /* Set port to non-blocking. Don't do send() if this fails */
2448 if (!set_noblock(port->sock))
2451 send(port->sock, buffer, strlen(buffer) + 1, 0);
2456 * split_opts -- split a string of options and append it to an argv array
2458 * NB: the string is destructively modified!
2460 * Since no current POSTGRES arguments require any quoting characters,
2461 * we can use the simple-minded tactic of assuming each set of space-
2462 * delimited characters is a separate argv element.
2464 * If you don't like that, well, we *used* to pass the whole option string
2465 * as ONE argument to execl(), which was even less intelligent...
2468 split_opts(char **argv, int *argcp, char *s)
2472 while (isspace((unsigned char) *s))
2476 argv[(*argcp)++] = s;
2477 while (*s && !isspace((unsigned char) *s))
2486 * BackendRun -- perform authentication, and if successful,
2487 * set up the backend's argument list and invoke PostgresMain()
2490 * Shouldn't return at all.
2491 * If PostgresMain() fails, return status.
2494 BackendRun(Port *port)
2497 char remote_host[NI_MAXHOST];
2498 char remote_port[NI_MAXSERV];
2499 char remote_ps_data[NI_MAXHOST];
2506 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
2509 * Let's clean up ourselves as the postmaster child, and close the
2510 * postmaster's listen sockets
2512 ClosePostmasterPorts(false);
2514 /* We don't want the postmaster's proc_exit() handlers */
2518 * Signal handlers setting is moved to tcop/postgres...
2521 /* Save port etc. for ps status */
2524 /* Reset MyProcPid to new backend's pid */
2525 MyProcPid = getpid();
2528 * PreAuthDelay is a debugging aid for investigating problems in the
2529 * authentication cycle: it can be set in postgresql.conf to allow
2530 * time to attach to the newly-forked backend with a debugger. (See
2531 * also the -W backend switch, which we allow clients to pass through
2532 * PGOPTIONS, but it is not honored until after authentication.)
2534 if (PreAuthDelay > 0)
2535 pg_usleep(PreAuthDelay * 1000000L);
2537 ClientAuthInProgress = true; /* limit visibility of log messages */
2539 /* save start time for end of session reporting */
2540 gettimeofday(&(port->session_start), NULL);
2542 /* set these to empty in case they are needed before we set them up */
2543 port->remote_host = "";
2544 port->remote_port = "";
2545 port->commandTag = "";
2548 * Initialize libpq and enable reporting of ereport errors to the
2549 * client. Must do this now because authentication uses libpq to send
2552 pq_init(); /* initialize libpq to talk to client */
2553 whereToSendOutput = Remote; /* now safe to ereport to client */
2556 * We arrange for a simple exit(0) if we receive SIGTERM or SIGQUIT
2557 * during any client authentication related communication. Otherwise
2558 * the postmaster cannot shutdown the database FAST or IMMED cleanly
2559 * if a buggy client blocks a backend during authentication.
2561 pqsignal(SIGTERM, authdie);
2562 pqsignal(SIGQUIT, authdie);
2563 pqsignal(SIGALRM, authdie);
2564 PG_SETMASK(&AuthBlockSig);
2567 * Get the remote host name and port for logging and status display.
2569 remote_host[0] = '\0';
2570 remote_port[0] = '\0';
2571 if (getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2572 remote_host, sizeof(remote_host),
2573 remote_port, sizeof(remote_port),
2574 (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV))
2576 int ret = getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2577 remote_host, sizeof(remote_host),
2578 remote_port, sizeof(remote_port),
2579 NI_NUMERICHOST | NI_NUMERICSERV);
2583 (errmsg("getnameinfo_all() failed: %s",
2584 gai_strerror(ret))));
2586 snprintf(remote_ps_data, sizeof(remote_ps_data),
2587 remote_port[0] == '\0' ? "%s" : "%s(%s)",
2588 remote_host, remote_port);
2590 if (Log_connections)
2592 (errmsg("connection received: host=%s port=%s",
2593 remote_host, remote_port)));
2596 * save remote_host and remote_port in port stucture
2598 port->remote_host = strdup(remote_host);
2599 port->remote_port = strdup(remote_port);
2602 * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.c
2603 * etcetera from the postmaster, and have to load them ourselves.
2604 * Build the PostmasterContext (which didn't exist before, in this
2605 * process) to contain the data.
2607 * FIXME: [fork/exec] Ugh. Is there a way around this overhead?
2610 Assert(PostmasterContext == NULL);
2611 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
2613 ALLOCSET_DEFAULT_MINSIZE,
2614 ALLOCSET_DEFAULT_INITSIZE,
2615 ALLOCSET_DEFAULT_MAXSIZE);
2616 MemoryContextSwitchTo(PostmasterContext);
2625 * Ready to begin client interaction. We will give up and exit(0)
2626 * after a time delay, so that a broken client can't hog a connection
2627 * indefinitely. PreAuthDelay doesn't count against the time limit.
2629 if (!enable_sig_alarm(AuthenticationTimeout * 1000, false))
2630 elog(FATAL, "could not set timer for authorization timeout");
2633 * Receive the startup packet (which might turn out to be a cancel
2636 status = ProcessStartupPacket(port, false);
2638 if (status != STATUS_OK)
2642 * Now that we have the user and database name, we can set the process
2643 * title for ps. It's good to do this as early as possible in
2646 init_ps_display(port->user_name, port->database_name, remote_ps_data);
2647 set_ps_display("authentication");
2650 * Now perform authentication exchange.
2652 ClientAuthentication(port); /* might not return, if failure */
2655 * Done with authentication. Disable timeout, and prevent
2656 * SIGTERM/SIGQUIT again until backend startup is complete.
2658 if (!disable_sig_alarm(false))
2659 elog(FATAL, "could not disable timer for authorization timeout");
2660 PG_SETMASK(&BlockSig);
2662 if (Log_connections)
2664 (errmsg("connection authorized: user=%s database=%s",
2665 port->user_name, port->database_name)));
2668 * Don't want backend to be able to see the postmaster random number
2669 * generator state. We have to clobber the static random_seed *and*
2670 * start a new random sequence in the random() library function.
2673 srandom((unsigned int) (MyProcPid ^ port->session_start.tv_usec));
2676 * Now, build the argv vector that will be given to PostgresMain.
2678 * The layout of the command line is
2679 * postgres [secure switches] -p databasename [insecure switches]
2680 * where the switches after -p come from the client request.
2682 * The maximum possible number of commandline arguments that could come
2683 * from ExtraOptions or port->cmdline_options is (strlen + 1) / 2; see
2687 maxac = 10; /* for fixed args supplied below */
2688 maxac += (strlen(ExtraOptions) + 1) / 2;
2689 if (port->cmdline_options)
2690 maxac += (strlen(port->cmdline_options) + 1) / 2;
2692 av = (char **) MemoryContextAlloc(TopMemoryContext,
2693 maxac * sizeof(char *));
2696 av[ac++] = "postgres";
2699 * Pass any backend switches specified with -o in the postmaster's own
2700 * command line. We assume these are secure. (It's OK to mangle
2701 * ExtraOptions now, since we're safely inside a subprocess.)
2703 split_opts(av, &ac, ExtraOptions);
2705 /* Tell the backend what protocol the frontend is using. */
2706 snprintf(protobuf, sizeof(protobuf), "-v%u", port->proto);
2707 av[ac++] = protobuf;
2710 * Tell the backend it is being called from the postmaster, and which
2711 * database to use. -p marks the end of secure switches.
2714 av[ac++] = port->database_name;
2717 * Pass the (insecure) option switches from the connection request.
2718 * (It's OK to mangle port->cmdline_options now.)
2720 if (port->cmdline_options)
2721 split_opts(av, &ac, port->cmdline_options);
2728 * Release postmaster's working memory context so that backend can
2729 * recycle the space. Note this does not trash *MyProcPort, because
2730 * ConnCreate() allocated that space with malloc() ... else we'd need
2731 * to copy the Port data here. Also, subsidiary data such as the
2732 * username isn't lost either; see ProcessStartupPacket().
2734 MemoryContextSwitchTo(TopMemoryContext);
2735 MemoryContextDelete(PostmasterContext);
2736 PostmasterContext = NULL;
2739 * Debug: print arguments being passed to backend
2742 (errmsg_internal("%s child[%d]: starting with (",
2743 progname, (int)getpid())));
2744 for (i = 0; i < ac; ++i)
2746 (errmsg_internal("\t%s", av[i])));
2748 (errmsg_internal(")")));
2750 ClientAuthInProgress = false; /* client_min_messages is active
2753 return (PostgresMain(ac, av, port->user_name));
2760 * postmaster_forkexec -- fork and exec a postmaster subprocess
2762 * The caller must have set up the argv array already, except for argv[2]
2763 * which will be filled with the name of the temp variable file.
2765 * Returns the child process PID, or -1 on fork failure (a suitable error
2766 * message has been logged on failure).
2768 * All uses of this routine will dispatch to SubPostmasterMain in the
2772 postmaster_forkexec(int argc, char *argv[])
2776 /* This entry point passes dummy values for the Port variables */
2777 memset(&port, 0, sizeof(port));
2778 return internal_forkexec(argc, argv, &port);
2782 * backend_forkexec -- fork/exec off a backend process
2784 * returns the pid of the fork/exec'd process, or -1 on failure
2787 backend_forkexec(Port *port)
2792 av[ac++] = "postgres";
2793 av[ac++] = "-forkbackend";
2794 av[ac++] = NULL; /* filled in by internal_forkexec */
2797 Assert(ac < lengthof(av));
2799 return internal_forkexec(ac, av, port);
2803 internal_forkexec(int argc, char *argv[], Port *port)
2806 char tmpfilename[MAXPGPATH];
2808 if (!write_backend_variables(tmpfilename, port))
2809 return -1; /* log made by write_backend_variables */
2811 /* Make sure caller set up argv properly */
2813 Assert(argv[argc] == NULL);
2814 Assert(strncmp(argv[1], "-fork", 5) == 0);
2815 Assert(argv[2] == NULL);
2817 /* Insert temp file name after -fork argument */
2818 argv[2] = tmpfilename;
2821 pid = win32_forkexec(postgres_exec_path, argv);
2823 /* Fire off execv in child */
2824 if ((pid = fork()) == 0)
2826 if (execv(postgres_exec_path, argv) < 0)
2829 (errmsg("could not execute server process \"%s\": %m",
2830 postgres_exec_path)));
2831 /* We're already in the child process here, can't return */
2837 return pid; /* Parent returns pid, or -1 on fork
2842 * SubPostmasterMain -- Get the fork/exec'd process into a state equivalent
2843 * to what it would be if we'd simply forked on Unix, and then
2844 * dispatch to the appropriate place.
2846 * The first two command line arguments are expected to be "-forkFOO"
2847 * (where FOO indicates which postmaster child we are to become), and
2848 * the name of a variables file that we can read to load data that would
2849 * have been inherited by fork() on Unix. Remaining arguments go to the
2850 * subprocess FooMain() routine.
2853 SubPostmasterMain(int argc, char *argv[])
2857 /* Do this sooner rather than later... */
2858 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
2860 MyProcPid = getpid(); /* reset MyProcPid */
2862 /* In EXEC_BACKEND case we will not have inherited these settings */
2863 IsPostmasterEnvironment = true;
2864 whereToSendOutput = None;
2866 PG_SETMASK(&BlockSig);
2868 /* Setup essential subsystems */
2869 MemoryContextInit();
2870 InitializeGUCOptions();
2872 /* Check we got appropriate args */
2874 elog(FATAL, "invalid subpostmaster invocation");
2876 /* Read in file-based context */
2877 memset(&port, 0, sizeof(Port));
2878 read_backend_variables(argv[2], &port);
2879 read_nondefault_variables();
2881 /* Run backend or appropriate child */
2882 if (strcmp(argv[1], "-forkbackend") == 0)
2884 /* BackendRun will close sockets */
2886 /* Attach process to shared segments */
2887 CreateSharedMemoryAndSemaphores(false, MaxBackends, 0);
2891 * Need to reinitialize the SSL library in the backend,
2892 * since the context structures contain function pointers
2893 * and cannot be passed through the parameter file.
2896 secure_initialize();
2899 Assert(argc == 3); /* shouldn't be any more args */
2900 proc_exit(BackendRun(&port));
2902 if (strcmp(argv[1], "-forkboot") == 0)
2904 /* Close the postmaster's sockets */
2905 ClosePostmasterPorts(false);
2907 /* Attach process to shared segments */
2908 CreateSharedMemoryAndSemaphores(false, MaxBackends, 0);
2910 BootstrapMain(argc - 2, argv + 2);
2913 if (strcmp(argv[1], "-forkarch") == 0)
2915 /* Close the postmaster's sockets */
2916 ClosePostmasterPorts(false);
2918 /* Do not want to attach to shared memory */
2920 PgArchiverMain(argc, argv);
2923 if (strcmp(argv[1], "-forkbuf") == 0)
2925 /* Close the postmaster's sockets */
2926 ClosePostmasterPorts(false);
2928 /* Do not want to attach to shared memory */
2930 PgstatBufferMain(argc, argv);
2933 if (strcmp(argv[1], "-forkcol") == 0)
2936 * Do NOT close postmaster sockets here, because we are forking
2937 * from pgstat buffer process, which already did it.
2940 /* Do not want to attach to shared memory */
2942 PgstatCollectorMain(argc, argv);
2945 if (strcmp(argv[1], "-forklog") == 0)
2947 /* Close the postmaster's sockets */
2948 ClosePostmasterPorts(true);
2950 /* Do not want to attach to shared memory */
2952 SysLoggerMain(argc, argv);
2956 return 1; /* shouldn't get here */
2958 #endif /* EXEC_BACKEND */
2962 * ExitPostmaster -- cleanup
2964 * Do NOT call exit() directly --- always go through here!
2967 ExitPostmaster(int status)
2969 /* should cleanup shared memory and kill all backends */
2972 * Not sure of the semantics here. When the Postmaster dies, should
2973 * the backends all be killed? probably not.
2975 * MUST -- vadim 05-10-1999
2982 * sigusr1_handler - handle signal conditions from child processes
2985 sigusr1_handler(SIGNAL_ARGS)
2987 int save_errno = errno;
2989 PG_SETMASK(&BlockSig);
2991 if (CheckPostmasterSignal(PMSIGNAL_PASSWORD_CHANGE))
2994 * Password or group file has changed.
3000 if (CheckPostmasterSignal(PMSIGNAL_WAKEN_CHILDREN))
3003 * Send SIGUSR1 to all children (triggers
3004 * CatchupInterruptHandler). See storage/ipc/sinval[adt].c for the
3007 if (Shutdown <= SmartShutdown)
3008 SignalChildren(SIGUSR1);
3011 if (PgArchPID != 0 && Shutdown == NoShutdown)
3013 if (CheckPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER))
3016 * Send SIGUSR1 to archiver process, to wake it up and begin
3017 * archiving next transaction log file.
3019 kill(PgArchPID, SIGUSR1);
3023 PG_SETMASK(&UnBlockSig);
3030 * Dummy signal handler
3032 * We use this for signals that we don't actually use in the postmaster,
3033 * but we do use in backends. If we were to SIG_IGN such signals in the
3034 * postmaster, then a newly started backend might drop a signal that arrives
3035 * before it's able to reconfigure its signal processing. (See notes in
3039 dummy_handler(SIGNAL_ARGS)
3045 * CharRemap: given an int in range 0..61, produce textual encoding of it
3046 * per crypt(3) conventions.
3070 RandomSalt(char *cryptSalt, char *md5Salt)
3072 long rand = PostmasterRandom();
3074 cryptSalt[0] = CharRemap(rand % 62);
3075 cryptSalt[1] = CharRemap(rand / 62);
3078 * It's okay to reuse the first random value for one of the MD5 salt
3079 * bytes, since only one of the two salts will be sent to the client.
3080 * After that we need to compute more random bits.
3082 * We use % 255, sacrificing one possible byte value, so as to ensure
3083 * that all bits of the random() value participate in the result.
3084 * While at it, add one to avoid generating any null bytes.
3086 md5Salt[0] = (rand % 255) + 1;
3087 rand = PostmasterRandom();
3088 md5Salt[1] = (rand % 255) + 1;
3089 rand = PostmasterRandom();
3090 md5Salt[2] = (rand % 255) + 1;
3091 rand = PostmasterRandom();
3092 md5Salt[3] = (rand % 255) + 1;
3099 PostmasterRandom(void)
3101 static bool initialized = false;
3105 Assert(random_seed != 0);
3106 srandom(random_seed);
3114 * Count up number of child processes (regular backends only)
3122 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
3129 * StartChildProcess -- start a non-backend child process for the postmaster
3131 * xlog determines what kind of child will be started. All child types
3132 * initially go to BootstrapMain, which will handle common setup.
3134 * Return value of StartChildProcess is subprocess' PID, or 0 if failed
3135 * to start subprocess.
3138 StartChildProcess(int xlop)
3145 #ifdef LINUX_PROFILE
3146 struct itimerval prof_itimer;
3150 * Set up command-line arguments for subprocess
3152 av[ac++] = "postgres";
3155 av[ac++] = "-forkboot";
3156 av[ac++] = NULL; /* filled in by postmaster_forkexec */
3159 snprintf(xlbuf, sizeof(xlbuf), "-x%d", xlop);
3163 av[ac++] = "template1";
3166 Assert(ac < lengthof(av));
3169 * Flush stdio channels (see comments in BackendStartup)
3176 pid = postmaster_forkexec(ac, av);
3178 #else /* !EXEC_BACKEND */
3180 #ifdef LINUX_PROFILE
3181 /* see comments in BackendStartup */
3182 getitimer(ITIMER_PROF, &prof_itimer);
3186 /* Specific beos actions before backend startup */
3187 beos_before_backend_startup();
3192 if (pid == 0) /* child */
3194 #ifdef LINUX_PROFILE
3195 setitimer(ITIMER_PROF, &prof_itimer, NULL);
3199 /* Specific beos actions after backend startup */
3200 beos_backend_startup();
3203 IsUnderPostmaster = true; /* we are a postmaster subprocess
3206 /* Close the postmaster's sockets */
3207 ClosePostmasterPorts(false);
3209 /* Lose the postmaster's on-exit routines and port connections */
3212 /* Release postmaster's working memory context */
3213 MemoryContextSwitchTo(TopMemoryContext);
3214 MemoryContextDelete(PostmasterContext);
3215 PostmasterContext = NULL;
3217 BootstrapMain(ac, av);
3220 #endif /* EXEC_BACKEND */
3224 /* in parent, fork failed */
3225 int save_errno = errno;
3228 /* Specific beos actions before backend startup */
3229 beos_backend_startup_failed();
3234 case BS_XLOG_STARTUP:
3236 (errmsg("could not fork startup process: %m")));
3238 case BS_XLOG_BGWRITER:
3240 (errmsg("could not fork background writer process: %m")));
3244 (errmsg("could not fork process: %m")));
3249 * fork failure is fatal during startup, but there's no need to
3250 * choke immediately if starting other child types fails.
3252 if (xlop == BS_XLOG_STARTUP)
3258 * in parent, successful fork
3265 * Create the opts file
3268 CreateOptsFile(int argc, char *argv[], char *fullprogname)
3270 char filename[MAXPGPATH];
3274 snprintf(filename, sizeof(filename), "%s/postmaster.opts", DataDir);
3276 if ((fp = fopen(filename, "w")) == NULL)
3278 elog(LOG, "could not create file \"%s\": %m", filename);
3282 fprintf(fp, "%s", fullprogname);
3283 for (i = 1; i < argc; i++)
3284 fprintf(fp, " %s%s%s", SYSTEMQUOTE, argv[i], SYSTEMQUOTE);
3289 elog(LOG, "could not write file \"%s\": %m", filename);
3300 * The following need to be available to the read/write_backend_variables
3303 #include "storage/spin.h"
3305 extern slock_t *ShmemLock;
3306 extern slock_t *ShmemIndexLock;
3307 extern void *ShmemIndexAlloc;
3308 typedef struct LWLock LWLock;
3309 extern LWLock *LWLockArray;
3310 extern slock_t *ProcStructLock;
3311 extern int pgStatSock;
3313 #define write_var(var,fp) fwrite((void*)&(var),sizeof(var),1,fp)
3314 #define read_var(var,fp) fread((void*)&(var),sizeof(var),1,fp)
3315 #define write_array_var(var,fp) fwrite((void*)(var),sizeof(var),1,fp)
3316 #define read_array_var(var,fp) fread((void*)(var),sizeof(var),1,fp)
3319 write_backend_variables(char *filename, Port *port)
3321 static unsigned long tmpBackendFileNum = 0;
3323 char str_buf[MAXPGPATH];
3325 /* Calculate name for temp file in caller's buffer */
3327 snprintf(filename, MAXPGPATH, "%s/%s/%s.backend_var.%d.%lu",
3328 DataDir, PG_TEMP_FILES_DIR, PG_TEMP_FILE_PREFIX,
3329 MyProcPid, ++tmpBackendFileNum);
3332 fp = AllocateFile(filename, PG_BINARY_W);
3335 /* As per OpenTemporaryFile... */
3336 char dirname[MAXPGPATH];
3338 snprintf(dirname, MAXPGPATH, "%s/%s", DataDir, PG_TEMP_FILES_DIR);
3339 mkdir(dirname, S_IRWXU);
3341 fp = AllocateFile(filename, PG_BINARY_W);
3345 (errcode_for_file_access(),
3346 errmsg("could not create file \"%s\": %m",
3353 write_var(port->sock, fp);
3354 write_var(port->proto, fp);
3355 write_var(port->laddr, fp);
3356 write_var(port->raddr, fp);
3357 write_var(port->canAcceptConnections, fp);
3358 write_var(port->cryptSalt, fp);
3359 write_var(port->md5Salt, fp);
3362 * XXX FIXME later: writing these strings as MAXPGPATH bytes always is
3363 * probably a waste of resources
3366 StrNCpy(str_buf, DataDir, MAXPGPATH);
3367 write_array_var(str_buf, fp);
3369 write_array_var(ListenSocket, fp);
3371 write_var(MyCancelKey, fp);
3373 write_var(UsedShmemSegID, fp);
3374 write_var(UsedShmemSegAddr, fp);
3376 write_var(ShmemLock, fp);
3377 write_var(ShmemIndexLock, fp);
3378 write_var(ShmemVariableCache, fp);
3379 write_var(ShmemIndexAlloc, fp);
3380 write_var(ShmemBackendArray, fp);
3382 write_var(LWLockArray, fp);
3383 write_var(ProcStructLock, fp);
3384 write_var(pgStatSock, fp);
3386 write_var(PostmasterPid, fp);
3388 write_var(PostmasterHandle, fp);
3391 write_var(syslogPipe[0], fp);
3392 write_var(syslogPipe[1], fp);
3394 StrNCpy(str_buf, my_exec_path, MAXPGPATH);
3395 write_array_var(str_buf, fp);
3397 write_array_var(ExtraOptions, fp);
3399 StrNCpy(str_buf, setlocale(LC_COLLATE, NULL), MAXPGPATH);
3400 write_array_var(str_buf, fp);
3401 StrNCpy(str_buf, setlocale(LC_CTYPE, NULL), MAXPGPATH);
3402 write_array_var(str_buf, fp);
3408 (errcode_for_file_access(),
3409 errmsg("could not write to file \"%s\": %m", filename)));
3417 read_backend_variables(char *filename, Port *port)
3420 char str_buf[MAXPGPATH];
3423 fp = AllocateFile(filename, PG_BINARY_R);
3426 (errcode_for_file_access(),
3427 errmsg("could not read from backend variables file \"%s\": %m",
3431 read_var(port->sock, fp);
3432 read_var(port->proto, fp);
3433 read_var(port->laddr, fp);
3434 read_var(port->raddr, fp);
3435 read_var(port->canAcceptConnections, fp);
3436 read_var(port->cryptSalt, fp);
3437 read_var(port->md5Salt, fp);
3439 read_array_var(str_buf, fp);
3440 SetDataDir(str_buf);
3442 read_array_var(ListenSocket, fp);
3444 read_var(MyCancelKey, fp);
3446 read_var(UsedShmemSegID, fp);
3447 read_var(UsedShmemSegAddr, fp);
3449 read_var(ShmemLock, fp);
3450 read_var(ShmemIndexLock, fp);
3451 read_var(ShmemVariableCache, fp);
3452 read_var(ShmemIndexAlloc, fp);
3453 read_var(ShmemBackendArray, fp);
3455 read_var(LWLockArray, fp);
3456 read_var(ProcStructLock, fp);
3457 read_var(pgStatSock, fp);
3459 read_var(PostmasterPid, fp);
3461 read_var(PostmasterHandle, fp);
3464 read_var(syslogPipe[0], fp);
3465 read_var(syslogPipe[1], fp);
3467 read_array_var(str_buf, fp);
3468 StrNCpy(my_exec_path, str_buf, MAXPGPATH);
3470 read_array_var(ExtraOptions, fp);
3472 read_array_var(str_buf, fp);
3473 setlocale(LC_COLLATE, str_buf);
3474 read_array_var(str_buf, fp);
3475 setlocale(LC_CTYPE, str_buf);
3479 if (unlink(filename) != 0)
3481 (errcode_for_file_access(),
3482 errmsg("could not remove file \"%s\": %m", filename)));
3487 ShmemBackendArraySize(void)
3489 return (NUM_BACKENDARRAY_ELEMS * sizeof(Backend));
3493 ShmemBackendArrayAllocation(void)
3495 size_t size = ShmemBackendArraySize();
3497 ShmemBackendArray = (Backend *) ShmemAlloc(size);
3498 /* Mark all slots as empty */
3499 memset(ShmemBackendArray, 0, size);
3503 ShmemBackendArrayAdd(Backend *bn)
3507 /* Find an empty slot */
3508 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
3510 if (ShmemBackendArray[i].pid == 0)
3512 ShmemBackendArray[i] = *bn;
3518 (errmsg_internal("no free slots in shmem backend array")));
3522 ShmemBackendArrayRemove(pid_t pid)
3526 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
3528 if (ShmemBackendArray[i].pid == pid)
3530 /* Mark the slot as empty */
3531 ShmemBackendArray[i].pid = 0;
3537 (errmsg_internal("could not find backend entry with pid %d",
3540 #endif /* EXEC_BACKEND */
3546 win32_forkexec(const char *path, char *argv[])
3549 PROCESS_INFORMATION pi;
3552 char cmdLine[MAXPGPATH * 2];
3553 HANDLE childHandleCopy;
3554 HANDLE waiterThread;
3556 /* Format the cmd line */
3557 cmdLine[sizeof(cmdLine) - 1] = '\0';
3558 cmdLine[sizeof(cmdLine) - 2] = '\0';
3559 snprintf(cmdLine, sizeof(cmdLine) - 1, "\"%s\"", path);
3561 while (argv[++i] != NULL)
3563 j = strlen(cmdLine);
3564 snprintf(cmdLine + j, sizeof(cmdLine) - 1 - j, " \"%s\"", argv[i]);
3566 if (cmdLine[sizeof(cmdLine) - 2] != '\0')
3568 elog(LOG, "subprocess command line too long");
3572 memset(&pi, 0, sizeof(pi));
3573 memset(&si, 0, sizeof(si));
3575 if (!CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
3577 elog(LOG, "CreateProcess call failed (%d): %m", (int) GetLastError());
3581 if (!IsUnderPostmaster)
3583 /* We are the Postmaster creating a child... */
3584 win32_AddChild(pi.dwProcessId, pi.hProcess);
3587 if (DuplicateHandle(GetCurrentProcess(),
3589 GetCurrentProcess(),
3593 DUPLICATE_SAME_ACCESS) == 0)
3595 (errmsg_internal("could not duplicate child handle: %d",
3596 (int) GetLastError())));
3598 waiterThread = CreateThread(NULL, 64 * 1024, win32_sigchld_waiter,
3599 (LPVOID) childHandleCopy, 0, NULL);
3602 (errmsg_internal("could not create sigchld waiter thread: %d",
3603 (int) GetLastError())));
3604 CloseHandle(waiterThread);
3606 if (IsUnderPostmaster)
3607 CloseHandle(pi.hProcess);
3608 CloseHandle(pi.hThread);
3610 return pi.dwProcessId;
3614 * Note: The following three functions must not be interrupted (eg. by
3615 * signals). As the Postgres Win32 signalling architecture (currently)
3616 * requires polling, or APC checking functions which aren't used here, this
3619 * We keep two separate arrays, instead of a single array of pid/HANDLE
3620 * structs, to avoid having to re-create a handle array for
3621 * WaitForMultipleObjects on each call to win32_waitpid.
3625 win32_AddChild(pid_t pid, HANDLE handle)
3627 Assert(win32_childPIDArray && win32_childHNDArray);
3628 if (win32_numChildren < NUM_BACKENDARRAY_ELEMS)
3630 win32_childPIDArray[win32_numChildren] = pid;
3631 win32_childHNDArray[win32_numChildren] = handle;
3632 ++win32_numChildren;
3636 (errmsg_internal("no room for child entry with pid %lu",
3637 (unsigned long) pid)));
3641 win32_RemoveChild(pid_t pid)
3645 Assert(win32_childPIDArray && win32_childHNDArray);
3647 for (i = 0; i < win32_numChildren; i++)
3649 if (win32_childPIDArray[i] == pid)
3651 CloseHandle(win32_childHNDArray[i]);
3653 /* Swap last entry into the "removed" one */
3654 --win32_numChildren;
3655 win32_childPIDArray[i] = win32_childPIDArray[win32_numChildren];
3656 win32_childHNDArray[i] = win32_childHNDArray[win32_numChildren];
3662 (errmsg_internal("could not find child entry with pid %lu",
3663 (unsigned long) pid)));
3667 win32_waitpid(int *exitstatus)
3670 * Note: Do NOT use WaitForMultipleObjectsEx, as we don't want to run
3676 unsigned long offset;
3678 Assert(win32_childPIDArray && win32_childHNDArray);
3679 elog(DEBUG3, "waiting on %lu children", win32_numChildren);
3681 for (offset = 0; offset < win32_numChildren; offset += MAXIMUM_WAIT_OBJECTS)
3683 unsigned long num = Min(MAXIMUM_WAIT_OBJECTS, win32_numChildren - offset);
3685 ret = WaitForMultipleObjects(num, &win32_childHNDArray[offset], FALSE, 0);
3690 (errmsg_internal("failed to wait on %lu of %lu children: %d",
3691 num, win32_numChildren, (int) GetLastError())));
3695 /* No children (in this chunk) have finished */
3701 * Get the exit code, and return the PID of, the
3702 * respective process
3704 index = offset + ret - WAIT_OBJECT_0;
3705 Assert(index >= 0 && index < win32_numChildren);
3706 if (!GetExitCodeProcess(win32_childHNDArray[index], &exitCode))
3709 * If we get this far, this should never happen, but,
3710 * then again... No choice other than to assume a
3711 * catastrophic failure.
3714 (errmsg_internal("failed to get exit code for child %lu",
3715 win32_childPIDArray[index])));
3717 *exitstatus = (int) exitCode;
3718 return win32_childPIDArray[index];
3722 /* No children have finished */
3727 * Note! Code below executes on separate threads, one for
3728 * each child process created
3731 win32_sigchld_waiter(LPVOID param)
3733 HANDLE procHandle = (HANDLE) param;
3735 DWORD r = WaitForSingleObject(procHandle, INFINITE);
3737 if (r == WAIT_OBJECT_0)
3738 pg_queue_signal(SIGCHLD);
3740 write_stderr("could not wait on child process handle: error code %d\n",
3741 (int) GetLastError());
3742 CloseHandle(procHandle);