1 /*-------------------------------------------------------------------------
4 * This program acts as a clearing house for requests to the
5 * POSTGRES system. Frontend programs send a startup message
6 * to the Postmaster and the postmaster uses the info in the
7 * message to setup a backend process.
9 * The postmaster also manages system-wide operations such as
10 * startup, shutdown, and periodic checkpoints. The postmaster
11 * itself doesn't do those operations, mind you --- it just forks
12 * off a subprocess to do them at the right times. It also takes
13 * care of resetting the system if a backend crashes.
15 * The postmaster process creates the shared memory and semaphore
16 * pools during startup, but as a rule does not touch them itself.
17 * In particular, it is not a member of the PGPROC array of backends
18 * and so it cannot participate in lock-manager operations. Keeping
19 * the postmaster away from shared memory operations makes it simpler
20 * and more reliable. The postmaster is almost always able to recover
21 * from crashes of individual backends by resetting shared memory;
22 * if it did much with shared memory then it would be prone to crashing
23 * along with the backends.
25 * When a request message is received, we now fork() immediately.
26 * The child process performs authentication of the request, and
27 * then becomes a backend if successful. This allows the auth code
28 * to be written in a simple single-threaded style (as opposed to the
29 * crufty "poor man's multitasking" code that used to be needed).
30 * More importantly, it ensures that blockages in non-multithreaded
31 * libraries like SSL or PAM cannot cause denial of service to other
35 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
36 * Portions Copyright (c) 1994, Regents of the University of California
40 * $PostgreSQL: pgsql/src/backend/postmaster/postmaster.c,v 1.358 2004/01/11 03:49:31 momjian Exp $
45 * The Postmaster sets up a few shared memory data structures
46 * for the backends. It should at the very least initialize the
50 * The Postmaster shares memory with the backends but should avoid
51 * touching shared memory, so as not to become stuck if a crashing
52 * backend screws up locks or shared memory. Likewise, the Postmaster
53 * should never block on messages from frontend clients.
56 * The Postmaster cleans up after backends if they have an emergency
57 * exit and/or core dump.
59 *-------------------------------------------------------------------------
70 #include <sys/socket.h>
74 #include <sys/param.h>
75 #include <netinet/in.h>
76 #include <arpa/inet.h>
80 #ifdef HAVE_SYS_SELECT_H
81 #include <sys/select.h>
89 #include <DNSServiceDiscovery/DNSServiceDiscovery.h>
92 #include "catalog/pg_database.h"
93 #include "commands/async.h"
94 #include "lib/dllist.h"
95 #include "libpq/auth.h"
96 #include "libpq/crypt.h"
97 #include "libpq/libpq.h"
98 #include "libpq/pqcomm.h"
99 #include "libpq/pqsignal.h"
100 #include "miscadmin.h"
101 #include "nodes/nodes.h"
102 #include "storage/fd.h"
103 #include "storage/ipc.h"
104 #include "storage/pg_shmem.h"
105 #include "storage/pmsignal.h"
106 #include "storage/proc.h"
107 #include "storage/bufmgr.h"
108 #include "access/xlog.h"
109 #include "tcop/tcopprot.h"
110 #include "utils/guc.h"
111 #include "utils/memutils.h"
112 #include "utils/ps_status.h"
113 #include "bootstrap/bootstrap.h"
117 #define INVALID_SOCK (-1)
119 #ifdef HAVE_SIGPROCMASK
131 * List of active backends (or child processes anyway; we don't actually
132 * know whether a given child has become a backend or is still in the
133 * authorization phase). This is used mainly to keep track of how many
134 * children we have and send them appropriate signals when necessary.
138 pid_t pid; /* process id of backend */
139 long cancel_key; /* cancel key for cancels for this backend */
142 static Dllist *BackendList;
144 /* The socket number we are listening for connections on */
150 * MaxBackends is the limit on the number of backends we can start.
151 * Note that a larger MaxBackends value will increase the size of the
152 * shared memory area as well as cause the postmaster to grab more
153 * kernel semaphores, even if you never actually use that many
159 * ReservedBackends is the number of backends reserved for superuser use.
160 * This number is taken out of the pool size given by MaxBackends so
161 * number of backend slots available to non-superusers is
162 * (MaxBackends - ReservedBackends). Note what this really means is
163 * "if there are <= ReservedBackends connections available, only superusers
164 * can make new connections" --- pre-existing superuser connections don't
165 * count against the limit.
167 int ReservedBackends;
170 static char *progname = NULL;
172 /* The socket(s) we're listening to. */
174 static int ListenSocket[MAXLISTEN];
176 /* Used to reduce macros tests */
178 const bool ExecBackend = true;
181 const bool ExecBackend = false;
185 * Set by the -o option
187 static char ExtraOptions[MAXPGPATH];
190 * These globals control the behavior of the postmaster in case some
191 * backend dumps core. Normally, it kills all peers of the dead backend
192 * and reinitializes shared memory. By specifying -s or -n, we can have
193 * the postmaster stop (rather than kill) peers and not reinitialize
194 * shared data structures.
196 static bool Reinit = true;
197 static int SendStop = false;
199 /* still more option variables */
200 bool NetServer = false; /* listen on TCP/IP */
201 bool EnableSSL = false;
202 bool SilentMode = false; /* silent mode (-S) */
204 int PreAuthDelay = 0;
205 int AuthenticationTimeout = 60;
206 int CheckPointTimeout = 300;
207 int CheckPointWarning = 30;
208 time_t LastSignalledCheckpoint = 0;
210 bool log_hostname; /* for ps display */
212 bool Log_connections = false;
213 bool Db_user_namespace = false;
215 char *rendezvous_name;
217 /* For FNCTL_NONBLOCK */
218 #if defined(WIN32) || defined(__BEOS__)
219 long ioctlsocket_ret=1;
222 /* list of library:init-function to be preloaded */
223 char *preload_libraries_string = NULL;
225 /* Startup/shutdown state */
226 static pid_t StartupPID = 0,
230 static time_t checkpointed = 0;
233 #define SmartShutdown 1
234 #define FastShutdown 2
236 static int Shutdown = NoShutdown;
238 static bool FatalError = false; /* T if recovering from backend crash */
240 bool ClientAuthInProgress = false; /* T during new-client
244 * State for assigning random salts and cancel keys.
245 * Also, the global MyCancelKey passes the cancel key assigned to a given
246 * backend from the postmaster to that backend (via fork).
249 static unsigned int random_seed = 0;
251 static int debug_flag = 0;
257 #ifdef HAVE_INT_OPTRESET
262 * postmaster.c - function prototypes
264 static void pmdaemonize(int argc, char *argv[]);
265 static Port *ConnCreate(int serverFd);
266 static void ConnFree(Port *port);
267 static void reset_shared(unsigned short port);
268 static void SIGHUP_handler(SIGNAL_ARGS);
269 static void pmdie(SIGNAL_ARGS);
270 static void reaper(SIGNAL_ARGS);
271 static void sigusr1_handler(SIGNAL_ARGS);
272 static void dummy_handler(SIGNAL_ARGS);
273 static void CleanupProc(int pid, int exitstatus);
274 static void LogChildExit(int lev, const char *procname,
275 int pid, int exitstatus);
276 static void BackendInit(Port *port);
277 static int BackendRun(Port *port);
278 static void ExitPostmaster(int status);
279 static void usage(const char *);
280 static int ServerLoop(void);
281 static int BackendStartup(Port *port);
282 static int ProcessStartupPacket(Port *port, bool SSLdone);
283 static void processCancelRequest(Port *port, void *pkt);
284 static int initMasks(fd_set *rmask);
285 static void report_fork_failure_to_client(Port *port, int errnum);
286 static enum CAC_state canAcceptConnections(void);
287 static long PostmasterRandom(void);
288 static void RandomSalt(char *cryptSalt, char *md5Salt);
289 static void SignalChildren(int signal);
290 static int CountChildren(void);
291 static bool CreateOptsFile(int argc, char *argv[]);
292 NON_EXEC_STATIC void SSDataBaseInit(int xlop);
293 static pid_t SSDataBase(int xlop);
295 postmaster_error(const char *fmt,...)
296 /* This lets gcc check the format string for consistency. */
297 __attribute__((format(printf, 1, 2)));
301 pid_t win32_forkexec(const char* path, char *argv[]);
304 static pid_t Backend_forkexec(Port *port);
306 static unsigned long tmpBackendFileNum = 0;
307 void read_backend_variables(unsigned long id, Port *port);
308 static bool write_backend_variables(Port *port);
311 #define StartupDataBase() SSDataBase(BS_XLOG_STARTUP)
312 #define CheckPointDataBase() SSDataBase(BS_XLOG_CHECKPOINT)
313 #define StartBackgroundWriter() SSDataBase(BS_XLOG_BGWRITER)
314 #define ShutdownDataBase() SSDataBase(BS_XLOG_SHUTDOWN)
318 checkDataDir(const char *checkdir)
320 char path[MAXPGPATH];
322 struct stat stat_buf;
324 if (checkdir == NULL)
327 gettext("%s does not know where to find the database system data.\n"
328 "You must specify the directory that contains the database system\n"
329 "either by specifying the -D invocation option or by setting the\n"
330 "PGDATA environment variable.\n"),
335 if (stat(checkdir, &stat_buf) == -1)
339 (errcode_for_file_access(),
340 errmsg("data directory \"%s\" does not exist",
344 (errcode_for_file_access(),
345 errmsg("could not read permissions of directory \"%s\": %m",
350 * Check if the directory has group or world access. If so, reject.
352 * XXX temporarily suppress check when on Windows, because there may not
353 * be proper support for Unix-y file permissions. Need to think of a
354 * reasonable check to apply on Windows.
356 #if !defined(__CYGWIN__) && !defined(WIN32)
357 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
359 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
360 errmsg("data directory \"%s\" has group or world access",
362 errdetail("Permissions should be u=rwx (0700).")));
365 /* Look for PG_VERSION before looking for pg_control */
366 ValidatePgVersion(checkdir);
368 snprintf(path, sizeof(path), "%s/global/pg_control", checkdir);
370 fp = AllocateFile(path, PG_BINARY_R);
374 gettext("%s: could not find the database system\n"
375 "Expected to find it in the directory \"%s\",\n"
376 "but could not open file \"%s\": %s\n"),
377 progname, checkdir, path, strerror(errno));
384 #ifdef USE_RENDEZVOUS
386 /* reg_reply -- empty callback function for DNSServiceRegistrationCreate() */
388 reg_reply(DNSServiceRegistrationReplyErrorType errorCode, void *context)
395 PostmasterMain(int argc, char *argv[])
399 char original_extraoptions[MAXPGPATH];
400 char *potential_DataDir = NULL;
403 *original_extraoptions = '\0';
407 IsPostmasterEnvironment = true;
410 * Catch standard options before doing much else. This even works on
411 * systems without getopt_long.
415 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
420 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
422 puts("postmaster (PostgreSQL) " PG_VERSION);
428 * for security, no dir or file created can be group or other
431 umask((mode_t) 0077);
433 MyProcPid = getpid();
436 * Fire up essential subsystems: memory management
441 * By default, palloc() requests in the postmaster will be allocated
442 * in the PostmasterContext, which is space that can be recycled by
443 * backends. Allocated data that needs to be available to backends
444 * should be allocated in TopMemoryContext.
446 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
448 ALLOCSET_DEFAULT_MINSIZE,
449 ALLOCSET_DEFAULT_INITSIZE,
450 ALLOCSET_DEFAULT_MAXSIZE);
451 MemoryContextSwitchTo(PostmasterContext);
453 IgnoreSystemIndexes(false);
458 InitializeGUCOptions();
460 potential_DataDir = getenv("PGDATA"); /* default value */
464 while ((opt = getopt(argc, argv, "A:a:B:b:c:D:d:Fh:ik:lm:MN:no:p:Ss-:")) != -1)
469 #ifdef USE_ASSERT_CHECKING
470 SetConfigOption("debug_assertions", optarg, PGC_POSTMASTER, PGC_S_ARGV);
472 postmaster_error("assert checking is not compiled in");
476 /* Can no longer set authentication method. */
479 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
482 /* Can no longer set the backend executable file to use. */
485 potential_DataDir = optarg;
489 /* Turn on debugging for the postmaster. */
490 char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
492 sprintf(debugstr, "debug%s", optarg);
493 SetConfigOption("log_min_messages", debugstr,
494 PGC_POSTMASTER, PGC_S_ARGV);
496 debug_flag = atoi(optarg);
500 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
503 SetConfigOption("virtual_host", optarg, PGC_POSTMASTER, PGC_S_ARGV);
506 SetConfigOption("tcpip_socket", "true", PGC_POSTMASTER, PGC_S_ARGV);
509 SetConfigOption("unix_socket_directory", optarg, PGC_POSTMASTER, PGC_S_ARGV);
513 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
517 /* Multiplexed backends no longer supported. */
522 * ignore this flag. This may be passed in because the
523 * program was run as 'postgres -M' instead of
528 /* The max number of backends to start. */
529 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
532 /* Don't reinit shared mem after abnormal exit */
538 * Other options to pass to the backend on the command
539 * line -- useful only for debugging.
541 strcat(ExtraOptions, " ");
542 strcat(ExtraOptions, optarg);
543 strcpy(original_extraoptions, optarg);
546 SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
551 * Start in 'S'ilent mode (disassociate from controlling
552 * tty). You may also think of this as 'S'ysV mode since
553 * it's most badly needed on SysV-derived systems like
556 SetConfigOption("silent_mode", "true", PGC_POSTMASTER, PGC_S_ARGV);
561 * In the event that some backend dumps core, send
562 * SIGSTOP, rather than SIGQUIT, to all its peers. This
563 * lets the wily post_hacker collect core dumps from
574 ParseLongOption(optarg, &name, &value);
579 (errcode(ERRCODE_SYNTAX_ERROR),
580 errmsg("--%s requires a value",
584 (errcode(ERRCODE_SYNTAX_ERROR),
585 errmsg("-c %s requires a value",
589 SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
598 gettext("Try \"%s --help\" for more information.\n"),
605 * Postmaster accepts no non-option switch arguments.
609 postmaster_error("invalid argument: \"%s\"", argv[optind]);
611 gettext("Try \"%s --help\" for more information.\n"),
617 * Now we can set the data directory, and then read postgresql.conf.
619 checkDataDir(potential_DataDir); /* issues error messages */
620 SetDataDir(potential_DataDir);
622 ProcessConfigFile(PGC_POSTMASTER);
624 write_nondefault_variables(PGC_POSTMASTER);
628 * Check for invalid combinations of GUC settings.
630 if (NBuffers < 2 * MaxBackends || NBuffers < 16)
633 * Do not accept -B so small that backends are likely to starve
634 * for lack of buffers. The specific choices here are somewhat
637 postmaster_error("the number of buffers (-B) must be at least twice the number of allowed connections (-N) and at least 16");
641 if (ReservedBackends >= MaxBackends)
643 postmaster_error("superuser_reserved_connections must be less than max_connections");
648 * Other one-time internal sanity checks can go here.
650 if (!CheckDateTokenTables())
652 postmaster_error("invalid datetoken tables, please fix");
657 * Now that we are done processing the postmaster arguments, reset
658 * getopt(3) library so that it will work correctly in subprocesses.
661 #ifdef HAVE_INT_OPTRESET
662 optreset = 1; /* some systems need this too */
665 /* For debugging: display postmaster environment */
667 extern char **environ;
671 (errmsg_internal("%s: PostmasterMain: initial environ dump:",
674 (errmsg_internal("-----------------------------------------")));
675 for (p = environ; *p; ++p)
677 (errmsg_internal("\t%s", *p)));
679 (errmsg_internal("-----------------------------------------")));
683 * On some systems our dynloader code needs the executable's pathname.
685 if (FindExec(pg_pathname, progname, "postgres") < 0)
687 (errmsg("%s: could not locate postgres executable",
691 * Initialize SSL library, if specified.
694 if (EnableSSL && !NetServer)
696 postmaster_error("TCP/IP connections must be enabled for SSL");
704 * process any libraries that should be preloaded and optionally
707 if (preload_libraries_string)
708 process_preload_libraries(preload_libraries_string);
711 * Fork away from controlling terminal, if -S specified.
713 * Must do this before we grab any interlock files, else the interlocks
714 * will show the wrong PID.
717 pmdaemonize(argc, argv);
720 * Create lockfile for data directory.
722 * We want to do this before we try to grab the input sockets, because
723 * the data directory interlock is more reliable than the socket-file
724 * interlock (thanks to whoever decided to put socket files in /tmp
725 * :-(). For the same reason, it's best to grab the TCP socket before
728 CreateDataDirLockFile(DataDir, true);
731 * Remove old temporary files. At this point there can be no other
732 * Postgres processes running in this directory, so this should be
738 * Establish input sockets.
740 for (i = 0; i < MAXLISTEN; i++)
741 ListenSocket[i] = -1;
745 if (VirtualHost && VirtualHost[0])
751 curhost = VirtualHost;
754 while (*curhost == ' ') /* skip any extra spaces */
756 if (*curhost == '\0')
758 endptr = strchr(curhost, ' ');
764 status = StreamServerPort(AF_UNSPEC, curhost,
765 (unsigned short) PostPortNumber,
767 ListenSocket, MAXLISTEN);
768 if (status != STATUS_OK)
770 (errmsg("could not create listen socket for \"%s\"",
775 curhost = endptr + 1;
783 status = StreamServerPort(AF_UNSPEC, NULL,
784 (unsigned short) PostPortNumber,
786 ListenSocket, MAXLISTEN);
787 if (status != STATUS_OK)
789 (errmsg("could not create TCP/IP listen socket")));
792 #ifdef USE_RENDEZVOUS
793 if (rendezvous_name != NULL)
795 DNSServiceRegistrationCreate(rendezvous_name,
798 htonl(PostPortNumber),
800 (DNSServiceRegistrationReply) reg_reply,
806 #ifdef HAVE_UNIX_SOCKETS
807 status = StreamServerPort(AF_UNIX, NULL,
808 (unsigned short) PostPortNumber,
810 ListenSocket, MAXLISTEN);
811 if (status != STATUS_OK)
813 (errmsg("could not create Unix-domain socket")));
819 * Set up shared memory and semaphores.
821 reset_shared(PostPortNumber);
824 * Initialize the list of active backends.
826 BackendList = DLNewList();
829 * Record postmaster options. We delay this till now to avoid
830 * recording bogus options (eg, NBuffers too high for available
833 if (!CreateOptsFile(argc, argv))
837 * Set up signal handlers for the postmaster process.
839 * CAUTION: when changing this list, check for side-effects on the signal
840 * handling setup of child processes. See tcop/postgres.c,
841 * bootstrap/bootstrap.c, and postmaster/pgstat.c.
844 PG_SETMASK(&BlockSig);
846 pqsignal(SIGHUP, SIGHUP_handler); /* reread config file and have
847 * children do same */
848 pqsignal(SIGINT, pmdie); /* send SIGTERM and ShutdownDataBase */
849 pqsignal(SIGQUIT, pmdie); /* send SIGQUIT and die */
850 pqsignal(SIGTERM, pmdie); /* wait for children and ShutdownDataBase */
851 pqsignal(SIGALRM, SIG_IGN); /* ignored */
852 pqsignal(SIGPIPE, SIG_IGN); /* ignored */
853 pqsignal(SIGUSR1, sigusr1_handler); /* message from child process */
854 pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
855 pqsignal(SIGCHLD, reaper); /* handle child termination */
856 pqsignal(SIGTTIN, SIG_IGN); /* ignored */
857 pqsignal(SIGTTOU, SIG_IGN); /* ignored */
858 /* ignore SIGXFSZ, so that ulimit violations work like disk full */
860 pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
864 * Reset whereToSendOutput from Debug (its starting state) to None.
865 * This prevents ereport from sending log messages to stderr unless
866 * the syslog/stderr switch permits. We don't do this until the
867 * postmaster is fully launched, since startup failures may as well be
868 * reported to stderr.
870 whereToSendOutput = None;
873 * On many platforms, the first call of localtime() incurs significant
874 * overhead to load timezone info from the system configuration files.
875 * By doing it once in the postmaster, we avoid having to do it in
876 * every started child process. The savings are not huge, but they
880 time_t now = time(NULL);
882 (void) localtime(&now);
886 * Initialize and try to startup the statistics collector process
892 * Load cached files for client authentication.
900 * We're ready to rock and roll...
902 StartupPID = StartupDataBase();
904 status = ServerLoop();
907 * ServerLoop probably shouldn't ever return, but if it does, close
910 ExitPostmaster(status != STATUS_OK);
912 return 0; /* not reached */
916 pmdaemonize(int argc, char *argv[])
922 struct itimerval prof_itimer;
926 /* see comments in BackendRun */
927 getitimer(ITIMER_PROF, &prof_itimer);
931 /* FIXME: [fork/exec] to be implemented? */
936 if (pid == (pid_t) -1)
938 postmaster_error("could not fork background process: %s",
944 /* Parent should just exit, without doing any atexit cleanup */
949 setitimer(ITIMER_PROF, &prof_itimer, NULL);
952 MyProcPid = getpid(); /* reset MyProcPid to child */
954 /* GH: If there's no setsid(), we hopefully don't need silent mode.
955 * Until there's a better solution.
960 postmaster_error("could not dissociate from controlling TTY: %s",
965 i = open(NULL_DEV, O_RDWR | PG_BINARY);
975 * Print out help message
978 usage(const char *progname)
980 printf(gettext("%s is the PostgreSQL server.\n\n"), progname);
981 printf(gettext("Usage:\n %s [OPTION]...\n\n"), progname);
982 printf(gettext("Options:\n"));
983 #ifdef USE_ASSERT_CHECKING
984 printf(gettext(" -A 1|0 enable/disable run-time assert checking\n"));
986 printf(gettext(" -B NBUFFERS number of shared buffers\n"));
987 printf(gettext(" -c NAME=VALUE set run-time parameter\n"));
988 printf(gettext(" -d 1-5 debugging level\n"));
989 printf(gettext(" -D DATADIR database directory\n"));
990 printf(gettext(" -F turn fsync off\n"));
991 printf(gettext(" -h HOSTNAME host name or IP address to listen on\n"));
992 printf(gettext(" -i enable TCP/IP connections\n"));
993 printf(gettext(" -k DIRECTORY Unix-domain socket location\n"));
995 printf(gettext(" -l enable SSL connections\n"));
997 printf(gettext(" -N MAX-CONNECT maximum number of allowed connections\n"));
998 printf(gettext(" -o OPTIONS pass \"OPTIONS\" to each server process\n"));
999 printf(gettext(" -p PORT port number to listen on\n"));
1000 printf(gettext(" -S silent mode (start in background without logging output)\n"));
1001 printf(gettext(" --help show this help, then exit\n"));
1002 printf(gettext(" --version output version information, then exit\n"));
1004 printf(gettext("\nDeveloper options:\n"));
1005 printf(gettext(" -n do not reinitialize shared memory after abnormal exit\n"));
1006 printf(gettext(" -s send SIGSTOP to all backend servers if one dies\n"));
1008 printf(gettext("\nPlease read the documentation for the complete list of run-time\n"
1009 "configuration settings and how to set them on the command line or in\n"
1010 "the configuration file.\n\n"
1011 "Report bugs to <pgsql-bugs@postgresql.org>.\n"));
1024 gettimeofday(&now, &tz);
1026 nSockets = initMasks(&readmask);
1032 struct timeval timeout;
1035 * The timeout for the select() below is normally set on the basis
1036 * of the time to the next checkpoint. However, if for some
1037 * reason we don't have a next-checkpoint time, time out after 60
1038 * seconds. This keeps checkpoint scheduling from locking up when
1039 * we get new connection requests infrequently (since we are
1040 * likely to detect checkpoint completion just after enabling
1041 * signals below, after we've already made the decision about how
1042 * long to wait this time).
1044 timeout.tv_sec = 60;
1045 timeout.tv_usec = 0;
1047 if (CheckPointPID == 0 && checkpointed &&
1048 Shutdown == NoShutdown && !FatalError && random_seed != 0)
1050 time_t now = time(NULL);
1052 if (CheckPointTimeout + checkpointed > now)
1055 * Not time for checkpoint yet, so set select timeout
1057 timeout.tv_sec = CheckPointTimeout + checkpointed - now;
1061 /* Time to make the checkpoint... */
1062 CheckPointPID = CheckPointDataBase();
1065 * if fork failed, schedule another try at 0.1 normal
1068 if (CheckPointPID == 0)
1070 timeout.tv_sec = CheckPointTimeout / 10;
1071 checkpointed = now + timeout.tv_sec - CheckPointTimeout;
1077 * If no background writer process is running and we should
1078 * do background writing, start one. It doesn't matter if
1079 * this fails, we'll just try again later.
1081 if (BgWriterPID == 0 && BgWriterPercent > 0 &&
1082 Shutdown == NoShutdown && !FatalError && random_seed != 0)
1084 BgWriterPID = StartBackgroundWriter();
1088 * Wait for something to happen.
1090 memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
1092 PG_SETMASK(&UnBlockSig);
1094 if (select(nSockets, &rmask, NULL, NULL, &timeout) < 0)
1096 PG_SETMASK(&BlockSig);
1097 if (errno == EINTR || errno == EWOULDBLOCK)
1100 (errcode_for_socket_access(),
1101 errmsg("select() failed in postmaster: %m")));
1102 return STATUS_ERROR;
1106 * Block all signals until we wait again. (This makes it safe for
1107 * our signal handlers to do nontrivial work.)
1109 PG_SETMASK(&BlockSig);
1112 * Select a random seed at the time of first receiving a request.
1114 while (random_seed == 0)
1116 gettimeofday(&later, &tz);
1119 * We are not sure how much precision is in tv_usec, so we
1120 * swap the nibbles of 'later' and XOR them with 'now'. On the
1121 * off chance that the result is 0, we loop until it isn't.
1123 random_seed = now.tv_usec ^
1124 ((later.tv_usec << 16) |
1125 ((later.tv_usec >> 16) & 0xffff));
1129 * New connection pending on any of our sockets? If so, fork a
1130 * child process to deal with it.
1132 for (i = 0; i < MAXLISTEN; i++)
1134 if (ListenSocket[i] == -1)
1136 if (FD_ISSET(ListenSocket[i], &rmask))
1138 port = ConnCreate(ListenSocket[i]);
1141 BackendStartup(port);
1144 * We no longer need the open socket or port structure
1147 StreamClose(port->sock);
1153 /* If we have lost the stats collector, try to start a new one */
1154 if (!pgstat_is_running)
1161 * Initialise the masks for select() for the ports
1162 * we are listening on. Return the number of sockets to listen on.
1166 initMasks(fd_set *rmask)
1173 for (i = 0; i < MAXLISTEN; i++)
1175 int fd = ListenSocket[i];
1189 * Read the startup packet and do something according to it.
1191 * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
1192 * not return at all.
1194 * (Note that ereport(FATAL) stuff is sent to the client, so only use it
1195 * if that's what you want. Return STATUS_ERROR if you don't want to
1196 * send anything to the client, which would typically be appropriate
1197 * if we detect a communications failure.)
1200 ProcessStartupPacket(Port *port, bool SSLdone)
1204 ProtocolVersion proto;
1205 MemoryContext oldcontext;
1207 if (pq_getbytes((char *) &len, 4) == EOF)
1210 * EOF after SSLdone probably means the client didn't like our
1211 * response to NEGOTIATE_SSL_CODE. That's not an error condition,
1212 * so don't clutter the log with a complaint.
1216 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1217 errmsg("incomplete startup packet")));
1218 return STATUS_ERROR;
1224 if (len < (int32) sizeof(ProtocolVersion) ||
1225 len > MAX_STARTUP_PACKET_LENGTH)
1228 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1229 errmsg("invalid length of startup packet")));
1230 return STATUS_ERROR;
1234 * Allocate at least the size of an old-style startup packet, plus one
1235 * extra byte, and make sure all are zeroes. This ensures we will
1236 * have null termination of all strings, in both fixed- and
1237 * variable-length packet layouts.
1239 if (len <= (int32) sizeof(StartupPacket))
1240 buf = palloc0(sizeof(StartupPacket) + 1);
1242 buf = palloc0(len + 1);
1244 if (pq_getbytes(buf, len) == EOF)
1247 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1248 errmsg("incomplete startup packet")));
1249 return STATUS_ERROR;
1253 * The first field is either a protocol version number or a special
1256 port->proto = proto = ntohl(*((ProtocolVersion *) buf));
1258 if (proto == CANCEL_REQUEST_CODE)
1261 abort(); /* FIXME: [fork/exec] Whoops. Not handled... yet */
1263 processCancelRequest(port, buf);
1265 return 127; /* XXX */
1268 if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
1273 /* No SSL when disabled or on Unix sockets */
1274 if (!EnableSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
1277 SSLok = 'S'; /* Support for SSL */
1279 SSLok = 'N'; /* No support for SSL */
1281 if (send(port->sock, &SSLok, 1, 0) != 1)
1284 (errcode_for_socket_access(),
1285 errmsg("failed to send SSL negotiation response: %m")));
1286 return STATUS_ERROR; /* close the connection */
1290 if (SSLok == 'S' && secure_open_server(port) == -1)
1291 return STATUS_ERROR;
1293 /* regular startup packet, cancel, etc packet should follow... */
1294 /* but not another SSL negotiation request */
1295 return ProcessStartupPacket(port, true);
1298 /* Could add additional special packet types here */
1301 * Set FrontendProtocol now so that ereport() knows what format to
1302 * send if we fail during startup.
1304 FrontendProtocol = proto;
1306 /* Check we can handle the protocol the frontend is using. */
1308 if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
1309 PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
1310 (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
1311 PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
1313 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1314 errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
1315 PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
1316 PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST),
1317 PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST),
1318 PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))));
1321 * Now fetch parameters out of startup packet and save them into the
1322 * Port structure. All data structures attached to the Port struct
1323 * must be allocated in TopMemoryContext so that they won't disappear
1324 * when we pass them to PostgresMain (see BackendRun). We need not
1325 * worry about leaking this storage on failure, since we aren't in the
1326 * postmaster process anymore.
1328 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1330 if (PG_PROTOCOL_MAJOR(proto) >= 3)
1332 int32 offset = sizeof(ProtocolVersion);
1335 * Scan packet body for name/option pairs. We can assume any
1336 * string beginning within the packet body is null-terminated,
1337 * thanks to zeroing extra byte above.
1339 port->guc_options = NIL;
1341 while (offset < len)
1343 char *nameptr = ((char *) buf) + offset;
1347 if (*nameptr == '\0')
1348 break; /* found packet terminator */
1349 valoffset = offset + strlen(nameptr) + 1;
1350 if (valoffset >= len)
1351 break; /* missing value, will complain below */
1352 valptr = ((char *) buf) + valoffset;
1354 if (strcmp(nameptr, "database") == 0)
1355 port->database_name = pstrdup(valptr);
1356 else if (strcmp(nameptr, "user") == 0)
1357 port->user_name = pstrdup(valptr);
1358 else if (strcmp(nameptr, "options") == 0)
1359 port->cmdline_options = pstrdup(valptr);
1362 /* Assume it's a generic GUC option */
1363 port->guc_options = lappend(port->guc_options,
1365 port->guc_options = lappend(port->guc_options,
1368 offset = valoffset + strlen(valptr) + 1;
1372 * If we didn't find a packet terminator exactly at the end of the
1373 * given packet length, complain.
1375 if (offset != len - 1)
1377 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1378 errmsg("invalid startup packet layout: expected terminator as last byte")));
1383 * Get the parameters from the old-style, fixed-width-fields
1384 * startup packet as C strings. The packet destination was
1385 * cleared first so a short packet has zeros silently added. We
1386 * have to be prepared to truncate the pstrdup result for oversize
1389 StartupPacket *packet = (StartupPacket *) buf;
1391 port->database_name = pstrdup(packet->database);
1392 if (strlen(port->database_name) > sizeof(packet->database))
1393 port->database_name[sizeof(packet->database)] = '\0';
1394 port->user_name = pstrdup(packet->user);
1395 if (strlen(port->user_name) > sizeof(packet->user))
1396 port->user_name[sizeof(packet->user)] = '\0';
1397 port->cmdline_options = pstrdup(packet->options);
1398 if (strlen(port->cmdline_options) > sizeof(packet->options))
1399 port->cmdline_options[sizeof(packet->options)] = '\0';
1400 port->guc_options = NIL;
1403 /* Check a user name was given. */
1404 if (port->user_name == NULL || port->user_name[0] == '\0')
1406 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1407 errmsg("no PostgreSQL user name specified in startup packet")));
1409 /* The database defaults to the user name. */
1410 if (port->database_name == NULL || port->database_name[0] == '\0')
1411 port->database_name = pstrdup(port->user_name);
1413 if (Db_user_namespace)
1416 * If user@, it is a global user, remove '@'. We only want to do
1417 * this if there is an '@' at the end and no earlier in the user
1418 * string or they may fake as a local user of another database
1419 * attaching to this database.
1421 if (strchr(port->user_name, '@') ==
1422 port->user_name + strlen(port->user_name) - 1)
1423 *strchr(port->user_name, '@') = '\0';
1426 /* Append '@' and dbname */
1429 db_user = palloc(strlen(port->user_name) +
1430 strlen(port->database_name) + 2);
1431 sprintf(db_user, "%s@%s", port->user_name, port->database_name);
1432 port->user_name = db_user;
1437 * Truncate given database and user names to length of a Postgres
1438 * name. This avoids lookup failures when overlength names are given.
1440 if (strlen(port->database_name) >= NAMEDATALEN)
1441 port->database_name[NAMEDATALEN - 1] = '\0';
1442 if (strlen(port->user_name) >= NAMEDATALEN)
1443 port->user_name[NAMEDATALEN - 1] = '\0';
1446 * Done putting stuff in TopMemoryContext.
1448 MemoryContextSwitchTo(oldcontext);
1451 * If we're going to reject the connection due to database state, say
1452 * so now instead of wasting cycles on an authentication exchange.
1453 * (This also allows a pg_ping utility to be written.)
1455 switch (port->canAcceptConnections)
1459 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1460 errmsg("the database system is starting up")));
1464 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1465 errmsg("the database system is shutting down")));
1469 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1470 errmsg("the database system is in recovery mode")));
1474 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
1475 errmsg("sorry, too many clients already")));
1487 * The client has sent a cancel request packet, not a normal
1488 * start-a-new-connection packet. Perform the necessary processing.
1489 * Nothing is sent back to the client.
1492 processCancelRequest(Port *port, void *pkt)
1494 CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
1496 long cancelAuthCode;
1500 backendPID = (int) ntohl(canc->backendPID);
1501 cancelAuthCode = (long) ntohl(canc->cancelAuthCode);
1503 if (backendPID == CheckPointPID)
1506 (errmsg_internal("ignoring cancel request for checkpoint process %d",
1510 else if (backendPID == BgWriterPID)
1513 (errmsg_internal("ignoring cancel request for bgwriter process %d",
1519 AttachSharedMemoryAndSemaphores();
1522 /* See if we have a matching backend */
1524 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
1526 bp = (Backend *) DLE_VAL(curr);
1527 if (bp->pid == backendPID)
1529 if (bp->cancel_key == cancelAuthCode)
1531 /* Found a match; signal that backend to cancel current op */
1533 (errmsg_internal("processing cancel request: sending SIGINT to process %d",
1535 kill(bp->pid, SIGINT);
1538 /* Right PID, wrong key: no way, Jose */
1540 (errmsg_internal("bad key in cancel request for process %d",
1546 /* No matching backend */
1548 (errmsg_internal("bad pid in cancel request for process %d",
1553 * canAcceptConnections --- check to see if database state allows connections.
1555 static enum CAC_state
1556 canAcceptConnections(void)
1558 /* Can't start backends when in startup/shutdown/recovery state. */
1559 if (Shutdown > NoShutdown)
1560 return CAC_SHUTDOWN;
1564 return CAC_RECOVERY;
1567 * Don't start too many children.
1569 * We allow more connections than we can have backends here because some
1570 * might still be authenticating; they might fail auth, or some
1571 * existing backend might exit before the auth cycle is completed. The
1572 * exact MaxBackends limit is enforced when a new backend tries to
1573 * join the shared-inval backend array.
1575 if (CountChildren() >= 2 * MaxBackends)
1583 * ConnCreate -- create a local connection data structure
1586 ConnCreate(int serverFd)
1590 if (!(port = (Port *) calloc(1, sizeof(Port))))
1593 (errcode(ERRCODE_OUT_OF_MEMORY),
1594 errmsg("out of memory")));
1598 if (StreamConnection(serverFd, port) != STATUS_OK)
1600 StreamClose(port->sock);
1607 * Precompute password salt values to use for this connection.
1608 * It's slightly annoying to do this long in advance of knowing
1609 * whether we'll need 'em or not, but we must do the random()
1610 * calls before we fork, not after. Else the postmaster's random
1611 * sequence won't get advanced, and all backends would end up
1612 * using the same salt...
1614 RandomSalt(port->cryptSalt, port->md5Salt);
1622 * ConnFree -- free a local connection data structure
1625 ConnFree(Port *conn)
1635 * ClosePostmasterPorts -- close all the postmaster's open sockets
1637 * This is called during child process startup to release file descriptors
1638 * that are not needed by that child process. The postmaster still has
1639 * them open, of course.
1642 ClosePostmasterPorts(bool pgstat_too)
1646 /* Close the listen sockets */
1647 for (i = 0; i < MAXLISTEN; i++)
1649 if (ListenSocket[i] != -1)
1651 StreamClose(ListenSocket[i]);
1652 ListenSocket[i] = -1;
1656 /* Close pgstat control sockets, unless we're starting pgstat itself */
1658 pgstat_close_sockets();
1663 * reset_shared -- reset shared memory and semaphores
1666 reset_shared(unsigned short port)
1669 * Create or re-create shared memory and semaphores.
1671 * Note: in each "cycle of life" we will normally assign the same IPC
1672 * keys (if using SysV shmem and/or semas), since the port number is
1673 * used to determine IPC keys. This helps ensure that we will clean
1674 * up dead IPC objects if the postmaster crashes and is restarted.
1676 CreateSharedMemoryAndSemaphores(false, MaxBackends, port);
1681 * SIGHUP -- reread config files, and tell children to do same
1684 SIGHUP_handler(SIGNAL_ARGS)
1686 int save_errno = errno;
1688 PG_SETMASK(&BlockSig);
1690 if (Shutdown <= SmartShutdown)
1693 (errmsg("received SIGHUP, reloading configuration files")));
1694 ProcessConfigFile(PGC_SIGHUP);
1696 write_nondefault_variables(PGC_SIGHUP);
1698 SignalChildren(SIGHUP);
1703 * Tell the background writer to terminate so that we
1704 * will start a new one with a possibly changed config
1706 if (BgWriterPID != 0)
1707 kill(BgWriterPID, SIGTERM);
1710 PG_SETMASK(&UnBlockSig);
1718 * pmdie -- signal handler for processing various postmaster signals.
1723 int save_errno = errno;
1725 PG_SETMASK(&BlockSig);
1728 (errmsg_internal("postmaster received signal %d",
1729 postgres_signal_arg)));
1731 switch (postgres_signal_arg)
1738 * Wait for children to end their work and ShutdownDataBase.
1740 if (BgWriterPID != 0)
1741 kill(BgWriterPID, SIGTERM);
1742 if (Shutdown >= SmartShutdown)
1744 Shutdown = SmartShutdown;
1746 (errmsg("received smart shutdown request")));
1747 if (DLGetHead(BackendList)) /* let reaper() handle this */
1751 * No children left. Shutdown data base system.
1753 if (StartupPID > 0 || FatalError) /* let reaper() handle
1756 if (ShutdownPID > 0)
1758 elog(PANIC, "shutdown process %d already running",
1763 ShutdownPID = ShutdownDataBase();
1771 * abort all children with SIGTERM (rollback active transactions
1772 * and exit) and ShutdownDataBase when they are gone.
1774 if (BgWriterPID != 0)
1775 kill(BgWriterPID, SIGTERM);
1776 if (Shutdown >= FastShutdown)
1779 (errmsg("received fast shutdown request")));
1780 if (DLGetHead(BackendList)) /* let reaper() handle this */
1782 Shutdown = FastShutdown;
1786 (errmsg("aborting any active transactions")));
1787 SignalChildren(SIGTERM);
1791 if (Shutdown > NoShutdown)
1793 Shutdown = FastShutdown;
1796 Shutdown = FastShutdown;
1799 * No children left. Shutdown data base system.
1801 if (StartupPID > 0 || FatalError) /* let reaper() handle
1804 if (ShutdownPID > 0)
1806 elog(PANIC, "shutdown process %d already running",
1811 ShutdownPID = ShutdownDataBase();
1817 * Immediate Shutdown:
1819 * abort all children with SIGQUIT and exit without attempt to
1820 * properly shutdown data base system.
1822 if (BgWriterPID != 0)
1823 kill(BgWriterPID, SIGQUIT);
1825 (errmsg("received immediate shutdown request")));
1826 if (ShutdownPID > 0)
1827 kill(ShutdownPID, SIGQUIT);
1829 kill(StartupPID, SIGQUIT);
1830 if (DLGetHead(BackendList))
1831 SignalChildren(SIGQUIT);
1836 PG_SETMASK(&UnBlockSig);
1842 * Reaper -- signal handler to cleanup after a backend (child) dies.
1847 int save_errno = errno;
1850 #warning fix waidpid for Win32
1853 int status; /* backend exit status */
1856 union wait status; /* backend exit status */
1859 int pid; /* process id of dead backend */
1861 PG_SETMASK(&BlockSig);
1864 (errmsg_internal("reaping dead processes")));
1866 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1868 exitstatus = status;
1870 while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
1872 exitstatus = status.w_status;
1876 * Check if this child was the statistics collector. If so, try to
1877 * start a new one. (If fail, we'll try again in future cycles of
1880 if (pgstat_ispgstat(pid))
1882 LogChildExit(LOG, gettext("statistics collector process"),
1889 * Check if this child was a shutdown or startup process.
1891 if (ShutdownPID > 0 && pid == ShutdownPID)
1893 if (exitstatus != 0)
1895 LogChildExit(LOG, gettext("shutdown process"),
1899 /* Normal postmaster exit is here */
1903 if (StartupPID > 0 && pid == StartupPID)
1905 if (exitstatus != 0)
1907 LogChildExit(LOG, gettext("startup process"),
1910 (errmsg("aborting startup due to startup process failure")));
1916 * Startup succeeded - remember its ID and RedoRecPtr.
1918 * NB: this MUST happen before we fork a checkpoint or shutdown
1919 * subprocess, else they will have wrong local ThisStartUpId.
1923 FatalError = false; /* done with recovery */
1926 * Arrange for first checkpoint to occur after standard delay.
1929 checkpointed = time(NULL);
1931 if (BgWriterPID == 0 && BgWriterPercent > 0 &&
1932 Shutdown == NoShutdown && !FatalError && random_seed != 0)
1934 BgWriterPID = StartBackgroundWriter();
1938 * Go to shutdown mode if a shutdown request was pending.
1940 if (Shutdown > NoShutdown)
1942 if (ShutdownPID > 0)
1944 elog(PANIC, "startup process %d died while shutdown process %d already running",
1945 pid, (int) ShutdownPID);
1948 ShutdownPID = ShutdownDataBase();
1955 * Else do standard child cleanup.
1957 CleanupProc(pid, exitstatus);
1959 } /* loop over pending child-death reports */
1965 * Wait for all children exit, then reset shmem and
1968 if (DLGetHead(BackendList) || StartupPID > 0 || ShutdownPID > 0)
1971 (errmsg("all server processes terminated; reinitializing")));
1974 reset_shared(PostPortNumber);
1976 StartupPID = StartupDataBase();
1981 if (Shutdown > NoShutdown)
1983 if (DLGetHead(BackendList))
1985 if (StartupPID > 0 || ShutdownPID > 0)
1987 ShutdownPID = ShutdownDataBase();
1991 PG_SETMASK(&UnBlockSig);
1997 * CleanupProc -- cleanup after terminated backend.
1999 * Remove all local state associated with backend.
2002 CleanupProc(int pid,
2003 int exitstatus) /* child's exit status. */
2009 LogChildExit(DEBUG2, gettext("child process"), pid, exitstatus);
2012 * If a backend dies in an ugly way (i.e. exit status not 0) then we
2013 * must signal all other backends to quickdie. If exit status is zero
2014 * we assume everything is hunky dory and simply remove the backend
2015 * from the active backend list.
2017 if (exitstatus == 0)
2019 curr = DLGetHead(BackendList);
2022 bp = (Backend *) DLE_VAL(curr);
2030 curr = DLGetSucc(curr);
2033 if (pid == CheckPointPID)
2038 checkpointed = time(NULL);
2039 /* Update RedoRecPtr for future child backends */
2040 GetSavedRedoRecPtr();
2043 else if (pid == BgWriterPID)
2051 /* below here we're dealing with a non-normal exit */
2053 /* Make log entry unless we did so already */
2057 (pid == CheckPointPID) ? gettext("checkpoint process") :
2058 (pid == BgWriterPID) ? gettext("bgwriter process") :
2059 gettext("server process"),
2062 (errmsg("terminating any other active server processes")));
2065 curr = DLGetHead(BackendList);
2068 next = DLGetSucc(curr);
2069 bp = (Backend *) DLE_VAL(curr);
2073 * This backend is still alive. Unless we did so already,
2074 * tell it to commit hara-kiri.
2076 * SIGQUIT is the special signal that says exit without proc_exit
2077 * and let the user know what's going on. But if SendStop is
2078 * set (-s on command line), then we send SIGSTOP instead, so
2079 * that we can get core dumps from all backends by hand.
2084 (errmsg_internal("sending %s to process %d",
2085 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2087 kill(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
2093 * Found entry for freshly-dead backend, so remove it.
2102 if (pid == CheckPointPID)
2107 else if (pid == BgWriterPID)
2114 * Tell the collector about backend termination
2123 * Log the death of a child process.
2126 LogChildExit(int lev, const char *procname, int pid, int exitstatus)
2128 if (WIFEXITED(exitstatus))
2132 * translator: %s is a noun phrase describing a child process,
2133 * such as "server process"
2135 (errmsg("%s (PID %d) exited with exit code %d",
2136 procname, pid, WEXITSTATUS(exitstatus))));
2137 else if (WIFSIGNALED(exitstatus))
2141 * translator: %s is a noun phrase describing a child process,
2142 * such as "server process"
2144 (errmsg("%s (PID %d) was terminated by signal %d",
2145 procname, pid, WTERMSIG(exitstatus))));
2150 * translator: %s is a noun phrase describing a child process,
2151 * such as "server process"
2153 (errmsg("%s (PID %d) exited with unexpected status %d",
2154 procname, pid, exitstatus)));
2158 * Send a signal to all backend children.
2161 SignalChildren(int signal)
2167 curr = DLGetHead(BackendList);
2170 next = DLGetSucc(curr);
2171 bp = (Backend *) DLE_VAL(curr);
2173 if (bp->pid != MyProcPid)
2176 (errmsg_internal("sending signal %d to process %d",
2179 kill(bp->pid, signal);
2187 * BackendStartup -- start backend process
2189 * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
2192 BackendStartup(Port *port)
2194 Backend *bn; /* for backend cleanup */
2197 #ifdef LINUX_PROFILE
2198 struct itimerval prof_itimer;
2202 * Compute the cancel key that will be assigned to this backend. The
2203 * backend will have its own copy in the forked-off process' value of
2204 * MyCancelKey, so that it can transmit the key to the frontend.
2206 MyCancelKey = PostmasterRandom();
2209 * Make room for backend data structure. Better before the fork() so
2210 * we can handle failure cleanly.
2212 bn = (Backend *) malloc(sizeof(Backend));
2216 (errcode(ERRCODE_OUT_OF_MEMORY),
2217 errmsg("out of memory")));
2218 return STATUS_ERROR;
2222 * Flush stdio channels just before fork, to avoid double-output
2223 * problems. Ideally we'd use fflush(NULL) here, but there are still a
2224 * few non-ANSI stdio libraries out there (like SunOS 4.1.x) that
2225 * coredump if we do. Presently stdout and stderr are the only stdio
2226 * output channels used by the postmaster, so fflush'ing them should
2232 #ifdef LINUX_PROFILE
2235 * Linux's fork() resets the profiling timer in the child process. If
2236 * we want to profile child processes then we need to save and restore
2237 * the timer setting. This is a waste of time if not profiling,
2238 * however, so only do it if commanded by specific -DLINUX_PROFILE
2241 getitimer(ITIMER_PROF, &prof_itimer);
2245 /* Specific beos actions before backend startup */
2246 beos_before_backend_startup();
2249 port->canAcceptConnections = canAcceptConnections();
2251 pid = Backend_forkexec(port);
2255 if (pid == 0) /* child */
2257 #ifdef LINUX_PROFILE
2258 setitimer(ITIMER_PROF, &prof_itimer, NULL);
2262 /* Specific beos backend startup actions */
2263 beos_backend_startup();
2267 proc_exit(BackendRun(port));
2271 /* in parent, error */
2274 int save_errno = errno;
2277 /* Specific beos backend startup actions */
2278 beos_backend_startup_failed();
2283 (errmsg("could not fork new process for connection: %m")));
2284 report_fork_failure_to_client(port, save_errno);
2285 return STATUS_ERROR;
2288 /* in parent, normal */
2290 (errmsg_internal("forked new backend, pid=%d socket=%d",
2291 (int) pid, port->sock)));
2294 * Everything's been successful, it's safe to add this backend to our
2298 bn->cancel_key = MyCancelKey;
2299 DLAddHead(BackendList, DLNewElem(bn));
2305 * Try to report backend fork() failure to client before we close the
2306 * connection. Since we do not care to risk blocking the postmaster on
2307 * this connection, we set the connection to non-blocking and try only once.
2309 * This is grungy special-purpose code; we cannot use backend libpq since
2310 * it's not up and running.
2313 report_fork_failure_to_client(Port *port, int errnum)
2317 /* Format the error message packet (always V2 protocol) */
2318 snprintf(buffer, sizeof(buffer), "E%s%s\n",
2319 gettext("could not fork new process for connection: "),
2322 /* Set port to non-blocking. Don't do send() if this fails */
2323 if (FCNTL_NONBLOCK(port->sock) < 0)
2326 send(port->sock, buffer, strlen(buffer) + 1, 0);
2331 * split_opts -- split a string of options and append it to an argv array
2333 * NB: the string is destructively modified!
2335 * Since no current POSTGRES arguments require any quoting characters,
2336 * we can use the simple-minded tactic of assuming each set of space-
2337 * delimited characters is a separate argv element.
2339 * If you don't like that, well, we *used* to pass the whole option string
2340 * as ONE argument to execl(), which was even less intelligent...
2343 split_opts(char **argv, int *argcp, char *s)
2347 while (isspace((unsigned char) *s))
2351 argv[(*argcp)++] = s;
2352 while (*s && !isspace((unsigned char) *s))
2361 * BackendInit/Run -- perform authentication [BackendInit], and if successful,
2362 * set up the backend's argument list [BackendRun] and invoke
2366 * Shouldn't return at all.
2367 * If PostgresMain() fails, return status.
2370 BackendInit(Port *port)
2375 char remote_host[NI_MAXHOST];
2376 char remote_port[NI_MAXSERV];
2378 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
2380 ClientAuthInProgress = true; /* limit visibility of log messages */
2382 /* We don't want the postmaster's proc_exit() handlers */
2386 * Signal handlers setting is moved to tcop/postgres...
2389 /* Save port etc. for ps status */
2392 /* Reset MyProcPid to new backend's pid */
2393 MyProcPid = getpid();
2396 * Initialize libpq and enable reporting of ereport errors to the
2397 * client. Must do this now because authentication uses libpq to send
2400 pq_init(); /* initialize libpq to talk to client */
2401 whereToSendOutput = Remote; /* now safe to ereport to client */
2404 * We arrange for a simple exit(0) if we receive SIGTERM or SIGQUIT
2405 * during any client authentication related communication. Otherwise
2406 * the postmaster cannot shutdown the database FAST or IMMED cleanly
2407 * if a buggy client blocks a backend during authentication.
2409 pqsignal(SIGTERM, authdie);
2410 pqsignal(SIGQUIT, authdie);
2411 pqsignal(SIGALRM, authdie);
2412 PG_SETMASK(&AuthBlockSig);
2415 * Get the remote host name and port for logging and status display.
2417 remote_host[0] = '\0';
2418 remote_port[0] = '\0';
2419 if (getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2420 remote_host, sizeof(remote_host),
2421 remote_port, sizeof(remote_port),
2422 (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV))
2424 getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2425 remote_host, sizeof(remote_host),
2426 remote_port, sizeof(remote_port),
2427 NI_NUMERICHOST | NI_NUMERICSERV);
2430 if (Log_connections)
2432 (errmsg("connection received: host=%s port=%s",
2433 remote_host, remote_port)));
2437 /* modify remote_host for use in ps status */
2438 char tmphost[NI_MAXHOST];
2440 snprintf(tmphost, sizeof(tmphost), "%s:%s", remote_host, remote_port);
2441 StrNCpy(remote_host, tmphost, sizeof(remote_host));
2445 * Ready to begin client interaction. We will give up and exit(0)
2446 * after a time delay, so that a broken client can't hog a connection
2447 * indefinitely. PreAuthDelay doesn't count against the time limit.
2449 if (!enable_sig_alarm(AuthenticationTimeout * 1000, false))
2450 elog(FATAL, "could not set timer for authorization timeout");
2453 * Receive the startup packet (which might turn out to be a cancel
2456 status = ProcessStartupPacket(port, false);
2458 if (status != STATUS_OK)
2462 * Now that we have the user and database name, we can set the process
2463 * title for ps. It's good to do this as early as possible in
2466 init_ps_display(port->user_name, port->database_name, remote_host);
2467 set_ps_display("authentication");
2470 * Now perform authentication exchange.
2472 ClientAuthentication(port); /* might not return, if failure */
2475 * Done with authentication. Disable timeout, and prevent
2476 * SIGTERM/SIGQUIT again until backend startup is complete.
2478 if (!disable_sig_alarm(false))
2479 elog(FATAL, "could not disable timer for authorization timeout");
2480 PG_SETMASK(&BlockSig);
2482 if (Log_connections)
2484 (errmsg("connection authorized: user=%s database=%s",
2485 port->user_name, port->database_name)));
2488 * Don't want backend to be able to see the postmaster random number
2489 * generator state. We have to clobber the static random_seed *and*
2490 * start a new random sequence in the random() library function.
2493 gettimeofday(&now, &tz);
2494 srandom((unsigned int) now.tv_usec);
2499 BackendRun(Port *port)
2509 * Let's clean up ourselves as the postmaster child, and
2510 * close the postmaster's other sockets
2512 ClosePostmasterPorts(true);
2515 * PreAuthDelay is a debugging aid for investigating problems in the
2516 * authentication cycle: it can be set in postgresql.conf to allow
2517 * time to attach to the newly-forked backend with a debugger. (See
2518 * also the -W backend switch, which we allow clients to pass through
2519 * PGOPTIONS, but it is not honored until after authentication.)
2521 if (PreAuthDelay > 0)
2522 sleep(PreAuthDelay);
2524 /* Will exit on failure */
2529 * Now, build the argv vector that will be given to PostgresMain.
2531 * The layout of the command line is
2532 * postgres [secure switches] -p databasename [insecure switches]
2533 * where the switches after -p come from the client request.
2535 * The maximum possible number of commandline arguments that could come
2536 * from ExtraOptions or port->cmdline_options is (strlen + 1) / 2; see
2540 maxac = 10; /* for fixed args supplied below */
2541 maxac += (strlen(ExtraOptions) + 1) / 2;
2542 if (port->cmdline_options)
2543 maxac += (strlen(port->cmdline_options) + 1) / 2;
2545 av = (char **) MemoryContextAlloc(TopMemoryContext,
2546 maxac * sizeof(char *));
2549 av[ac++] = "postgres";
2552 * Pass the requested debugging level along to the backend.
2556 snprintf(debugbuf, sizeof(debugbuf), "-d%d", debug_flag);
2557 av[ac++] = debugbuf;
2561 * Pass any backend switches specified with -o in the postmaster's own
2562 * command line. We assume these are secure.
2564 split_opts(av, &ac, ExtraOptions);
2566 /* Tell the backend what protocol the frontend is using. */
2567 snprintf(protobuf, sizeof(protobuf), "-v%u", port->proto);
2568 av[ac++] = protobuf;
2571 /* pass data dir before end of secure switches (-p) */
2577 * Tell the backend it is being called from the postmaster, and which
2578 * database to use. -p marks the end of secure switches.
2581 av[ac++] = port->database_name;
2584 * Pass the (insecure) option switches from the connection request.
2585 * (It's OK to mangle port->cmdline_options now.)
2587 if (port->cmdline_options)
2588 split_opts(av, &ac, port->cmdline_options);
2595 * Release postmaster's working memory context so that backend can
2596 * recycle the space. Note this does not trash *MyProcPort, because
2597 * ConnCreate() allocated that space with malloc() ... else we'd need
2598 * to copy the Port data here. Also, subsidiary data such as the
2599 * username isn't lost either; see ProcessStartupPacket().
2601 MemoryContextSwitchTo(TopMemoryContext);
2602 #ifndef EXEC_BACKEND
2603 MemoryContextDelete(PostmasterContext);
2605 PostmasterContext = NULL;
2608 * Debug: print arguments being passed to backend
2611 (errmsg_internal("%s child[%d]: starting with (",
2612 progname, getpid())));
2613 for (i = 0; i < ac; ++i)
2615 (errmsg_internal("\t%s", av[i])));
2617 (errmsg_internal(")")));
2619 ClientAuthInProgress = false; /* client_min_messages is active
2622 return (PostgresMain(ac, av, port->user_name));
2630 * SubPostmasterMain -- prepare the fork/exec'd process to be in an equivalent
2631 * state (for calling BackendRun) as a forked process.
2634 * Shouldn't return at all.
2637 SubPostmasterMain(int argc, char* argv[])
2639 unsigned long backendID;
2642 memset((void*)&port, 0, sizeof(Port));
2645 /* Setup global context */
2646 MemoryContextInit();
2647 InitializeGUCOptions();
2649 /* Parse passed-in context */
2651 backendID = (unsigned long)atol(argv[argc++]);
2652 DataDir = strdup(argv[argc++]);
2654 /* Read in file-based context */
2655 read_nondefault_variables();
2656 read_backend_variables(backendID,&port);
2658 /* FIXME: [fork/exec] Ugh */
2665 proc_exit(BackendRun(&port));
2670 * Backend_forkexec -- fork/exec off a backend process
2673 * the pid of the fork/exec'd process
2676 Backend_forkexec(Port *port)
2680 int ac = 0, bufc = 0, i;
2681 char buf[2][MAXPGPATH];
2683 if (!write_backend_variables(port))
2684 return -1; /* log made by write_backend_variables */
2686 av[ac++] = "postgres";
2687 av[ac++] = "-forkexec";
2689 /* Format up context to pass to exec'd process */
2690 snprintf(buf[bufc++],MAXPGPATH,"%lu",tmpBackendFileNum);
2691 /* FIXME: [fork/exec] whitespaces in directories? */
2692 snprintf(buf[bufc++],MAXPGPATH,"%s",DataDir);
2694 /* Add to the arg list */
2695 Assert(bufc <= lengthof(buf));
2696 for (i = 0; i < bufc; i++)
2699 /* FIXME: [fork/exec] ExtraOptions? */
2702 Assert(ac <= lengthof(av));
2705 pid = win32_forkexec(pg_pathname,av); /* logs on error */
2707 /* Fire off execv in child */
2708 if ((pid = fork()) == 0 && (execv(pg_pathname,av) == -1))
2710 * FIXME: [fork/exec] suggestions for what to do here?
2711 * Probably OK to issue error (unlike pgstat case)
2715 return pid; /* Parent returns pid */
2722 * ExitPostmaster -- cleanup
2724 * Do NOT call exit() directly --- always go through here!
2727 ExitPostmaster(int status)
2729 /* should cleanup shared memory and kill all backends */
2732 * Not sure of the semantics here. When the Postmaster dies, should
2733 * the backends all be killed? probably not.
2735 * MUST -- vadim 05-10-1999
2737 /* Should I use true instead? */
2738 ClosePostmasterPorts(false);
2744 * sigusr1_handler - handle signal conditions from child processes
2747 sigusr1_handler(SIGNAL_ARGS)
2749 int save_errno = errno;
2751 PG_SETMASK(&BlockSig);
2753 if (CheckPostmasterSignal(PMSIGNAL_DO_CHECKPOINT))
2755 if (CheckPointWarning != 0)
2758 * This only times checkpoints forced by running out of
2759 * segment files. Other checkpoints could reduce the
2760 * frequency of forced checkpoints.
2762 time_t now = time(NULL);
2764 if (LastSignalledCheckpoint != 0)
2766 int elapsed_secs = now - LastSignalledCheckpoint;
2768 if (elapsed_secs < CheckPointWarning)
2770 (errmsg("checkpoints are occurring too frequently (%d seconds apart)",
2772 errhint("Consider increasing the configuration parameter \"checkpoint_segments\".")));
2774 LastSignalledCheckpoint = now;
2778 * Request to schedule a checkpoint
2780 * Ignore request if checkpoint is already running or checkpointing
2781 * is currently disabled
2783 if (CheckPointPID == 0 && checkpointed &&
2784 Shutdown == NoShutdown && !FatalError && random_seed != 0)
2786 CheckPointPID = CheckPointDataBase();
2787 /* note: if fork fails, CheckPointPID stays 0; nothing happens */
2791 if (CheckPostmasterSignal(PMSIGNAL_PASSWORD_CHANGE))
2794 * Password or group file has changed.
2800 if (CheckPostmasterSignal(PMSIGNAL_WAKEN_CHILDREN))
2803 * Send SIGUSR2 to all children (triggers AsyncNotifyHandler). See
2804 * storage/ipc/sinvaladt.c for the use of this.
2806 if (Shutdown == NoShutdown)
2807 SignalChildren(SIGUSR2);
2810 PG_SETMASK(&UnBlockSig);
2817 * Dummy signal handler
2819 * We use this for signals that we don't actually use in the postmaster,
2820 * but we do use in backends. If we SIG_IGN such signals in the postmaster,
2821 * then a newly started backend might drop a signal that arrives before it's
2822 * able to reconfigure its signal processing. (See notes in postgres.c.)
2825 dummy_handler(SIGNAL_ARGS)
2831 * CharRemap: given an int in range 0..61, produce textual encoding of it
2832 * per crypt(3) conventions.
2856 RandomSalt(char *cryptSalt, char *md5Salt)
2858 long rand = PostmasterRandom();
2860 cryptSalt[0] = CharRemap(rand % 62);
2861 cryptSalt[1] = CharRemap(rand / 62);
2864 * It's okay to reuse the first random value for one of the MD5 salt
2865 * bytes, since only one of the two salts will be sent to the client.
2866 * After that we need to compute more random bits.
2868 * We use % 255, sacrificing one possible byte value, so as to ensure
2869 * that all bits of the random() value participate in the result.
2870 * While at it, add one to avoid generating any null bytes.
2872 md5Salt[0] = (rand % 255) + 1;
2873 rand = PostmasterRandom();
2874 md5Salt[1] = (rand % 255) + 1;
2875 rand = PostmasterRandom();
2876 md5Salt[2] = (rand % 255) + 1;
2877 rand = PostmasterRandom();
2878 md5Salt[3] = (rand % 255) + 1;
2885 PostmasterRandom(void)
2887 static bool initialized = false;
2891 Assert(random_seed != 0);
2892 srandom(random_seed);
2900 * Count up number of child processes.
2909 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2911 bp = (Backend *) DLE_VAL(curr);
2912 if (bp->pid != MyProcPid)
2915 if (CheckPointPID != 0)
2917 if (BgWriterPID != 0)
2923 * Fire off a subprocess for startup/shutdown/checkpoint.
2925 * Return value of SSDataBase is subprocess' PID, or 0 if failed to start subprocess
2926 * (0 is returned only for checkpoint case).
2928 * note: in the EXEC_BACKEND case, we delay the fork until argument list has been
2931 NON_EXEC_STATIC void
2932 SSDataBaseInit(int xlop)
2934 const char *statmsg;
2936 IsUnderPostmaster = true; /* we are a postmaster subprocess
2939 /* Lose the postmaster's on-exit routines and port connections */
2943 * Identify myself via ps
2947 case BS_XLOG_STARTUP:
2948 statmsg = "startup subprocess";
2950 case BS_XLOG_CHECKPOINT:
2951 statmsg = "checkpoint subprocess";
2953 case BS_XLOG_BGWRITER:
2954 statmsg = "bgwriter subprocess";
2956 case BS_XLOG_SHUTDOWN:
2957 statmsg = "shutdown subprocess";
2960 statmsg = "??? subprocess";
2963 init_ps_display(statmsg, "", "");
2969 SSDataBase(int xlop)
2973 #ifndef EXEC_BACKEND
2974 #ifdef LINUX_PROFILE
2975 struct itimerval prof_itimer;
2984 #ifndef EXEC_BACKEND
2985 #ifdef LINUX_PROFILE
2986 /* see comments in BackendRun */
2987 getitimer(ITIMER_PROF, &prof_itimer);
2991 /* Specific beos actions before backend startup */
2992 beos_before_backend_startup();
2995 /* Non EXEC_BACKEND case; fork here */
2996 if ((pid = fork()) == 0) /* child */
3004 #ifndef EXEC_BACKEND
3005 #ifdef LINUX_PROFILE
3006 setitimer(ITIMER_PROF, &prof_itimer, NULL);
3010 /* Specific beos actions after backend startup */
3011 beos_backend_startup();
3014 /* Close the postmaster's sockets */
3015 ClosePostmasterPorts(true);
3017 SSDataBaseInit(xlop);
3019 if (!write_backend_variables(NULL))
3020 return -1; /* log issued by write_backend_variables */
3023 /* Set up command-line arguments for subprocess */
3024 av[ac++] = "postgres";
3029 snprintf(nbbuf, sizeof(nbbuf), "-B%d", NBuffers);
3032 snprintf(xlbuf, sizeof(xlbuf), "-x%d", xlop);
3036 /* pass data dir before end of secure switches (-p) */
3040 /* and the backend identifier + dbname */
3041 snprintf(idbuf, sizeof(idbuf), "-p%lu,template1", tmpBackendFileNum);
3045 av[ac++] = "template1";
3050 Assert(ac < lengthof(av));
3053 /* EXEC_BACKEND case; fork/exec here */
3055 pid = win32_forkexec(pg_pathname,av); /* logs on error */
3057 if ((pid = fork()) == 0 && (execv(pg_pathname,av) == -1))
3060 elog(ERROR,"unable to execv in SSDataBase: %m");
3065 BootstrapMain(ac, av);
3073 #ifndef EXEC_BACKEND
3075 /* Specific beos actions before backend startup */
3076 beos_backend_startup_failed();
3081 case BS_XLOG_STARTUP:
3083 (errmsg("could not fork startup process: %m")));
3085 case BS_XLOG_CHECKPOINT:
3087 (errmsg("could not fork checkpoint process: %m")));
3089 case BS_XLOG_BGWRITER:
3091 (errmsg("could not fork bgwriter process: %m")));
3093 case BS_XLOG_SHUTDOWN:
3095 (errmsg("could not fork shutdown process: %m")));
3099 (errmsg("could not fork process: %m")));
3104 * fork failure is fatal during startup/shutdown, but there's no
3105 * need to choke if a routine checkpoint or starting a background
3108 if (xlop == BS_XLOG_CHECKPOINT)
3110 if (xlop == BS_XLOG_BGWRITER)
3116 * The startup and shutdown processes are not considered normal
3117 * backends, but the checkpoint and bgwriter processes are.
3118 * They must be added to the list of backends.
3120 if (xlop == BS_XLOG_CHECKPOINT || xlop == BS_XLOG_BGWRITER)
3122 if (!(bn = (Backend *) malloc(sizeof(Backend))))
3125 (errcode(ERRCODE_OUT_OF_MEMORY),
3126 errmsg("out of memory")));
3131 bn->cancel_key = PostmasterRandom();
3132 DLAddHead(BackendList, DLNewElem(bn));
3135 * Since this code is executed periodically, it's a fine place to
3136 * do other actions that should happen every now and then on no
3137 * particular schedule. Such as...
3140 TouchSocketLockFile();
3148 * Create the opts file
3151 CreateOptsFile(int argc, char *argv[])
3153 char fullprogname[MAXPGPATH];
3154 char filename[MAXPGPATH];
3158 if (FindExec(fullprogname, argv[0], "postmaster") < 0)
3161 snprintf(filename, sizeof(filename), "%s/postmaster.opts", DataDir);
3163 if ((fp = fopen(filename, "w")) == NULL)
3165 elog(LOG, "could not create file \"%s\": %m", filename);
3169 fprintf(fp, "%s", fullprogname);
3170 for (i = 1; i < argc; i++)
3171 fprintf(fp, " '%s'", argv[i]);
3177 elog(LOG, "could not write file \"%s\": %m", filename);
3187 * This should be used only for reporting "interactive" errors (essentially,
3188 * bogus arguments on the command line). Once the postmaster is launched,
3189 * use ereport. In particular, don't use this for anything that occurs
3190 * after pmdaemonize.
3193 postmaster_error(const char *fmt,...)
3197 fprintf(stderr, "%s: ", progname);
3199 vfprintf(stderr, gettext(fmt), ap);
3201 fprintf(stderr, "\n");
3208 * The following need to be available to the read/write_backend_variables
3211 #include "storage/spin.h"
3212 extern XLogRecPtr RedoRecPtr;
3213 extern XLogwrtResult LogwrtResult;
3214 extern slock_t *ShmemLock;
3215 extern slock_t *ShmemIndexLock;
3216 extern void *ShmemIndexAlloc;
3217 typedef struct LWLock LWLock;
3218 extern LWLock *LWLockArray;
3219 extern slock_t *ProcStructLock;
3220 extern int pgStatSock;
3222 #define write_var(var,fp) fwrite((void*)&(var),sizeof(var),1,fp)
3223 #define read_var(var,fp) fread((void*)&(var),sizeof(var),1,fp)
3224 #define get_tmp_backend_file_name(buf,id) \
3228 "%s/%s/%s.backend_var.%lu", \
3230 PG_TEMP_FILES_DIR, \
3231 PG_TEMP_FILE_PREFIX, \
3236 write_backend_variables(Port *port)
3238 char filename[MAXPGPATH];
3240 get_tmp_backend_file_name(filename,++tmpBackendFileNum);
3243 fp = AllocateFile(filename, PG_BINARY_W);
3246 /* As per OpenTemporaryFile... */
3247 char dirname[MAXPGPATH];
3248 sprintf(dirname,"%s/%s",DataDir,PG_TEMP_FILES_DIR);
3249 mkdir(dirname, S_IRWXU);
3251 fp = AllocateFile(filename, PG_BINARY_W);
3255 (errcode_for_file_access(),
3256 errmsg("could not write to file \"%s\": %m", filename)));
3264 write_var(port->sock,fp);
3265 write_var(port->proto,fp);
3266 write_var(port->laddr,fp);
3267 write_var(port->raddr,fp);
3268 write_var(port->canAcceptConnections,fp);
3269 write_var(port->cryptSalt,fp);
3270 write_var(port->md5Salt,fp);
3272 write_var(MyCancelKey,fp);
3274 write_var(RedoRecPtr,fp);
3275 write_var(LogwrtResult,fp);
3277 write_var(UsedShmemSegID,fp);
3278 write_var(UsedShmemSegAddr,fp);
3280 write_var(ShmemLock,fp);
3281 write_var(ShmemIndexLock,fp);
3282 write_var(ShmemVariableCache,fp);
3283 write_var(ShmemIndexAlloc,fp);
3285 write_var(LWLockArray,fp);
3286 write_var(ProcStructLock,fp);
3287 write_var(pgStatSock,fp);
3289 write_var(PreAuthDelay,fp);
3290 write_var(debug_flag,fp);
3298 read_backend_variables(unsigned long id, Port *port)
3300 char filename[MAXPGPATH];
3302 get_tmp_backend_file_name(filename,id);
3305 fp = AllocateFile(filename, PG_BINARY_R);
3309 (errcode_for_file_access(),
3310 errmsg("could not read from backend_variables file \"%s\": %m", filename)));
3317 read_var(port->sock,fp);
3318 read_var(port->proto,fp);
3319 read_var(port->laddr,fp);
3320 read_var(port->raddr,fp);
3321 read_var(port->canAcceptConnections,fp);
3322 read_var(port->cryptSalt,fp);
3323 read_var(port->md5Salt,fp);
3325 read_var(MyCancelKey,fp);
3327 read_var(RedoRecPtr,fp);
3328 read_var(LogwrtResult,fp);
3330 read_var(UsedShmemSegID,fp);
3331 read_var(UsedShmemSegAddr,fp);
3333 read_var(ShmemLock,fp);
3334 read_var(ShmemIndexLock,fp);
3335 read_var(ShmemVariableCache,fp);
3336 read_var(ShmemIndexAlloc,fp);
3338 read_var(LWLockArray,fp);
3339 read_var(ProcStructLock,fp);
3340 read_var(pgStatSock,fp);
3342 read_var(PreAuthDelay,fp);
3343 read_var(debug_flag,fp);
3347 if (unlink(filename) != 0)
3349 (errcode_for_file_access(),
3350 errmsg("could not remove file \"%s\": %m", filename)));
3357 pid_t win32_forkexec(const char* path, char *argv[])
3360 PROCESS_INFORMATION pi;
3363 char cmdLine[MAXPGPATH];
3365 /* Format the cmd line */
3366 snprintf(cmdLine,sizeof(cmdLine),"%s",path);
3368 while (argv[++i] != NULL)
3370 /* FIXME: [fork/exec] some strlen checks might be prudent here */
3371 strcat(cmdLine," ");
3372 strcat(cmdLine,argv[i]);
3376 * The following snippet can disappear when we consistently
3377 * use forward slashes.
3380 while (*(p++) != '\0')
3381 if (*p == '/') *p = '\\';
3383 memset(&pi,0,sizeof(pi));
3384 memset(&si,0,sizeof(si));
3386 if (!CreateProcess(NULL,cmdLine,NULL,NULL,TRUE,0,NULL,NULL,&si,&pi))
3388 elog(ERROR,"CreateProcess call failed (%d): %m",GetLastError());
3393 FIXME: [fork/exec] we might need to keep the following handle/s,
3394 depending on how we implement signalling.
3396 CloseHandle(pi.hProcess);
3397 CloseHandle(pi.hThread);
3399 return pi.dwProcessId;