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.426 2004/10/06 09:35:21 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>
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;
226 static int debug_flag = 0;
232 #ifdef HAVE_INT_OPTRESET
237 * postmaster.c - function prototypes
239 static void checkDataDir(const char *checkdir);
240 static bool onlyConfigSpecified(const char *checkdir);
242 #ifdef USE_RENDEZVOUS
243 static void reg_reply(DNSServiceRegistrationReplyErrorType errorCode,
246 static void pmdaemonize(void);
247 static Port *ConnCreate(int serverFd);
248 static void ConnFree(Port *port);
249 static void reset_shared(unsigned short port);
250 static void SIGHUP_handler(SIGNAL_ARGS);
251 static void pmdie(SIGNAL_ARGS);
252 static void reaper(SIGNAL_ARGS);
253 static void sigusr1_handler(SIGNAL_ARGS);
254 static void dummy_handler(SIGNAL_ARGS);
255 static void CleanupBackend(int pid, int exitstatus);
256 static void HandleChildCrash(int pid, int exitstatus, const char *procname);
257 static void LogChildExit(int lev, const char *procname,
258 int pid, int exitstatus);
259 static int BackendRun(Port *port);
260 static void ExitPostmaster(int status);
261 static void usage(const char *);
262 static int ServerLoop(void);
263 static int BackendStartup(Port *port);
264 static int ProcessStartupPacket(Port *port, bool SSLdone);
265 static void processCancelRequest(Port *port, void *pkt);
266 static int initMasks(fd_set *rmask);
267 static void report_fork_failure_to_client(Port *port, int errnum);
268 static enum CAC_state canAcceptConnections(void);
269 static long PostmasterRandom(void);
270 static void RandomSalt(char *cryptSalt, char *md5Salt);
271 static void SignalChildren(int signal);
272 static int CountChildren(void);
273 static bool CreateOptsFile(int argc, char *argv[], char *fullprogname);
274 static pid_t StartChildProcess(int xlop);
279 static pid_t win32_forkexec(const char *path, char *argv[]);
280 static void win32_AddChild(pid_t pid, HANDLE handle);
281 static void win32_RemoveChild(pid_t pid);
282 static pid_t win32_waitpid(int *exitstatus);
283 static DWORD WINAPI win32_sigchld_waiter(LPVOID param);
285 static pid_t *win32_childPIDArray;
286 static HANDLE *win32_childHNDArray;
287 static unsigned long win32_numChildren = 0;
289 HANDLE PostmasterHandle;
292 static pid_t backend_forkexec(Port *port);
293 static pid_t internal_forkexec(int argc, char *argv[], Port *port);
295 static void read_backend_variables(char *filename, Port *port);
296 static bool write_backend_variables(char *filename, Port *port);
298 static void ShmemBackendArrayAdd(Backend *bn);
299 static void ShmemBackendArrayRemove(pid_t pid);
300 #endif /* EXEC_BACKEND */
302 #define StartupDataBase() StartChildProcess(BS_XLOG_STARTUP)
303 #define StartBackgroundWriter() StartChildProcess(BS_XLOG_BGWRITER)
307 * Postmaster main entry point
310 PostmasterMain(int argc, char *argv[])
314 char *userPGDATA = NULL;
317 progname = get_progname(argv[0]);
319 MyProcPid = PostmasterPid = getpid();
321 IsPostmasterEnvironment = true;
324 * Catch standard options before doing much else. This even works on
325 * systems without getopt_long.
329 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
334 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
336 puts("postmaster (PostgreSQL) " PG_VERSION);
342 * for security, no dir or file created can be group or other
345 umask((mode_t) 0077);
348 * Fire up essential subsystems: memory management
353 * By default, palloc() requests in the postmaster will be allocated
354 * in the PostmasterContext, which is space that can be recycled by
355 * backends. Allocated data that needs to be available to backends
356 * should be allocated in TopMemoryContext.
358 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
360 ALLOCSET_DEFAULT_MINSIZE,
361 ALLOCSET_DEFAULT_INITSIZE,
362 ALLOCSET_DEFAULT_MAXSIZE);
363 MemoryContextSwitchTo(PostmasterContext);
365 IgnoreSystemIndexes(false);
367 if (find_my_exec(argv[0], my_exec_path) < 0)
368 elog(FATAL, "%s: could not locate my own executable path",
371 get_pkglib_path(my_exec_path, pkglib_path);
376 InitializeGUCOptions();
378 userPGDATA = getenv("PGDATA"); /* default value */
382 while ((opt = getopt(argc, argv, "A:a:B:b:c:D:d:Fh:ik:lm:MN:no:p:Ss-:")) != -1)
387 #ifdef USE_ASSERT_CHECKING
388 SetConfigOption("debug_assertions", optarg, PGC_POSTMASTER, PGC_S_ARGV);
390 write_stderr("%s: assert checking is not compiled in\n", progname);
394 /* Can no longer set authentication method. */
397 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
400 /* Can no longer set the backend executable file to use. */
407 /* Turn on debugging for the postmaster. */
408 char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
410 sprintf(debugstr, "debug%s", optarg);
411 SetConfigOption("log_min_messages", debugstr,
412 PGC_POSTMASTER, PGC_S_ARGV);
414 debug_flag = atoi(optarg);
418 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
421 SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
424 SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
427 SetConfigOption("unix_socket_directory", optarg, PGC_POSTMASTER, PGC_S_ARGV);
431 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
435 /* Multiplexed backends no longer supported. */
440 * ignore this flag. This may be passed in because the
441 * program was run as 'postgres -M' instead of
446 /* The max number of backends to start. */
447 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
450 /* Don't reinit shared mem after abnormal exit */
456 * Other options to pass to the backend on the command
459 snprintf(ExtraOptions + strlen(ExtraOptions),
460 sizeof(ExtraOptions) - strlen(ExtraOptions),
464 SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
469 * Start in 'S'ilent mode (disassociate from controlling
470 * tty). You may also think of this as 'S'ysV mode since
471 * it's most badly needed on SysV-derived systems like
474 SetConfigOption("silent_mode", "true", PGC_POSTMASTER, PGC_S_ARGV);
479 * In the event that some backend dumps core, send
480 * SIGSTOP, rather than SIGQUIT, to all its peers. This
481 * lets the wily post_hacker collect core dumps from
492 ParseLongOption(optarg, &name, &value);
497 (errcode(ERRCODE_SYNTAX_ERROR),
498 errmsg("--%s requires a value",
502 (errcode(ERRCODE_SYNTAX_ERROR),
503 errmsg("-c %s requires a value",
507 SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
515 write_stderr("Try \"%s --help\" for more information.\n",
522 * Postmaster accepts no non-option switch arguments.
526 write_stderr("%s: invalid argument: \"%s\"\n",
527 progname, argv[optind]);
528 write_stderr("Try \"%s --help\" for more information.\n",
535 userPGDATA = strdup(userPGDATA);
536 canonicalize_path(userPGDATA);
539 if (onlyConfigSpecified(userPGDATA))
542 * It is either a file name or a directory with no
543 * global/pg_control file, and hence not a data directory.
545 user_pgconfig = userPGDATA;
546 ProcessConfigFile(PGC_POSTMASTER);
548 if (!guc_pgdata) /* Got a pgdata from the config file? */
550 write_stderr("%s does not know where to find the database system data.\n"
551 "This should be specified as \"pgdata\" in %s%s.\n",
552 progname, userPGDATA,
553 user_pgconfig_is_dir ? "/postgresql.conf" : "");
556 checkDataDir(guc_pgdata);
557 SetDataDir(guc_pgdata);
562 * Now we can set the data directory, and then read
565 checkDataDir(userPGDATA);
566 SetDataDir(userPGDATA);
567 ProcessConfigFile(PGC_POSTMASTER);
570 if (external_pidfile)
572 FILE *fpidfile = fopen(external_pidfile, "w");
576 fprintf(fpidfile, "%d\n", MyProcPid);
578 /* Should we remove the pid file on postmaster exit? */
582 gettext("%s could not write to external pid file %s\n"),
583 progname, external_pidfile);
586 /* If timezone is not set, determine what the OS uses */
587 pg_timezone_initialize();
590 write_nondefault_variables(PGC_POSTMASTER);
594 * Check for invalid combinations of GUC settings.
596 if (NBuffers < 2 * MaxBackends || NBuffers < 16)
599 * Do not accept -B so small that backends are likely to starve
600 * for lack of buffers. The specific choices here are somewhat
603 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);
607 if (ReservedBackends >= MaxBackends)
609 write_stderr("%s: superuser_reserved_connections must be less than max_connections\n", progname);
614 * Other one-time internal sanity checks can go here.
616 if (!CheckDateTokenTables())
618 write_stderr("%s: invalid datetoken tables, please fix\n", progname);
623 * Now that we are done processing the postmaster arguments, reset
624 * getopt(3) library so that it will work correctly in subprocesses.
627 #ifdef HAVE_INT_OPTRESET
628 optreset = 1; /* some systems need this too */
631 /* For debugging: display postmaster environment */
633 extern char **environ;
637 (errmsg_internal("%s: PostmasterMain: initial environ dump:",
640 (errmsg_internal("-----------------------------------------")));
641 for (p = environ; *p; ++p)
643 (errmsg_internal("\t%s", *p)));
645 (errmsg_internal("-----------------------------------------")));
649 if (find_other_exec(argv[0], "postgres", PG_VERSIONSTR,
650 postgres_exec_path) < 0)
652 (errmsg("%s: could not locate matching postgres executable",
657 * Initialize SSL library, if specified.
665 * process any libraries that should be preloaded and optionally
668 if (preload_libraries_string)
669 process_preload_libraries(preload_libraries_string);
672 * Fork away from controlling terminal, if -S specified.
674 * Must do this before we grab any interlock files, else the interlocks
675 * will show the wrong PID.
681 * Create lockfile for data directory.
683 * We want to do this before we try to grab the input sockets, because
684 * the data directory interlock is more reliable than the socket-file
685 * interlock (thanks to whoever decided to put socket files in /tmp
686 * :-(). For the same reason, it's best to grab the TCP socket(s)
687 * before the Unix socket.
689 CreateDataDirLockFile(DataDir, true);
692 * Remove old temporary files. At this point there can be no other
693 * Postgres processes running in this directory, so this should be
699 * Establish input sockets.
701 for (i = 0; i < MAXLISTEN; i++)
702 ListenSocket[i] = -1;
710 /* Need a modifiable copy of ListenAddresses */
711 rawstring = pstrdup(ListenAddresses);
713 /* Parse string into list of identifiers */
714 if (!SplitIdentifierString(rawstring, ',', &elemlist))
716 /* syntax error in list */
718 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
719 errmsg("invalid list syntax for \"listen_addresses\"")));
724 char *curhost = (char *) lfirst(l);
726 if (strcmp(curhost, "*") == 0)
727 status = StreamServerPort(AF_UNSPEC, NULL,
728 (unsigned short) PostPortNumber,
730 ListenSocket, MAXLISTEN);
732 status = StreamServerPort(AF_UNSPEC, curhost,
733 (unsigned short) PostPortNumber,
735 ListenSocket, MAXLISTEN);
736 if (status != STATUS_OK)
738 (errmsg("could not create listen socket for \"%s\"",
746 #ifdef USE_RENDEZVOUS
747 /* Register for Rendezvous only if we opened TCP socket(s) */
748 if (ListenSocket[0] != -1 && rendezvous_name != NULL)
750 DNSServiceRegistrationCreate(rendezvous_name,
753 htonl(PostPortNumber),
755 (DNSServiceRegistrationReply) reg_reply,
760 #ifdef HAVE_UNIX_SOCKETS
761 status = StreamServerPort(AF_UNIX, NULL,
762 (unsigned short) PostPortNumber,
764 ListenSocket, MAXLISTEN);
765 if (status != STATUS_OK)
767 (errmsg("could not create Unix-domain socket")));
771 * check that we have some socket to listen on
773 if (ListenSocket[0] == -1)
775 (errmsg("no socket created for listening")));
780 * Set up shared memory and semaphores.
782 reset_shared(PostPortNumber);
785 * Estimate number of openable files. This must happen after setting
786 * up semaphores, because on some platforms semaphores count as open
792 * Initialize the list of active backends.
794 BackendList = DLNewList();
799 * Initialize the child pid/HANDLE arrays for signal handling.
801 win32_childPIDArray = (pid_t *)
802 malloc(NUM_BACKENDARRAY_ELEMS * sizeof(pid_t));
803 win32_childHNDArray = (HANDLE *)
804 malloc(NUM_BACKENDARRAY_ELEMS * sizeof(HANDLE));
805 if (!win32_childPIDArray || !win32_childHNDArray)
807 (errcode(ERRCODE_OUT_OF_MEMORY),
808 errmsg("out of memory")));
811 * Set up a handle that child processes can use to check whether the
812 * postmaster is still running.
814 if (DuplicateHandle(GetCurrentProcess(),
820 DUPLICATE_SAME_ACCESS) == 0)
822 (errmsg_internal("could not duplicate postmaster handle: %d",
823 (int) GetLastError())));
827 * Record postmaster options. We delay this till now to avoid
828 * recording bogus options (eg, NBuffers too high for available
831 if (!CreateOptsFile(argc, argv, my_exec_path))
835 * Set up signal handlers for the postmaster process.
837 * CAUTION: when changing this list, check for side-effects on the signal
838 * handling setup of child processes. See tcop/postgres.c,
839 * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/pgarch.c,
840 * postmaster/pgstat.c, and postmaster/syslogger.c.
843 PG_SETMASK(&BlockSig);
845 pqsignal(SIGHUP, SIGHUP_handler); /* reread config file and have
846 * children do same */
847 pqsignal(SIGINT, pmdie); /* send SIGTERM and shut down */
848 pqsignal(SIGQUIT, pmdie); /* send SIGQUIT and die */
849 pqsignal(SIGTERM, pmdie); /* wait for children and shut down */
850 pqsignal(SIGALRM, SIG_IGN); /* ignored */
851 pqsignal(SIGPIPE, SIG_IGN); /* ignored */
852 pqsignal(SIGUSR1, sigusr1_handler); /* message from child process */
853 pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
854 pqsignal(SIGCHLD, reaper); /* handle child termination */
855 pqsignal(SIGTTIN, SIG_IGN); /* ignored */
856 pqsignal(SIGTTOU, SIG_IGN); /* ignored */
857 /* ignore SIGXFSZ, so that ulimit violations work like disk full */
859 pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
863 * If enabled, start up syslogger collection subprocess
865 SysLoggerPID = SysLogger_Start();
868 * Reset whereToSendOutput from Debug (its starting state) to None.
869 * This stops ereport from sending log messages to stderr unless
870 * Log_destination permits. We don't do this until the postmaster is
871 * fully launched, since startup failures may as well be reported to
874 whereToSendOutput = None;
877 * Initialize the statistics collector stuff
882 * Load cached files for client authentication.
890 * We're ready to rock and roll...
892 StartupPID = StartupDataBase();
895 write_nondefault_variables(PGC_POSTMASTER);
898 status = ServerLoop();
901 * ServerLoop probably shouldn't ever return, but if it does, close
904 ExitPostmaster(status != STATUS_OK);
906 return 0; /* not reached */
912 onlyConfigSpecified(const char *checkdir)
914 char path[MAXPGPATH];
915 struct stat stat_buf;
917 if (checkdir == NULL) /* checkDataDir handles this */
920 if (stat(checkdir, &stat_buf) == -1) /* ditto */
923 if (S_ISREG(stat_buf.st_mode)) /* It's a regular file, so assume
926 else if (S_ISDIR(stat_buf.st_mode)) /* It's a directory, is it a
927 * config or system dir? */
929 snprintf(path, MAXPGPATH, "%s/global/pg_control", checkdir);
930 /* If this is not found, it is a config-only directory */
931 if (stat(path, &stat_buf) == -1)
939 * Validate the proposed data directory
942 checkDataDir(const char *checkdir)
944 char path[MAXPGPATH];
946 struct stat stat_buf;
948 if (checkdir == NULL)
950 write_stderr("%s does not know where to find the database system data.\n"
951 "You must specify the directory that contains the database system\n"
952 "either by specifying the -D invocation option or by setting the\n"
953 "PGDATA environment variable.\n",
958 if (stat(checkdir, &stat_buf) == -1)
962 (errcode_for_file_access(),
963 errmsg("data directory \"%s\" does not exist",
967 (errcode_for_file_access(),
968 errmsg("could not read permissions of directory \"%s\": %m",
973 * Check if the directory has group or world access. If so, reject.
975 * XXX temporarily suppress check when on Windows, because there may not
976 * be proper support for Unix-y file permissions. Need to think of a
977 * reasonable check to apply on Windows.
979 #if !defined(WIN32) && !defined(__CYGWIN__)
980 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
982 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
983 errmsg("data directory \"%s\" has group or world access",
985 errdetail("Permissions should be u=rwx (0700).")));
988 /* Look for PG_VERSION before looking for pg_control */
989 ValidatePgVersion(checkdir);
991 snprintf(path, sizeof(path), "%s/global/pg_control", checkdir);
993 fp = AllocateFile(path, PG_BINARY_R);
996 write_stderr("%s: could not find the database system\n"
997 "Expected to find it in the directory \"%s\",\n"
998 "but could not open file \"%s\": %s\n",
999 progname, checkdir, path, strerror(errno));
1006 #ifdef USE_RENDEZVOUS
1009 * empty callback function for DNSServiceRegistrationCreate()
1012 reg_reply(DNSServiceRegistrationReplyErrorType errorCode, void *context)
1016 #endif /* USE_RENDEZVOUS */
1020 * Fork away from the controlling terminal (-S option)
1029 #ifdef LINUX_PROFILE
1030 struct itimerval prof_itimer;
1033 #ifdef LINUX_PROFILE
1034 /* see comments in BackendStartup */
1035 getitimer(ITIMER_PROF, &prof_itimer);
1039 if (pid == (pid_t) -1)
1041 write_stderr("%s: could not fork background process: %s\n",
1042 progname, strerror(errno));
1047 /* Parent should just exit, without doing any atexit cleanup */
1051 #ifdef LINUX_PROFILE
1052 setitimer(ITIMER_PROF, &prof_itimer, NULL);
1055 MyProcPid = PostmasterPid = getpid(); /* reset PID vars to child */
1057 /* GH: If there's no setsid(), we hopefully don't need silent mode.
1058 * Until there's a better solution.
1063 write_stderr("%s: could not dissociate from controlling TTY: %s\n",
1064 progname, strerror(errno));
1068 i = open(NULL_DEV, O_RDWR);
1075 elog(FATAL, "SilentMode not supported under WIN32");
1081 * Print out help message
1084 usage(const char *progname)
1086 printf(gettext("%s is the PostgreSQL server.\n\n"), progname);
1087 printf(gettext("Usage:\n %s [OPTION]...\n\n"), progname);
1088 printf(gettext("Options:\n"));
1089 #ifdef USE_ASSERT_CHECKING
1090 printf(gettext(" -A 1|0 enable/disable run-time assert checking\n"));
1092 printf(gettext(" -B NBUFFERS number of shared buffers\n"));
1093 printf(gettext(" -c NAME=VALUE set run-time parameter\n"));
1094 printf(gettext(" -d 1-5 debugging level\n"));
1095 printf(gettext(" -D DATADIR database directory\n"));
1096 printf(gettext(" -F turn fsync off\n"));
1097 printf(gettext(" -h HOSTNAME host name or IP address to listen on\n"));
1098 printf(gettext(" -i enable TCP/IP connections\n"));
1099 printf(gettext(" -k DIRECTORY Unix-domain socket location\n"));
1101 printf(gettext(" -l enable SSL connections\n"));
1103 printf(gettext(" -N MAX-CONNECT maximum number of allowed connections\n"));
1104 printf(gettext(" -o OPTIONS pass \"OPTIONS\" to each server process\n"));
1105 printf(gettext(" -p PORT port number to listen on\n"));
1106 printf(gettext(" -S silent mode (start in background without logging output)\n"));
1107 printf(gettext(" --help show this help, then exit\n"));
1108 printf(gettext(" --version output version information, then exit\n"));
1110 printf(gettext("\nDeveloper options:\n"));
1111 printf(gettext(" -n do not reinitialize shared memory after abnormal exit\n"));
1112 printf(gettext(" -s send SIGSTOP to all backend servers if one dies\n"));
1114 printf(gettext("\nPlease read the documentation for the complete list of run-time\n"
1115 "configuration settings and how to set them on the command line or in\n"
1116 "the configuration file.\n\n"
1117 "Report bugs to <pgsql-bugs@postgresql.org>.\n"));
1122 * Main idle loop of postmaster
1131 struct timeval earlier,
1135 gettimeofday(&earlier, &tz);
1136 last_touch_time = time(NULL);
1138 nSockets = initMasks(&readmask);
1144 struct timeval timeout;
1149 * Wait for something to happen.
1151 * We wait at most one minute, to ensure that the other background
1152 * tasks handled below get done even when no requests are
1155 memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
1157 timeout.tv_sec = 60;
1158 timeout.tv_usec = 0;
1160 PG_SETMASK(&UnBlockSig);
1162 selres = select(nSockets, &rmask, NULL, NULL, &timeout);
1165 * Block all signals until we wait again. (This makes it safe for
1166 * our signal handlers to do nontrivial work.)
1168 PG_SETMASK(&BlockSig);
1172 if (errno != EINTR && errno != EWOULDBLOCK)
1175 (errcode_for_socket_access(),
1176 errmsg("select() failed in postmaster: %m")));
1177 return STATUS_ERROR;
1182 * New connection pending on any of our sockets? If so, fork a
1183 * child process to deal with it.
1188 * Select a random seed at the time of first receiving a
1191 while (random_seed == 0)
1193 gettimeofday(&later, &tz);
1196 * We are not sure how much precision is in tv_usec, so we
1197 * swap the nibbles of 'later' and XOR them with
1198 * 'earlier'. On the off chance that the result is 0, we
1199 * loop until it isn't.
1201 random_seed = earlier.tv_usec ^
1202 ((later.tv_usec << 16) |
1203 ((later.tv_usec >> 16) & 0xffff));
1206 for (i = 0; i < MAXLISTEN; i++)
1208 if (ListenSocket[i] == -1)
1210 if (FD_ISSET(ListenSocket[i], &rmask))
1212 port = ConnCreate(ListenSocket[i]);
1215 BackendStartup(port);
1218 * We no longer need the open socket or port
1219 * structure in this process
1221 StreamClose(port->sock);
1228 /* If we have lost the system logger, try to start a new one */
1229 if (SysLoggerPID == 0 && Redirect_stderr)
1230 SysLoggerPID = SysLogger_Start();
1233 * If no background writer process is running, and we are not in a
1234 * state that prevents it, start one. It doesn't matter if this
1235 * fails, we'll just try again later.
1237 if (BgWriterPID == 0 && StartupPID == 0 && !FatalError)
1239 BgWriterPID = StartBackgroundWriter();
1240 /* If shutdown is pending, set it going */
1241 if (Shutdown > NoShutdown && BgWriterPID != 0)
1242 kill(BgWriterPID, SIGUSR2);
1245 /* If we have lost the archiver, try to start a new one */
1246 if (XLogArchivingActive() && PgArchPID == 0 &&
1247 StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
1248 PgArchPID = pgarch_start();
1250 /* If we have lost the stats collector, try to start a new one */
1251 if (PgStatPID == 0 &&
1252 StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
1253 PgStatPID = pgstat_start();
1256 * Touch the socket and lock file at least every ten minutes, to
1257 * ensure that they are not removed by overzealous /tmp-cleaning
1261 if (now - last_touch_time >= 10 * 60)
1264 TouchSocketLockFile();
1265 last_touch_time = now;
1272 * Initialise the masks for select() for the ports we are listening on.
1273 * Return the number of sockets to listen on.
1276 initMasks(fd_set *rmask)
1283 for (i = 0; i < MAXLISTEN; i++)
1285 int fd = ListenSocket[i];
1299 * Read the startup packet and do something according to it.
1301 * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
1302 * not return at all.
1304 * (Note that ereport(FATAL) stuff is sent to the client, so only use it
1305 * if that's what you want. Return STATUS_ERROR if you don't want to
1306 * send anything to the client, which would typically be appropriate
1307 * if we detect a communications failure.)
1310 ProcessStartupPacket(Port *port, bool SSLdone)
1314 ProtocolVersion proto;
1315 MemoryContext oldcontext;
1317 if (pq_getbytes((char *) &len, 4) == EOF)
1320 * EOF after SSLdone probably means the client didn't like our
1321 * response to NEGOTIATE_SSL_CODE. That's not an error condition,
1322 * so don't clutter the log with a complaint.
1326 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1327 errmsg("incomplete startup packet")));
1328 return STATUS_ERROR;
1334 if (len < (int32) sizeof(ProtocolVersion) ||
1335 len > MAX_STARTUP_PACKET_LENGTH)
1338 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1339 errmsg("invalid length of startup packet")));
1340 return STATUS_ERROR;
1344 * Allocate at least the size of an old-style startup packet, plus one
1345 * extra byte, and make sure all are zeroes. This ensures we will
1346 * have null termination of all strings, in both fixed- and
1347 * variable-length packet layouts.
1349 if (len <= (int32) sizeof(StartupPacket))
1350 buf = palloc0(sizeof(StartupPacket) + 1);
1352 buf = palloc0(len + 1);
1354 if (pq_getbytes(buf, len) == EOF)
1357 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1358 errmsg("incomplete startup packet")));
1359 return STATUS_ERROR;
1363 * The first field is either a protocol version number or a special
1366 port->proto = proto = ntohl(*((ProtocolVersion *) buf));
1368 if (proto == CANCEL_REQUEST_CODE)
1370 processCancelRequest(port, buf);
1371 return 127; /* XXX */
1374 if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
1379 /* No SSL when disabled or on Unix sockets */
1380 if (!EnableSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
1383 SSLok = 'S'; /* Support for SSL */
1385 SSLok = 'N'; /* No support for SSL */
1387 if (send(port->sock, &SSLok, 1, 0) != 1)
1390 (errcode_for_socket_access(),
1391 errmsg("failed to send SSL negotiation response: %m")));
1392 return STATUS_ERROR; /* close the connection */
1396 if (SSLok == 'S' && secure_open_server(port) == -1)
1397 return STATUS_ERROR;
1399 /* regular startup packet, cancel, etc packet should follow... */
1400 /* but not another SSL negotiation request */
1401 return ProcessStartupPacket(port, true);
1404 /* Could add additional special packet types here */
1407 * Set FrontendProtocol now so that ereport() knows what format to
1408 * send if we fail during startup.
1410 FrontendProtocol = proto;
1412 /* Check we can handle the protocol the frontend is using. */
1414 if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
1415 PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
1416 (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
1417 PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
1419 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1420 errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
1421 PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
1422 PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST),
1423 PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST),
1424 PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))));
1427 * Now fetch parameters out of startup packet and save them into the
1428 * Port structure. All data structures attached to the Port struct
1429 * must be allocated in TopMemoryContext so that they won't disappear
1430 * when we pass them to PostgresMain (see BackendRun). We need not
1431 * worry about leaking this storage on failure, since we aren't in the
1432 * postmaster process anymore.
1434 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1436 if (PG_PROTOCOL_MAJOR(proto) >= 3)
1438 int32 offset = sizeof(ProtocolVersion);
1441 * Scan packet body for name/option pairs. We can assume any
1442 * string beginning within the packet body is null-terminated,
1443 * thanks to zeroing extra byte above.
1445 port->guc_options = NIL;
1447 while (offset < len)
1449 char *nameptr = ((char *) buf) + offset;
1453 if (*nameptr == '\0')
1454 break; /* found packet terminator */
1455 valoffset = offset + strlen(nameptr) + 1;
1456 if (valoffset >= len)
1457 break; /* missing value, will complain below */
1458 valptr = ((char *) buf) + valoffset;
1460 if (strcmp(nameptr, "database") == 0)
1461 port->database_name = pstrdup(valptr);
1462 else if (strcmp(nameptr, "user") == 0)
1463 port->user_name = pstrdup(valptr);
1464 else if (strcmp(nameptr, "options") == 0)
1465 port->cmdline_options = pstrdup(valptr);
1468 /* Assume it's a generic GUC option */
1469 port->guc_options = lappend(port->guc_options,
1471 port->guc_options = lappend(port->guc_options,
1474 offset = valoffset + strlen(valptr) + 1;
1478 * If we didn't find a packet terminator exactly at the end of the
1479 * given packet length, complain.
1481 if (offset != len - 1)
1483 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1484 errmsg("invalid startup packet layout: expected terminator as last byte")));
1489 * Get the parameters from the old-style, fixed-width-fields
1490 * startup packet as C strings. The packet destination was
1491 * cleared first so a short packet has zeros silently added. We
1492 * have to be prepared to truncate the pstrdup result for oversize
1495 StartupPacket *packet = (StartupPacket *) buf;
1497 port->database_name = pstrdup(packet->database);
1498 if (strlen(port->database_name) > sizeof(packet->database))
1499 port->database_name[sizeof(packet->database)] = '\0';
1500 port->user_name = pstrdup(packet->user);
1501 if (strlen(port->user_name) > sizeof(packet->user))
1502 port->user_name[sizeof(packet->user)] = '\0';
1503 port->cmdline_options = pstrdup(packet->options);
1504 if (strlen(port->cmdline_options) > sizeof(packet->options))
1505 port->cmdline_options[sizeof(packet->options)] = '\0';
1506 port->guc_options = NIL;
1509 /* Check a user name was given. */
1510 if (port->user_name == NULL || port->user_name[0] == '\0')
1512 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1513 errmsg("no PostgreSQL user name specified in startup packet")));
1515 /* The database defaults to the user name. */
1516 if (port->database_name == NULL || port->database_name[0] == '\0')
1517 port->database_name = pstrdup(port->user_name);
1519 if (Db_user_namespace)
1522 * If user@, it is a global user, remove '@'. We only want to do
1523 * this if there is an '@' at the end and no earlier in the user
1524 * string or they may fake as a local user of another database
1525 * attaching to this database.
1527 if (strchr(port->user_name, '@') ==
1528 port->user_name + strlen(port->user_name) - 1)
1529 *strchr(port->user_name, '@') = '\0';
1532 /* Append '@' and dbname */
1535 db_user = palloc(strlen(port->user_name) +
1536 strlen(port->database_name) + 2);
1537 sprintf(db_user, "%s@%s", port->user_name, port->database_name);
1538 port->user_name = db_user;
1543 * Truncate given database and user names to length of a Postgres
1544 * name. This avoids lookup failures when overlength names are given.
1546 if (strlen(port->database_name) >= NAMEDATALEN)
1547 port->database_name[NAMEDATALEN - 1] = '\0';
1548 if (strlen(port->user_name) >= NAMEDATALEN)
1549 port->user_name[NAMEDATALEN - 1] = '\0';
1552 * Done putting stuff in TopMemoryContext.
1554 MemoryContextSwitchTo(oldcontext);
1557 * If we're going to reject the connection due to database state, say
1558 * so now instead of wasting cycles on an authentication exchange.
1559 * (This also allows a pg_ping utility to be written.)
1561 switch (port->canAcceptConnections)
1565 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1566 errmsg("the database system is starting up")));
1570 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1571 errmsg("the database system is shutting down")));
1575 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1576 errmsg("the database system is in recovery mode")));
1580 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
1581 errmsg("sorry, too many clients already")));
1593 * The client has sent a cancel request packet, not a normal
1594 * start-a-new-connection packet. Perform the necessary processing.
1595 * Nothing is sent back to the client.
1598 processCancelRequest(Port *port, void *pkt)
1600 CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
1602 long cancelAuthCode;
1605 #ifndef EXEC_BACKEND
1612 backendPID = (int) ntohl(canc->backendPID);
1613 cancelAuthCode = (long) ntohl(canc->cancelAuthCode);
1616 * See if we have a matching backend. In the EXEC_BACKEND case, we
1617 * can no longer access the postmaster's own backend list, and must
1618 * rely on the duplicate array in shared memory.
1620 #ifndef EXEC_BACKEND
1621 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
1623 bp = (Backend *) DLE_VAL(curr);
1625 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
1627 bp = (Backend *) &ShmemBackendArray[i];
1629 if (bp->pid == backendPID)
1631 if (bp->cancel_key == cancelAuthCode)
1633 /* Found a match; signal that backend to cancel current op */
1635 (errmsg_internal("processing cancel request: sending SIGINT to process %d",
1637 kill(bp->pid, SIGINT);
1640 /* Right PID, wrong key: no way, Jose */
1642 (errmsg_internal("bad key in cancel request for process %d",
1648 /* No matching backend */
1650 (errmsg_internal("bad pid in cancel request for process %d",
1655 * canAcceptConnections --- check to see if database state allows connections.
1657 static enum CAC_state
1658 canAcceptConnections(void)
1660 /* Can't start backends when in startup/shutdown/recovery state. */
1661 if (Shutdown > NoShutdown)
1662 return CAC_SHUTDOWN;
1666 return CAC_RECOVERY;
1669 * Don't start too many children.
1671 * We allow more connections than we can have backends here because some
1672 * might still be authenticating; they might fail auth, or some
1673 * existing backend might exit before the auth cycle is completed. The
1674 * exact MaxBackends limit is enforced when a new backend tries to
1675 * join the shared-inval backend array.
1677 if (CountChildren() >= 2 * MaxBackends)
1685 * ConnCreate -- create a local connection data structure
1688 ConnCreate(int serverFd)
1692 if (!(port = (Port *) calloc(1, sizeof(Port))))
1695 (errcode(ERRCODE_OUT_OF_MEMORY),
1696 errmsg("out of memory")));
1700 if (StreamConnection(serverFd, port) != STATUS_OK)
1702 StreamClose(port->sock);
1709 * Precompute password salt values to use for this connection.
1710 * It's slightly annoying to do this long in advance of knowing
1711 * whether we'll need 'em or not, but we must do the random()
1712 * calls before we fork, not after. Else the postmaster's random
1713 * sequence won't get advanced, and all backends would end up
1714 * using the same salt...
1716 RandomSalt(port->cryptSalt, port->md5Salt);
1724 * ConnFree -- free a local connection data structure
1727 ConnFree(Port *conn)
1737 * ClosePostmasterPorts -- close all the postmaster's open sockets
1739 * This is called during child process startup to release file descriptors
1740 * that are not needed by that child process. The postmaster still has
1741 * them open, of course.
1743 * Note: we pass am_syslogger as a boolean because we don't want to set
1744 * the global variable yet when this is called.
1747 ClosePostmasterPorts(bool am_syslogger)
1751 /* Close the listen sockets */
1752 for (i = 0; i < MAXLISTEN; i++)
1754 if (ListenSocket[i] != -1)
1756 StreamClose(ListenSocket[i]);
1757 ListenSocket[i] = -1;
1761 /* If using syslogger, close the read side of the pipe */
1765 if (syslogPipe[0] >= 0)
1766 close(syslogPipe[0]);
1770 CloseHandle(syslogPipe[0]);
1778 * reset_shared -- reset shared memory and semaphores
1781 reset_shared(unsigned short port)
1784 * Create or re-create shared memory and semaphores.
1786 * Note: in each "cycle of life" we will normally assign the same IPC
1787 * keys (if using SysV shmem and/or semas), since the port number is
1788 * used to determine IPC keys. This helps ensure that we will clean
1789 * up dead IPC objects if the postmaster crashes and is restarted.
1791 CreateSharedMemoryAndSemaphores(false, MaxBackends, port);
1796 * SIGHUP -- reread config files, and tell children to do same
1799 SIGHUP_handler(SIGNAL_ARGS)
1801 int save_errno = errno;
1803 PG_SETMASK(&BlockSig);
1805 if (Shutdown <= SmartShutdown)
1808 (errmsg("received SIGHUP, reloading configuration files")));
1809 ProcessConfigFile(PGC_SIGHUP);
1810 SignalChildren(SIGHUP);
1811 if (BgWriterPID != 0)
1812 kill(BgWriterPID, SIGHUP);
1814 kill(PgArchPID, SIGHUP);
1815 if (SysLoggerPID != 0)
1816 kill(SysLoggerPID, SIGHUP);
1817 /* PgStatPID does not currently need SIGHUP */
1822 /* Update the starting-point file for future children */
1823 write_nondefault_variables(PGC_SIGHUP);
1827 PG_SETMASK(&UnBlockSig);
1834 * pmdie -- signal handler for processing various postmaster signals.
1839 int save_errno = errno;
1841 PG_SETMASK(&BlockSig);
1844 (errmsg_internal("postmaster received signal %d",
1845 postgres_signal_arg)));
1847 switch (postgres_signal_arg)
1854 * Wait for children to end their work, then shut down.
1856 if (Shutdown >= SmartShutdown)
1858 Shutdown = SmartShutdown;
1860 (errmsg("received smart shutdown request")));
1862 if (DLGetHead(BackendList))
1863 break; /* let reaper() handle this */
1866 * No children left. Begin shutdown of data base system.
1868 if (StartupPID != 0 || FatalError)
1869 break; /* let reaper() handle this */
1870 /* Start the bgwriter if not running */
1871 if (BgWriterPID == 0)
1872 BgWriterPID = StartBackgroundWriter();
1873 /* And tell it to shut down */
1874 if (BgWriterPID != 0)
1875 kill(BgWriterPID, SIGUSR2);
1876 /* Tell pgarch to shut down too; nothing left for it to do */
1878 kill(PgArchPID, SIGQUIT);
1879 /* Tell pgstat to shut down too; nothing left for it to do */
1881 kill(PgStatPID, SIGQUIT);
1889 * Abort all children with SIGTERM (rollback active transactions
1890 * and exit) and shut down when they are gone.
1892 if (Shutdown >= FastShutdown)
1894 Shutdown = FastShutdown;
1896 (errmsg("received fast shutdown request")));
1898 if (DLGetHead(BackendList))
1903 (errmsg("aborting any active transactions")));
1904 SignalChildren(SIGTERM);
1905 /* reaper() does the rest */
1911 * No children left. Begin shutdown of data base system.
1913 * Note: if we previously got SIGTERM then we may send SIGUSR2 to
1914 * the bgwriter a second time here. This should be harmless.
1916 if (StartupPID != 0 || FatalError)
1917 break; /* let reaper() handle this */
1918 /* Start the bgwriter if not running */
1919 if (BgWriterPID == 0)
1920 BgWriterPID = StartBackgroundWriter();
1921 /* And tell it to shut down */
1922 if (BgWriterPID != 0)
1923 kill(BgWriterPID, SIGUSR2);
1924 /* Tell pgarch to shut down too; nothing left for it to do */
1926 kill(PgArchPID, SIGQUIT);
1927 /* Tell pgstat to shut down too; nothing left for it to do */
1929 kill(PgStatPID, SIGQUIT);
1935 * Immediate Shutdown:
1937 * abort all children with SIGQUIT and exit without attempt to
1938 * properly shut down data base system.
1941 (errmsg("received immediate shutdown request")));
1942 if (StartupPID != 0)
1943 kill(StartupPID, SIGQUIT);
1944 if (BgWriterPID != 0)
1945 kill(BgWriterPID, SIGQUIT);
1947 kill(PgArchPID, SIGQUIT);
1949 kill(PgStatPID, SIGQUIT);
1950 if (DLGetHead(BackendList))
1951 SignalChildren(SIGQUIT);
1956 PG_SETMASK(&UnBlockSig);
1962 * Reaper -- signal handler to cleanup after a backend (child) dies.
1967 int save_errno = errno;
1970 int status; /* backend exit status */
1974 union wait status; /* backend exit status */
1978 int pid; /* process id of dead backend */
1980 PG_SETMASK(&BlockSig);
1983 (errmsg_internal("reaping dead processes")));
1985 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1987 exitstatus = status;
1990 while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
1992 exitstatus = status.w_status;
1994 while ((pid = win32_waitpid(&exitstatus)) > 0)
1997 * We need to do this here, and not in CleanupBackend, since this
1998 * is to be called on all children when we are done with them.
1999 * Could move to LogChildExit, but that seems like asking for
2002 win32_RemoveChild(pid);
2004 #endif /* HAVE_WAITPID */
2007 * Check if this child was a startup process.
2009 if (StartupPID != 0 && pid == StartupPID)
2012 if (exitstatus != 0)
2014 LogChildExit(LOG, gettext("startup process"),
2017 (errmsg("aborting startup due to startup process failure")));
2022 * Startup succeeded - we are done with system startup or
2028 * Crank up the background writer. It doesn't matter if this
2029 * fails, we'll just try again later.
2031 Assert(BgWriterPID == 0);
2032 BgWriterPID = StartBackgroundWriter();
2035 * Go to shutdown mode if a shutdown request was pending.
2036 * Otherwise, try to start the archiver and stats collector
2039 if (Shutdown > NoShutdown && BgWriterPID != 0)
2040 kill(BgWriterPID, SIGUSR2);
2041 else if (Shutdown == NoShutdown)
2043 if (XLogArchivingActive() && PgArchPID == 0)
2044 PgArchPID = pgarch_start();
2046 PgStatPID = pgstat_start();
2053 * Was it the bgwriter?
2055 if (BgWriterPID != 0 && pid == BgWriterPID)
2058 if (exitstatus == 0 && Shutdown > NoShutdown &&
2059 !FatalError && !DLGetHead(BackendList))
2062 * Normal postmaster exit is here: we've seen normal exit
2063 * of the bgwriter after it's been told to shut down. We
2064 * expect that it wrote a shutdown checkpoint. (If for
2065 * some reason it didn't, recovery will occur on next
2066 * postmaster start.)
2068 * Note: we do not wait around for exit of the archiver or
2069 * stats processes. They've been sent SIGQUIT by this
2070 * point, and in any case contain logic to commit
2071 * hara-kiri if they notice the postmaster is gone.
2077 * Any unexpected exit of the bgwriter is treated as a crash.
2079 HandleChildCrash(pid, exitstatus,
2080 gettext("background writer process"));
2085 * Was it the archiver? If so, just try to start a new one; no
2086 * need to force reset of the rest of the system. (If fail, we'll
2087 * try again in future cycles of the main loop.)
2089 if (PgArchPID != 0 && pid == PgArchPID)
2092 if (exitstatus != 0)
2093 LogChildExit(LOG, gettext("archiver process"),
2095 if (XLogArchivingActive() &&
2096 StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
2097 PgArchPID = pgarch_start();
2102 * Was it the statistics collector? If so, just try to start a
2103 * new one; no need to force reset of the rest of the system. (If
2104 * fail, we'll try again in future cycles of the main loop.)
2106 if (PgStatPID != 0 && pid == PgStatPID)
2109 if (exitstatus != 0)
2110 LogChildExit(LOG, gettext("statistics collector process"),
2112 if (StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
2113 PgStatPID = pgstat_start();
2117 /* Was it the system logger? try to start a new one */
2118 if (SysLoggerPID != 0 && pid == SysLoggerPID)
2121 /* for safety's sake, launch new logger *first* */
2122 SysLoggerPID = SysLogger_Start();
2123 if (exitstatus != 0)
2124 LogChildExit(LOG, gettext("system logger process"),
2130 * Else do standard backend child cleanup.
2132 CleanupBackend(pid, exitstatus);
2133 } /* loop over pending child-death reports */
2138 * Wait for all important children to exit, then reset shmem and
2139 * StartupDataBase. (We can ignore the archiver and stats
2140 * processes here since they are not connected to shmem.)
2142 if (DLGetHead(BackendList) || StartupPID != 0 || BgWriterPID != 0)
2145 (errmsg("all server processes terminated; reinitializing")));
2148 reset_shared(PostPortNumber);
2150 StartupPID = StartupDataBase();
2155 if (Shutdown > NoShutdown)
2157 if (DLGetHead(BackendList) || StartupPID != 0)
2159 /* Start the bgwriter if not running */
2160 if (BgWriterPID == 0)
2161 BgWriterPID = StartBackgroundWriter();
2162 /* And tell it to shut down */
2163 if (BgWriterPID != 0)
2164 kill(BgWriterPID, SIGUSR2);
2165 /* Tell pgarch to shut down too; nothing left for it to do */
2167 kill(PgArchPID, SIGQUIT);
2168 /* Tell pgstat to shut down too; nothing left for it to do */
2170 kill(PgStatPID, SIGQUIT);
2174 PG_SETMASK(&UnBlockSig);
2181 * CleanupBackend -- cleanup after terminated backend.
2183 * Remove all local state associated with backend.
2186 CleanupBackend(int pid,
2187 int exitstatus) /* child's exit status. */
2191 LogChildExit(DEBUG2, gettext("server process"), pid, exitstatus);
2194 * If a backend dies in an ugly way (i.e. exit status not 0) then we
2195 * must signal all other backends to quickdie. If exit status is zero
2196 * we assume everything is hunky dory and simply remove the backend
2197 * from the active backend list.
2199 if (exitstatus != 0)
2201 HandleChildCrash(pid, exitstatus, gettext("server process"));
2205 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2207 Backend *bp = (Backend *) DLE_VAL(curr);
2215 ShmemBackendArrayRemove(pid);
2217 /* Tell the collector about backend termination */
2225 * HandleChildCrash -- cleanup after failed backend or bgwriter.
2227 * The objectives here are to clean up our local state about the child
2228 * process, and to signal all other remaining children to quickdie.
2231 HandleChildCrash(int pid, int exitstatus, const char *procname)
2238 * Make log entry unless there was a previous crash (if so, nonzero
2239 * exit status is to be expected in SIGQUIT response; don't clutter
2244 LogChildExit(LOG, procname, pid, exitstatus);
2246 (errmsg("terminating any other active server processes")));
2249 /* Process regular backends */
2250 for (curr = DLGetHead(BackendList); curr; curr = next)
2252 next = DLGetSucc(curr);
2253 bp = (Backend *) DLE_VAL(curr);
2257 * Found entry for freshly-dead backend, so remove it.
2263 ShmemBackendArrayRemove(pid);
2265 /* Tell the collector about backend termination */
2267 /* Keep looping so we can signal remaining backends */
2272 * This backend is still alive. Unless we did so already,
2273 * tell it to commit hara-kiri.
2275 * SIGQUIT is the special signal that says exit without proc_exit
2276 * and let the user know what's going on. But if SendStop is
2277 * set (-s on command line), then we send SIGSTOP instead, so
2278 * that we can get core dumps from all backends by hand.
2283 (errmsg_internal("sending %s to process %d",
2284 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2286 kill(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
2291 /* Take care of the bgwriter too */
2292 if (pid == BgWriterPID)
2294 else if (BgWriterPID != 0 && !FatalError)
2297 (errmsg_internal("sending %s to process %d",
2298 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2299 (int) BgWriterPID)));
2300 kill(BgWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
2303 /* Force a power-cycle of the pgarch process too */
2304 /* (Shouldn't be necessary, but just for luck) */
2305 if (PgArchPID != 0 && !FatalError)
2308 (errmsg_internal("sending %s to process %d",
2311 kill(PgArchPID, SIGQUIT);
2314 /* Force a power-cycle of the pgstat processes too */
2315 /* (Shouldn't be necessary, but just for luck) */
2316 if (PgStatPID != 0 && !FatalError)
2319 (errmsg_internal("sending %s to process %d",
2322 kill(PgStatPID, SIGQUIT);
2325 /* We do NOT restart the syslogger */
2331 * Log the death of a child process.
2334 LogChildExit(int lev, const char *procname, int pid, int exitstatus)
2336 if (WIFEXITED(exitstatus))
2340 * translator: %s is a noun phrase describing a child process,
2341 * such as "server process"
2343 (errmsg("%s (PID %d) exited with exit code %d",
2344 procname, pid, WEXITSTATUS(exitstatus))));
2345 else if (WIFSIGNALED(exitstatus))
2349 * translator: %s is a noun phrase describing a child process,
2350 * such as "server process"
2352 (errmsg("%s (PID %d) was terminated by signal %d",
2353 procname, pid, WTERMSIG(exitstatus))));
2358 * translator: %s is a noun phrase describing a child process,
2359 * such as "server process"
2361 (errmsg("%s (PID %d) exited with unexpected status %d",
2362 procname, pid, exitstatus)));
2366 * Send a signal to all backend children (but NOT special children)
2369 SignalChildren(int signal)
2373 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2375 Backend *bp = (Backend *) DLE_VAL(curr);
2378 (errmsg_internal("sending signal %d to process %d",
2379 signal, (int) bp->pid)));
2380 kill(bp->pid, signal);
2385 * BackendStartup -- start backend process
2387 * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
2390 BackendStartup(Port *port)
2392 Backend *bn; /* for backend cleanup */
2395 #ifdef LINUX_PROFILE
2396 struct itimerval prof_itimer;
2400 * Compute the cancel key that will be assigned to this backend. The
2401 * backend will have its own copy in the forked-off process' value of
2402 * MyCancelKey, so that it can transmit the key to the frontend.
2404 MyCancelKey = PostmasterRandom();
2407 * Make room for backend data structure. Better before the fork() so
2408 * we can handle failure cleanly.
2410 bn = (Backend *) malloc(sizeof(Backend));
2414 (errcode(ERRCODE_OUT_OF_MEMORY),
2415 errmsg("out of memory")));
2416 return STATUS_ERROR;
2419 /* Pass down canAcceptConnections state (kluge for EXEC_BACKEND case) */
2420 port->canAcceptConnections = canAcceptConnections();
2423 * Flush stdio channels just before fork, to avoid double-output
2424 * problems. Ideally we'd use fflush(NULL) here, but there are still a
2425 * few non-ANSI stdio libraries out there (like SunOS 4.1.x) that
2426 * coredump if we do. Presently stdout and stderr are the only stdio
2427 * output channels used by the postmaster, so fflush'ing them should
2435 pid = backend_forkexec(port);
2437 #else /* !EXEC_BACKEND */
2439 #ifdef LINUX_PROFILE
2442 * Linux's fork() resets the profiling timer in the child process. If
2443 * we want to profile child processes then we need to save and restore
2444 * the timer setting. This is a waste of time if not profiling,
2445 * however, so only do it if commanded by specific -DLINUX_PROFILE
2448 getitimer(ITIMER_PROF, &prof_itimer);
2452 /* Specific beos actions before backend startup */
2453 beos_before_backend_startup();
2458 if (pid == 0) /* child */
2460 #ifdef LINUX_PROFILE
2461 setitimer(ITIMER_PROF, &prof_itimer, NULL);
2465 /* Specific beos backend startup actions */
2466 beos_backend_startup();
2470 proc_exit(BackendRun(port));
2472 #endif /* EXEC_BACKEND */
2476 /* in parent, fork failed */
2477 int save_errno = errno;
2480 /* Specific beos backend startup actions */
2481 beos_backend_startup_failed();
2486 (errmsg("could not fork new process for connection: %m")));
2487 report_fork_failure_to_client(port, save_errno);
2488 return STATUS_ERROR;
2491 /* in parent, successful fork */
2493 (errmsg_internal("forked new backend, pid=%d socket=%d",
2494 (int) pid, port->sock)));
2497 * Everything's been successful, it's safe to add this backend to our
2501 bn->cancel_key = MyCancelKey;
2502 DLAddHead(BackendList, DLNewElem(bn));
2504 ShmemBackendArrayAdd(bn);
2511 * Try to report backend fork() failure to client before we close the
2512 * connection. Since we do not care to risk blocking the postmaster on
2513 * this connection, we set the connection to non-blocking and try only once.
2515 * This is grungy special-purpose code; we cannot use backend libpq since
2516 * it's not up and running.
2519 report_fork_failure_to_client(Port *port, int errnum)
2523 /* Format the error message packet (always V2 protocol) */
2524 snprintf(buffer, sizeof(buffer), "E%s%s\n",
2525 gettext("could not fork new process for connection: "),
2528 /* Set port to non-blocking. Don't do send() if this fails */
2529 if (!set_noblock(port->sock))
2532 send(port->sock, buffer, strlen(buffer) + 1, 0);
2537 * split_opts -- split a string of options and append it to an argv array
2539 * NB: the string is destructively modified!
2541 * Since no current POSTGRES arguments require any quoting characters,
2542 * we can use the simple-minded tactic of assuming each set of space-
2543 * delimited characters is a separate argv element.
2545 * If you don't like that, well, we *used* to pass the whole option string
2546 * as ONE argument to execl(), which was even less intelligent...
2549 split_opts(char **argv, int *argcp, char *s)
2553 while (isspace((unsigned char) *s))
2557 argv[(*argcp)++] = s;
2558 while (*s && !isspace((unsigned char) *s))
2567 * BackendRun -- perform authentication, and if successful,
2568 * set up the backend's argument list and invoke PostgresMain()
2571 * Shouldn't return at all.
2572 * If PostgresMain() fails, return status.
2575 BackendRun(Port *port)
2580 char remote_host[NI_MAXHOST];
2581 char remote_port[NI_MAXSERV];
2582 char remote_ps_data[NI_MAXHOST];
2590 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
2593 * Let's clean up ourselves as the postmaster child, and close the
2594 * postmaster's listen sockets
2596 ClosePostmasterPorts(false);
2598 /* We don't want the postmaster's proc_exit() handlers */
2602 * Signal handlers setting is moved to tcop/postgres...
2605 /* Save port etc. for ps status */
2608 /* Reset MyProcPid to new backend's pid */
2609 MyProcPid = getpid();
2612 * PreAuthDelay is a debugging aid for investigating problems in the
2613 * authentication cycle: it can be set in postgresql.conf to allow
2614 * time to attach to the newly-forked backend with a debugger. (See
2615 * also the -W backend switch, which we allow clients to pass through
2616 * PGOPTIONS, but it is not honored until after authentication.)
2618 if (PreAuthDelay > 0)
2619 pg_usleep(PreAuthDelay * 1000000L);
2621 ClientAuthInProgress = true; /* limit visibility of log messages */
2623 /* save start time for end of session reporting */
2624 gettimeofday(&(port->session_start), NULL);
2626 /* set these to empty in case they are needed before we set them up */
2627 port->remote_host = "";
2628 port->remote_port = "";
2629 port->commandTag = "";
2632 * Initialize libpq and enable reporting of ereport errors to the
2633 * client. Must do this now because authentication uses libpq to send
2636 pq_init(); /* initialize libpq to talk to client */
2637 whereToSendOutput = Remote; /* now safe to ereport to client */
2640 * We arrange for a simple exit(0) if we receive SIGTERM or SIGQUIT
2641 * during any client authentication related communication. Otherwise
2642 * the postmaster cannot shutdown the database FAST or IMMED cleanly
2643 * if a buggy client blocks a backend during authentication.
2645 pqsignal(SIGTERM, authdie);
2646 pqsignal(SIGQUIT, authdie);
2647 pqsignal(SIGALRM, authdie);
2648 PG_SETMASK(&AuthBlockSig);
2651 * Get the remote host name and port for logging and status display.
2653 remote_host[0] = '\0';
2654 remote_port[0] = '\0';
2655 if (getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2656 remote_host, sizeof(remote_host),
2657 remote_port, sizeof(remote_port),
2658 (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV))
2660 int ret = getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2661 remote_host, sizeof(remote_host),
2662 remote_port, sizeof(remote_port),
2663 NI_NUMERICHOST | NI_NUMERICSERV);
2667 (errmsg("getnameinfo_all() failed: %s",
2668 gai_strerror(ret))));
2670 snprintf(remote_ps_data, sizeof(remote_ps_data),
2671 remote_port[0] == '\0' ? "%s" : "%s(%s)",
2672 remote_host, remote_port);
2674 if (Log_connections)
2676 (errmsg("connection received: host=%s port=%s",
2677 remote_host, remote_port)));
2680 * save remote_host and remote_port in port stucture
2682 port->remote_host = strdup(remote_host);
2683 port->remote_port = strdup(remote_port);
2686 * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.c
2687 * etcetera from the postmaster, and have to load them ourselves.
2688 * Build the PostmasterContext (which didn't exist before, in this
2689 * process) to contain the data.
2691 * FIXME: [fork/exec] Ugh. Is there a way around this overhead?
2694 Assert(PostmasterContext == NULL);
2695 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
2697 ALLOCSET_DEFAULT_MINSIZE,
2698 ALLOCSET_DEFAULT_INITSIZE,
2699 ALLOCSET_DEFAULT_MAXSIZE);
2700 MemoryContextSwitchTo(PostmasterContext);
2709 * Ready to begin client interaction. We will give up and exit(0)
2710 * after a time delay, so that a broken client can't hog a connection
2711 * indefinitely. PreAuthDelay doesn't count against the time limit.
2713 if (!enable_sig_alarm(AuthenticationTimeout * 1000, false))
2714 elog(FATAL, "could not set timer for authorization timeout");
2717 * Receive the startup packet (which might turn out to be a cancel
2720 status = ProcessStartupPacket(port, false);
2722 if (status != STATUS_OK)
2726 * Now that we have the user and database name, we can set the process
2727 * title for ps. It's good to do this as early as possible in
2730 init_ps_display(port->user_name, port->database_name, remote_ps_data);
2731 set_ps_display("authentication");
2734 * Now perform authentication exchange.
2736 ClientAuthentication(port); /* might not return, if failure */
2739 * Done with authentication. Disable timeout, and prevent
2740 * SIGTERM/SIGQUIT again until backend startup is complete.
2742 if (!disable_sig_alarm(false))
2743 elog(FATAL, "could not disable timer for authorization timeout");
2744 PG_SETMASK(&BlockSig);
2746 if (Log_connections)
2748 (errmsg("connection authorized: user=%s database=%s",
2749 port->user_name, port->database_name)));
2752 * Don't want backend to be able to see the postmaster random number
2753 * generator state. We have to clobber the static random_seed *and*
2754 * start a new random sequence in the random() library function.
2757 gettimeofday(&now, &tz);
2758 srandom((unsigned int) now.tv_usec);
2762 * Now, build the argv vector that will be given to PostgresMain.
2764 * The layout of the command line is
2765 * postgres [secure switches] -p databasename [insecure switches]
2766 * where the switches after -p come from the client request.
2768 * The maximum possible number of commandline arguments that could come
2769 * from ExtraOptions or port->cmdline_options is (strlen + 1) / 2; see
2773 maxac = 10; /* for fixed args supplied below */
2774 maxac += (strlen(ExtraOptions) + 1) / 2;
2775 if (port->cmdline_options)
2776 maxac += (strlen(port->cmdline_options) + 1) / 2;
2778 av = (char **) MemoryContextAlloc(TopMemoryContext,
2779 maxac * sizeof(char *));
2782 av[ac++] = "postgres";
2785 * Pass the requested debugging level along to the backend.
2789 snprintf(debugbuf, sizeof(debugbuf), "-d%d", debug_flag);
2790 av[ac++] = debugbuf;
2794 * Pass any backend switches specified with -o in the postmaster's own
2795 * command line. We assume these are secure. (It's OK to mangle
2796 * ExtraOptions now, since we're safely inside a subprocess.)
2798 split_opts(av, &ac, ExtraOptions);
2800 /* Tell the backend what protocol the frontend is using. */
2801 snprintf(protobuf, sizeof(protobuf), "-v%u", port->proto);
2802 av[ac++] = protobuf;
2805 * Tell the backend it is being called from the postmaster, and which
2806 * database to use. -p marks the end of secure switches.
2809 av[ac++] = port->database_name;
2812 * Pass the (insecure) option switches from the connection request.
2813 * (It's OK to mangle port->cmdline_options now.)
2815 if (port->cmdline_options)
2816 split_opts(av, &ac, port->cmdline_options);
2823 * Release postmaster's working memory context so that backend can
2824 * recycle the space. Note this does not trash *MyProcPort, because
2825 * ConnCreate() allocated that space with malloc() ... else we'd need
2826 * to copy the Port data here. Also, subsidiary data such as the
2827 * username isn't lost either; see ProcessStartupPacket().
2829 MemoryContextSwitchTo(TopMemoryContext);
2830 MemoryContextDelete(PostmasterContext);
2831 PostmasterContext = NULL;
2834 * Debug: print arguments being passed to backend
2837 (errmsg_internal("%s child[%d]: starting with (",
2838 progname, getpid())));
2839 for (i = 0; i < ac; ++i)
2841 (errmsg_internal("\t%s", av[i])));
2843 (errmsg_internal(")")));
2845 ClientAuthInProgress = false; /* client_min_messages is active
2848 return (PostgresMain(ac, av, port->user_name));
2855 * postmaster_forkexec -- fork and exec a postmaster subprocess
2857 * The caller must have set up the argv array already, except for argv[2]
2858 * which will be filled with the name of the temp variable file.
2860 * Returns the child process PID, or -1 on fork failure (a suitable error
2861 * message has been logged on failure).
2863 * All uses of this routine will dispatch to SubPostmasterMain in the
2867 postmaster_forkexec(int argc, char *argv[])
2871 /* This entry point passes dummy values for the Port variables */
2872 memset(&port, 0, sizeof(port));
2873 return internal_forkexec(argc, argv, &port);
2877 * backend_forkexec -- fork/exec off a backend process
2879 * returns the pid of the fork/exec'd process, or -1 on failure
2882 backend_forkexec(Port *port)
2887 av[ac++] = "postgres";
2888 av[ac++] = "-forkbackend";
2889 av[ac++] = NULL; /* filled in by internal_forkexec */
2892 Assert(ac < lengthof(av));
2894 return internal_forkexec(ac, av, port);
2898 internal_forkexec(int argc, char *argv[], Port *port)
2901 char tmpfilename[MAXPGPATH];
2903 if (!write_backend_variables(tmpfilename, port))
2904 return -1; /* log made by write_backend_variables */
2906 /* Make sure caller set up argv properly */
2908 Assert(argv[argc] == NULL);
2909 Assert(strncmp(argv[1], "-fork", 5) == 0);
2910 Assert(argv[2] == NULL);
2912 /* Insert temp file name after -fork argument */
2913 argv[2] = tmpfilename;
2916 pid = win32_forkexec(postgres_exec_path, argv);
2918 /* Fire off execv in child */
2919 if ((pid = fork()) == 0)
2921 if (execv(postgres_exec_path, argv) < 0)
2924 (errmsg("could not exec backend process \"%s\": %m",
2925 postgres_exec_path)));
2926 /* We're already in the child process here, can't return */
2932 return pid; /* Parent returns pid, or -1 on fork
2937 * SubPostmasterMain -- Get the fork/exec'd process into a state equivalent
2938 * to what it would be if we'd simply forked on Unix, and then
2939 * dispatch to the appropriate place.
2941 * The first two command line arguments are expected to be "-forkFOO"
2942 * (where FOO indicates which postmaster child we are to become), and
2943 * the name of a variables file that we can read to load data that would
2944 * have been inherited by fork() on Unix. Remaining arguments go to the
2945 * subprocess FooMain() routine.
2948 SubPostmasterMain(int argc, char *argv[])
2952 /* Do this sooner rather than later... */
2953 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
2955 MyProcPid = getpid(); /* reset MyProcPid */
2957 /* In EXEC_BACKEND case we will not have inherited these settings */
2958 IsPostmasterEnvironment = true;
2959 whereToSendOutput = None;
2961 PG_SETMASK(&BlockSig);
2963 /* Setup essential subsystems */
2964 MemoryContextInit();
2965 InitializeGUCOptions();
2967 /* Check we got appropriate args */
2969 elog(FATAL, "invalid subpostmaster invocation");
2971 /* Read in file-based context */
2972 memset(&port, 0, sizeof(Port));
2973 read_backend_variables(argv[2], &port);
2974 read_nondefault_variables();
2976 /* Run backend or appropriate child */
2977 if (strcmp(argv[1], "-forkbackend") == 0)
2979 /* BackendRun will close sockets */
2981 /* Attach process to shared segments */
2982 CreateSharedMemoryAndSemaphores(false, MaxBackends, 0);
2986 * Need to reinitialize the SSL library in the backend,
2987 * since the context structures contain function pointers
2988 * and cannot be passed through the parameter file.
2991 secure_initialize();
2994 Assert(argc == 3); /* shouldn't be any more args */
2995 proc_exit(BackendRun(&port));
2997 if (strcmp(argv[1], "-forkboot") == 0)
2999 /* Close the postmaster's sockets */
3000 ClosePostmasterPorts(false);
3002 /* Attach process to shared segments */
3003 CreateSharedMemoryAndSemaphores(false, MaxBackends, 0);
3005 BootstrapMain(argc - 2, argv + 2);
3008 if (strcmp(argv[1], "-forkarch") == 0)
3010 /* Close the postmaster's sockets */
3011 ClosePostmasterPorts(false);
3013 /* Do not want to attach to shared memory */
3015 PgArchiverMain(argc, argv);
3018 if (strcmp(argv[1], "-forkbuf") == 0)
3020 /* Close the postmaster's sockets */
3021 ClosePostmasterPorts(false);
3023 /* Do not want to attach to shared memory */
3025 PgstatBufferMain(argc, argv);
3028 if (strcmp(argv[1], "-forkcol") == 0)
3031 * Do NOT close postmaster sockets here, because we are forking
3032 * from pgstat buffer process, which already did it.
3035 /* Do not want to attach to shared memory */
3037 PgstatCollectorMain(argc, argv);
3040 if (strcmp(argv[1], "-forklog") == 0)
3042 /* Close the postmaster's sockets */
3043 ClosePostmasterPorts(true);
3045 /* Do not want to attach to shared memory */
3047 SysLoggerMain(argc, argv);
3051 return 1; /* shouldn't get here */
3053 #endif /* EXEC_BACKEND */
3057 * ExitPostmaster -- cleanup
3059 * Do NOT call exit() directly --- always go through here!
3062 ExitPostmaster(int status)
3064 /* should cleanup shared memory and kill all backends */
3067 * Not sure of the semantics here. When the Postmaster dies, should
3068 * the backends all be killed? probably not.
3070 * MUST -- vadim 05-10-1999
3077 * sigusr1_handler - handle signal conditions from child processes
3080 sigusr1_handler(SIGNAL_ARGS)
3082 int save_errno = errno;
3084 PG_SETMASK(&BlockSig);
3086 if (CheckPostmasterSignal(PMSIGNAL_PASSWORD_CHANGE))
3089 * Password or group file has changed.
3095 if (CheckPostmasterSignal(PMSIGNAL_WAKEN_CHILDREN))
3098 * Send SIGUSR1 to all children (triggers
3099 * CatchupInterruptHandler). See storage/ipc/sinval[adt].c for the
3102 if (Shutdown <= SmartShutdown)
3103 SignalChildren(SIGUSR1);
3106 if (PgArchPID != 0 && Shutdown == NoShutdown)
3108 if (CheckPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER))
3111 * Send SIGUSR1 to archiver process, to wake it up and begin
3112 * archiving next transaction log file.
3114 kill(PgArchPID, SIGUSR1);
3118 PG_SETMASK(&UnBlockSig);
3125 * Dummy signal handler
3127 * We use this for signals that we don't actually use in the postmaster,
3128 * but we do use in backends. If we were to SIG_IGN such signals in the
3129 * postmaster, then a newly started backend might drop a signal that arrives
3130 * before it's able to reconfigure its signal processing. (See notes in
3134 dummy_handler(SIGNAL_ARGS)
3140 * CharRemap: given an int in range 0..61, produce textual encoding of it
3141 * per crypt(3) conventions.
3165 RandomSalt(char *cryptSalt, char *md5Salt)
3167 long rand = PostmasterRandom();
3169 cryptSalt[0] = CharRemap(rand % 62);
3170 cryptSalt[1] = CharRemap(rand / 62);
3173 * It's okay to reuse the first random value for one of the MD5 salt
3174 * bytes, since only one of the two salts will be sent to the client.
3175 * After that we need to compute more random bits.
3177 * We use % 255, sacrificing one possible byte value, so as to ensure
3178 * that all bits of the random() value participate in the result.
3179 * While at it, add one to avoid generating any null bytes.
3181 md5Salt[0] = (rand % 255) + 1;
3182 rand = PostmasterRandom();
3183 md5Salt[1] = (rand % 255) + 1;
3184 rand = PostmasterRandom();
3185 md5Salt[2] = (rand % 255) + 1;
3186 rand = PostmasterRandom();
3187 md5Salt[3] = (rand % 255) + 1;
3194 PostmasterRandom(void)
3196 static bool initialized = false;
3200 Assert(random_seed != 0);
3201 srandom(random_seed);
3209 * Count up number of child processes (regular backends only)
3217 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
3224 * StartChildProcess -- start a non-backend child process for the postmaster
3226 * xlog determines what kind of child will be started. All child types
3227 * initially go to BootstrapMain, which will handle common setup.
3229 * Return value of StartChildProcess is subprocess' PID, or 0 if failed
3230 * to start subprocess.
3233 StartChildProcess(int xlop)
3240 #ifdef LINUX_PROFILE
3241 struct itimerval prof_itimer;
3245 * Set up command-line arguments for subprocess
3247 av[ac++] = "postgres";
3250 av[ac++] = "-forkboot";
3251 av[ac++] = NULL; /* filled in by postmaster_forkexec */
3254 snprintf(xlbuf, sizeof(xlbuf), "-x%d", xlop);
3258 av[ac++] = "template1";
3261 Assert(ac < lengthof(av));
3264 * Flush stdio channels (see comments in BackendStartup)
3271 pid = postmaster_forkexec(ac, av);
3273 #else /* !EXEC_BACKEND */
3275 #ifdef LINUX_PROFILE
3276 /* see comments in BackendStartup */
3277 getitimer(ITIMER_PROF, &prof_itimer);
3281 /* Specific beos actions before backend startup */
3282 beos_before_backend_startup();
3287 if (pid == 0) /* child */
3289 #ifdef LINUX_PROFILE
3290 setitimer(ITIMER_PROF, &prof_itimer, NULL);
3294 /* Specific beos actions after backend startup */
3295 beos_backend_startup();
3298 IsUnderPostmaster = true; /* we are a postmaster subprocess
3301 /* Close the postmaster's sockets */
3302 ClosePostmasterPorts(false);
3304 /* Lose the postmaster's on-exit routines and port connections */
3307 /* Release postmaster's working memory context */
3308 MemoryContextSwitchTo(TopMemoryContext);
3309 MemoryContextDelete(PostmasterContext);
3310 PostmasterContext = NULL;
3312 BootstrapMain(ac, av);
3315 #endif /* EXEC_BACKEND */
3319 /* in parent, fork failed */
3320 int save_errno = errno;
3323 /* Specific beos actions before backend startup */
3324 beos_backend_startup_failed();
3329 case BS_XLOG_STARTUP:
3331 (errmsg("could not fork startup process: %m")));
3333 case BS_XLOG_BGWRITER:
3335 (errmsg("could not fork background writer process: %m")));
3339 (errmsg("could not fork process: %m")));
3344 * fork failure is fatal during startup, but there's no need to
3345 * choke immediately if starting other child types fails.
3347 if (xlop == BS_XLOG_STARTUP)
3353 * in parent, successful fork
3360 * Create the opts file
3363 CreateOptsFile(int argc, char *argv[], char *fullprogname)
3365 char filename[MAXPGPATH];
3369 snprintf(filename, sizeof(filename), "%s/postmaster.opts", DataDir);
3371 if ((fp = fopen(filename, "w")) == NULL)
3373 elog(LOG, "could not create file \"%s\": %m", filename);
3377 fprintf(fp, "%s", fullprogname);
3378 for (i = 1; i < argc; i++)
3379 fprintf(fp, " '%s'", argv[i]);
3384 elog(LOG, "could not write file \"%s\": %m", filename);
3395 * The following need to be available to the read/write_backend_variables
3398 #include "storage/spin.h"
3400 extern slock_t *ShmemLock;
3401 extern slock_t *ShmemIndexLock;
3402 extern void *ShmemIndexAlloc;
3403 typedef struct LWLock LWLock;
3404 extern LWLock *LWLockArray;
3405 extern slock_t *ProcStructLock;
3406 extern int pgStatSock;
3408 #define write_var(var,fp) fwrite((void*)&(var),sizeof(var),1,fp)
3409 #define read_var(var,fp) fread((void*)&(var),sizeof(var),1,fp)
3410 #define write_array_var(var,fp) fwrite((void*)(var),sizeof(var),1,fp)
3411 #define read_array_var(var,fp) fread((void*)(var),sizeof(var),1,fp)
3414 write_backend_variables(char *filename, Port *port)
3416 static unsigned long tmpBackendFileNum = 0;
3418 char str_buf[MAXPGPATH];
3420 /* Calculate name for temp file in caller's buffer */
3422 snprintf(filename, MAXPGPATH, "%s/%s/%s.backend_var.%d.%lu",
3423 DataDir, PG_TEMP_FILES_DIR, PG_TEMP_FILE_PREFIX,
3424 MyProcPid, ++tmpBackendFileNum);
3427 fp = AllocateFile(filename, PG_BINARY_W);
3430 /* As per OpenTemporaryFile... */
3431 char dirname[MAXPGPATH];
3433 snprintf(dirname, MAXPGPATH, "%s/%s", DataDir, PG_TEMP_FILES_DIR);
3434 mkdir(dirname, S_IRWXU);
3436 fp = AllocateFile(filename, PG_BINARY_W);
3440 (errcode_for_file_access(),
3441 errmsg("could not create file \"%s\": %m",
3448 write_var(port->sock, fp);
3449 write_var(port->proto, fp);
3450 write_var(port->laddr, fp);
3451 write_var(port->raddr, fp);
3452 write_var(port->canAcceptConnections, fp);
3453 write_var(port->cryptSalt, fp);
3454 write_var(port->md5Salt, fp);
3457 * XXX FIXME later: writing these strings as MAXPGPATH bytes always is
3458 * probably a waste of resources
3461 StrNCpy(str_buf, DataDir, MAXPGPATH);
3462 write_array_var(str_buf, fp);
3464 write_array_var(ListenSocket, fp);
3466 write_var(MyCancelKey, fp);
3468 write_var(UsedShmemSegID, fp);
3469 write_var(UsedShmemSegAddr, fp);
3471 write_var(ShmemLock, fp);
3472 write_var(ShmemIndexLock, fp);
3473 write_var(ShmemVariableCache, fp);
3474 write_var(ShmemIndexAlloc, fp);
3475 write_var(ShmemBackendArray, fp);
3477 write_var(LWLockArray, fp);
3478 write_var(ProcStructLock, fp);
3479 write_var(pgStatSock, fp);
3481 write_var(debug_flag, fp);
3482 write_var(PostmasterPid, fp);
3484 write_var(PostmasterHandle, fp);
3487 write_var(syslogPipe[0], fp);
3488 write_var(syslogPipe[1], fp);
3490 StrNCpy(str_buf, my_exec_path, MAXPGPATH);
3491 write_array_var(str_buf, fp);
3493 write_array_var(ExtraOptions, fp);
3495 StrNCpy(str_buf, setlocale(LC_COLLATE, NULL), MAXPGPATH);
3496 write_array_var(str_buf, fp);
3497 StrNCpy(str_buf, setlocale(LC_CTYPE, NULL), MAXPGPATH);
3498 write_array_var(str_buf, fp);
3504 (errcode_for_file_access(),
3505 errmsg("could not write to file \"%s\": %m", filename)));
3513 read_backend_variables(char *filename, Port *port)
3516 char str_buf[MAXPGPATH];
3519 fp = AllocateFile(filename, PG_BINARY_R);
3522 (errcode_for_file_access(),
3523 errmsg("could not read from backend variables file \"%s\": %m",
3527 read_var(port->sock, fp);
3528 read_var(port->proto, fp);
3529 read_var(port->laddr, fp);
3530 read_var(port->raddr, fp);
3531 read_var(port->canAcceptConnections, fp);
3532 read_var(port->cryptSalt, fp);
3533 read_var(port->md5Salt, fp);
3535 read_array_var(str_buf, fp);
3536 SetDataDir(str_buf);
3538 read_array_var(ListenSocket, fp);
3540 read_var(MyCancelKey, fp);
3542 read_var(UsedShmemSegID, fp);
3543 read_var(UsedShmemSegAddr, fp);
3545 read_var(ShmemLock, fp);
3546 read_var(ShmemIndexLock, fp);
3547 read_var(ShmemVariableCache, fp);
3548 read_var(ShmemIndexAlloc, fp);
3549 read_var(ShmemBackendArray, fp);
3551 read_var(LWLockArray, fp);
3552 read_var(ProcStructLock, fp);
3553 read_var(pgStatSock, fp);
3555 read_var(debug_flag, fp);
3556 read_var(PostmasterPid, fp);
3558 read_var(PostmasterHandle, fp);
3561 read_var(syslogPipe[0], fp);
3562 read_var(syslogPipe[1], fp);
3564 read_array_var(str_buf, fp);
3565 StrNCpy(my_exec_path, str_buf, MAXPGPATH);
3567 read_array_var(ExtraOptions, fp);
3569 read_array_var(str_buf, fp);
3570 setlocale(LC_COLLATE, str_buf);
3571 read_array_var(str_buf, fp);
3572 setlocale(LC_CTYPE, str_buf);
3576 if (unlink(filename) != 0)
3578 (errcode_for_file_access(),
3579 errmsg("could not remove file \"%s\": %m", filename)));
3584 ShmemBackendArraySize(void)
3586 return (NUM_BACKENDARRAY_ELEMS * sizeof(Backend));
3590 ShmemBackendArrayAllocation(void)
3592 size_t size = ShmemBackendArraySize();
3594 ShmemBackendArray = (Backend *) ShmemAlloc(size);
3595 /* Mark all slots as empty */
3596 memset(ShmemBackendArray, 0, size);
3600 ShmemBackendArrayAdd(Backend *bn)
3604 /* Find an empty slot */
3605 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
3607 if (ShmemBackendArray[i].pid == 0)
3609 ShmemBackendArray[i] = *bn;
3615 (errmsg_internal("no free slots in shmem backend array")));
3619 ShmemBackendArrayRemove(pid_t pid)
3623 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
3625 if (ShmemBackendArray[i].pid == pid)
3627 /* Mark the slot as empty */
3628 ShmemBackendArray[i].pid = 0;
3634 (errmsg_internal("could not find backend entry with pid %d",
3637 #endif /* EXEC_BACKEND */
3643 win32_forkexec(const char *path, char *argv[])
3646 PROCESS_INFORMATION pi;
3649 char cmdLine[MAXPGPATH * 2];
3650 HANDLE childHandleCopy;
3651 HANDLE waiterThread;
3653 /* Format the cmd line */
3654 cmdLine[sizeof(cmdLine) - 1] = '\0';
3655 cmdLine[sizeof(cmdLine) - 2] = '\0';
3656 snprintf(cmdLine, sizeof(cmdLine) - 1, "\"%s\"", path);
3658 while (argv[++i] != NULL)
3660 j = strlen(cmdLine);
3661 snprintf(cmdLine + j, sizeof(cmdLine) - 1 - j, " \"%s\"", argv[i]);
3663 if (cmdLine[sizeof(cmdLine) - 2] != '\0')
3665 elog(LOG, "subprocess command line too long");
3669 memset(&pi, 0, sizeof(pi));
3670 memset(&si, 0, sizeof(si));
3672 if (!CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
3674 elog(LOG, "CreateProcess call failed (%d): %m", (int) GetLastError());
3678 if (!IsUnderPostmaster)
3680 /* We are the Postmaster creating a child... */
3681 win32_AddChild(pi.dwProcessId, pi.hProcess);
3684 if (DuplicateHandle(GetCurrentProcess(),
3686 GetCurrentProcess(),
3690 DUPLICATE_SAME_ACCESS) == 0)
3692 (errmsg_internal("could not duplicate child handle: %d",
3693 (int) GetLastError())));
3695 waiterThread = CreateThread(NULL, 64 * 1024, win32_sigchld_waiter,
3696 (LPVOID) childHandleCopy, 0, NULL);
3699 (errmsg_internal("could not create sigchld waiter thread: %d",
3700 (int) GetLastError())));
3701 CloseHandle(waiterThread);
3703 if (IsUnderPostmaster)
3704 CloseHandle(pi.hProcess);
3705 CloseHandle(pi.hThread);
3707 return pi.dwProcessId;
3711 * Note: The following three functions must not be interrupted (eg. by
3712 * signals). As the Postgres Win32 signalling architecture (currently)
3713 * requires polling, or APC checking functions which aren't used here, this
3716 * We keep two separate arrays, instead of a single array of pid/HANDLE
3717 * structs, to avoid having to re-create a handle array for
3718 * WaitForMultipleObjects on each call to win32_waitpid.
3722 win32_AddChild(pid_t pid, HANDLE handle)
3724 Assert(win32_childPIDArray && win32_childHNDArray);
3725 if (win32_numChildren < NUM_BACKENDARRAY_ELEMS)
3727 win32_childPIDArray[win32_numChildren] = pid;
3728 win32_childHNDArray[win32_numChildren] = handle;
3729 ++win32_numChildren;
3733 (errmsg_internal("no room for child entry with pid %lu",
3734 (unsigned long) pid)));
3738 win32_RemoveChild(pid_t pid)
3742 Assert(win32_childPIDArray && win32_childHNDArray);
3744 for (i = 0; i < win32_numChildren; i++)
3746 if (win32_childPIDArray[i] == pid)
3748 CloseHandle(win32_childHNDArray[i]);
3750 /* Swap last entry into the "removed" one */
3751 --win32_numChildren;
3752 win32_childPIDArray[i] = win32_childPIDArray[win32_numChildren];
3753 win32_childHNDArray[i] = win32_childHNDArray[win32_numChildren];
3759 (errmsg_internal("could not find child entry with pid %lu",
3760 (unsigned long) pid)));
3764 win32_waitpid(int *exitstatus)
3767 * Note: Do NOT use WaitForMultipleObjectsEx, as we don't want to run
3773 unsigned long offset;
3775 Assert(win32_childPIDArray && win32_childHNDArray);
3776 elog(DEBUG3, "waiting on %lu children", win32_numChildren);
3778 for (offset = 0; offset < win32_numChildren; offset += MAXIMUM_WAIT_OBJECTS)
3780 unsigned long num = min(MAXIMUM_WAIT_OBJECTS, win32_numChildren - offset);
3782 ret = WaitForMultipleObjects(num, &win32_childHNDArray[offset], FALSE, 0);
3787 (errmsg_internal("failed to wait on %lu of %lu children: %d",
3788 num, win32_numChildren, (int) GetLastError())));
3792 /* No children (in this chunk) have finished */
3798 * Get the exit code, and return the PID of, the
3799 * respective process
3801 index = offset + ret - WAIT_OBJECT_0;
3802 Assert(index >= 0 && index < win32_numChildren);
3803 if (!GetExitCodeProcess(win32_childHNDArray[index], &exitCode))
3806 * If we get this far, this should never happen, but,
3807 * then again... No choice other than to assume a
3808 * catastrophic failure.
3811 (errmsg_internal("failed to get exit code for child %lu",
3812 win32_childPIDArray[index])));
3814 *exitstatus = (int) exitCode;
3815 return win32_childPIDArray[index];
3819 /* No children have finished */
3824 * Note! Code below executes on separate threads, one for
3825 * each child process created
3828 win32_sigchld_waiter(LPVOID param)
3830 HANDLE procHandle = (HANDLE) param;
3832 DWORD r = WaitForSingleObject(procHandle, INFINITE);
3834 if (r == WAIT_OBJECT_0)
3835 pg_queue_signal(SIGCHLD);
3837 write_stderr("ERROR: failed to wait on child process handle: %d\n",
3838 (int) GetLastError());
3839 CloseHandle(procHandle);