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.353 2003/12/25 03:52:51 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 = (char *) 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 NON_EXEC_STATIC bool BackendInit(Port *port);
277 static int BackendFork(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)));
300 void read_backend_variables(pid_t pid, Port *port);
301 static void write_backend_variables(pid_t pid, Port *port);
304 #define StartupDataBase() SSDataBase(BS_XLOG_STARTUP)
305 #define CheckPointDataBase() SSDataBase(BS_XLOG_CHECKPOINT)
306 #define StartBackgroundWriter() SSDataBase(BS_XLOG_BGWRITER)
307 #define ShutdownDataBase() SSDataBase(BS_XLOG_SHUTDOWN)
311 checkDataDir(const char *checkdir)
313 char path[MAXPGPATH];
315 struct stat stat_buf;
317 if (checkdir == NULL)
320 gettext("%s does not know where to find the database system data.\n"
321 "You must specify the directory that contains the database system\n"
322 "either by specifying the -D invocation option or by setting the\n"
323 "PGDATA environment variable.\n"),
328 if (stat(checkdir, &stat_buf) == -1)
332 (errcode_for_file_access(),
333 errmsg("data directory \"%s\" does not exist",
337 (errcode_for_file_access(),
338 errmsg("could not read permissions of directory \"%s\": %m",
343 * Check if the directory has group or world access. If so, reject.
345 * XXX temporarily suppress check when on Windows, because there may not
346 * be proper support for Unix-y file permissions. Need to think of a
347 * reasonable check to apply on Windows.
349 #if !defined(__CYGWIN__) && !defined(WIN32)
350 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
352 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
353 errmsg("data directory \"%s\" has group or world access",
355 errdetail("Permissions should be u=rwx (0700).")));
358 /* Look for PG_VERSION before looking for pg_control */
359 ValidatePgVersion(checkdir);
361 snprintf(path, sizeof(path), "%s/global/pg_control", checkdir);
363 fp = AllocateFile(path, PG_BINARY_R);
367 gettext("%s: could not find the database system\n"
368 "Expected to find it in the directory \"%s\",\n"
369 "but could not open file \"%s\": %s\n"),
370 progname, checkdir, path, strerror(errno));
377 #ifdef USE_RENDEZVOUS
379 /* reg_reply -- empty callback function for DNSServiceRegistrationCreate() */
381 reg_reply(DNSServiceRegistrationReplyErrorType errorCode, void *context)
388 PostmasterMain(int argc, char *argv[])
392 char original_extraoptions[MAXPGPATH];
393 char *potential_DataDir = NULL;
396 *original_extraoptions = '\0';
400 IsPostmasterEnvironment = true;
403 * Catch standard options before doing much else. This even works on
404 * systems without getopt_long.
408 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
413 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
415 puts("postmaster (PostgreSQL) " PG_VERSION);
421 * for security, no dir or file created can be group or other
424 umask((mode_t) 0077);
426 MyProcPid = getpid();
429 * Fire up essential subsystems: memory management
434 * By default, palloc() requests in the postmaster will be allocated
435 * in the PostmasterContext, which is space that can be recycled by
436 * backends. Allocated data that needs to be available to backends
437 * should be allocated in TopMemoryContext.
439 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
441 ALLOCSET_DEFAULT_MINSIZE,
442 ALLOCSET_DEFAULT_INITSIZE,
443 ALLOCSET_DEFAULT_MAXSIZE);
444 MemoryContextSwitchTo(PostmasterContext);
446 IgnoreSystemIndexes(false);
451 InitializeGUCOptions();
453 potential_DataDir = getenv("PGDATA"); /* default value */
457 while ((opt = getopt(argc, argv, "A:a:B:b:c:D:d:Fh:ik:lm:MN:no:p:Ss-:")) != -1)
462 #ifdef USE_ASSERT_CHECKING
463 SetConfigOption("debug_assertions", optarg, PGC_POSTMASTER, PGC_S_ARGV);
465 postmaster_error("assert checking is not compiled in");
469 /* Can no longer set authentication method. */
472 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
475 /* Can no longer set the backend executable file to use. */
478 potential_DataDir = optarg;
482 /* Turn on debugging for the postmaster. */
483 char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
485 sprintf(debugstr, "debug%s", optarg);
486 SetConfigOption("log_min_messages", debugstr,
487 PGC_POSTMASTER, PGC_S_ARGV);
489 debug_flag = atoi(optarg);
493 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
496 SetConfigOption("virtual_host", optarg, PGC_POSTMASTER, PGC_S_ARGV);
499 SetConfigOption("tcpip_socket", "true", PGC_POSTMASTER, PGC_S_ARGV);
502 SetConfigOption("unix_socket_directory", optarg, PGC_POSTMASTER, PGC_S_ARGV);
506 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
510 /* Multiplexed backends no longer supported. */
515 * ignore this flag. This may be passed in because the
516 * program was run as 'postgres -M' instead of
521 /* The max number of backends to start. */
522 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
525 /* Don't reinit shared mem after abnormal exit */
531 * Other options to pass to the backend on the command
532 * line -- useful only for debugging.
534 strcat(ExtraOptions, " ");
535 strcat(ExtraOptions, optarg);
536 strcpy(original_extraoptions, optarg);
539 SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
544 * Start in 'S'ilent mode (disassociate from controlling
545 * tty). You may also think of this as 'S'ysV mode since
546 * it's most badly needed on SysV-derived systems like
549 SetConfigOption("silent_mode", "true", PGC_POSTMASTER, PGC_S_ARGV);
554 * In the event that some backend dumps core, send
555 * SIGSTOP, rather than SIGQUIT, to all its peers. This
556 * lets the wily post_hacker collect core dumps from
567 ParseLongOption(optarg, &name, &value);
572 (errcode(ERRCODE_SYNTAX_ERROR),
573 errmsg("--%s requires a value",
577 (errcode(ERRCODE_SYNTAX_ERROR),
578 errmsg("-c %s requires a value",
582 SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
591 gettext("Try \"%s --help\" for more information.\n"),
598 * Postmaster accepts no non-option switch arguments.
602 postmaster_error("invalid argument: \"%s\"", argv[optind]);
604 gettext("Try \"%s --help\" for more information.\n"),
610 * Now we can set the data directory, and then read postgresql.conf.
612 checkDataDir(potential_DataDir); /* issues error messages */
613 SetDataDir(potential_DataDir);
615 ProcessConfigFile(PGC_POSTMASTER);
617 write_nondefault_variables(PGC_POSTMASTER);
621 * Check for invalid combinations of GUC settings.
623 if (NBuffers < 2 * MaxBackends || NBuffers < 16)
626 * Do not accept -B so small that backends are likely to starve
627 * for lack of buffers. The specific choices here are somewhat
630 postmaster_error("the number of buffers (-B) must be at least twice the number of allowed connections (-N) and at least 16");
634 if (ReservedBackends >= MaxBackends)
636 postmaster_error("superuser_reserved_connections must be less than max_connections");
641 * Other one-time internal sanity checks can go here.
643 if (!CheckDateTokenTables())
645 postmaster_error("invalid datetoken tables, please fix");
650 * Now that we are done processing the postmaster arguments, reset
651 * getopt(3) library so that it will work correctly in subprocesses.
654 #ifdef HAVE_INT_OPTRESET
655 optreset = 1; /* some systems need this too */
658 /* For debugging: display postmaster environment */
660 extern char **environ;
664 (errmsg_internal("%s: PostmasterMain: initial environ dump:",
667 (errmsg_internal("-----------------------------------------")));
668 for (p = environ; *p; ++p)
670 (errmsg_internal("\t%s", *p)));
672 (errmsg_internal("-----------------------------------------")));
676 * On some systems our dynloader code needs the executable's pathname.
678 if (FindExec(pg_pathname, progname, "postgres") < 0)
680 (errmsg("%s: could not locate postgres executable",
684 * Initialize SSL library, if specified.
687 if (EnableSSL && !NetServer)
689 postmaster_error("TCP/IP connections must be enabled for SSL");
697 * process any libraries that should be preloaded and optionally
700 if (preload_libraries_string)
701 process_preload_libraries(preload_libraries_string);
704 * Fork away from controlling terminal, if -S specified.
706 * Must do this before we grab any interlock files, else the interlocks
707 * will show the wrong PID.
710 pmdaemonize(argc, argv);
713 * Create lockfile for data directory.
715 * We want to do this before we try to grab the input sockets, because
716 * the data directory interlock is more reliable than the socket-file
717 * interlock (thanks to whoever decided to put socket files in /tmp
718 * :-(). For the same reason, it's best to grab the TCP socket before
721 CreateDataDirLockFile(DataDir, true);
724 * Remove old temporary files. At this point there can be no other
725 * Postgres processes running in this directory, so this should be
731 * Establish input sockets.
733 for (i = 0; i < MAXLISTEN; i++)
734 ListenSocket[i] = -1;
738 if (VirtualHost && VirtualHost[0])
744 curhost = VirtualHost;
747 while (*curhost == ' ') /* skip any extra spaces */
749 if (*curhost == '\0')
751 endptr = strchr(curhost, ' ');
757 status = StreamServerPort(AF_UNSPEC, curhost,
758 (unsigned short) PostPortNumber,
760 ListenSocket, MAXLISTEN);
761 if (status != STATUS_OK)
763 (errmsg("could not create listen socket for \"%s\"",
768 curhost = endptr + 1;
776 status = StreamServerPort(AF_UNSPEC, NULL,
777 (unsigned short) PostPortNumber,
779 ListenSocket, MAXLISTEN);
780 if (status != STATUS_OK)
782 (errmsg("could not create TCP/IP listen socket")));
785 #ifdef USE_RENDEZVOUS
786 if (rendezvous_name != NULL)
788 DNSServiceRegistrationCreate(rendezvous_name,
791 htonl(PostPortNumber),
793 (DNSServiceRegistrationReply) reg_reply,
799 #ifdef HAVE_UNIX_SOCKETS
800 status = StreamServerPort(AF_UNIX, NULL,
801 (unsigned short) PostPortNumber,
803 ListenSocket, MAXLISTEN);
804 if (status != STATUS_OK)
806 (errmsg("could not create Unix-domain socket")));
812 * Set up shared memory and semaphores.
814 reset_shared(PostPortNumber);
817 * Initialize the list of active backends.
819 BackendList = DLNewList();
822 * Record postmaster options. We delay this till now to avoid
823 * recording bogus options (eg, NBuffers too high for available
826 if (!CreateOptsFile(argc, argv))
830 * Set up signal handlers for the postmaster process.
832 * CAUTION: when changing this list, check for side-effects on the signal
833 * handling setup of child processes. See tcop/postgres.c,
834 * bootstrap/bootstrap.c, and postmaster/pgstat.c.
837 PG_SETMASK(&BlockSig);
839 pqsignal(SIGHUP, SIGHUP_handler); /* reread config file and have
840 * children do same */
841 pqsignal(SIGINT, pmdie); /* send SIGTERM and ShutdownDataBase */
842 pqsignal(SIGQUIT, pmdie); /* send SIGQUIT and die */
843 pqsignal(SIGTERM, pmdie); /* wait for children and ShutdownDataBase */
844 pqsignal(SIGALRM, SIG_IGN); /* ignored */
845 pqsignal(SIGPIPE, SIG_IGN); /* ignored */
846 pqsignal(SIGUSR1, sigusr1_handler); /* message from child process */
847 pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
848 pqsignal(SIGCHLD, reaper); /* handle child termination */
849 pqsignal(SIGTTIN, SIG_IGN); /* ignored */
850 pqsignal(SIGTTOU, SIG_IGN); /* ignored */
851 /* ignore SIGXFSZ, so that ulimit violations work like disk full */
853 pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
857 * Reset whereToSendOutput from Debug (its starting state) to None.
858 * This prevents ereport from sending log messages to stderr unless
859 * the syslog/stderr switch permits. We don't do this until the
860 * postmaster is fully launched, since startup failures may as well be
861 * reported to stderr.
863 whereToSendOutput = None;
866 * On many platforms, the first call of localtime() incurs significant
867 * overhead to load timezone info from the system configuration files.
868 * By doing it once in the postmaster, we avoid having to do it in
869 * every started child process. The savings are not huge, but they
873 time_t now = time(NULL);
875 (void) localtime(&now);
879 * Initialize and try to startup the statistics collector process
885 * Load cached files for client authentication.
893 * We're ready to rock and roll...
895 StartupPID = StartupDataBase();
897 status = ServerLoop();
900 * ServerLoop probably shouldn't ever return, but if it does, close
903 ExitPostmaster(status != STATUS_OK);
905 return 0; /* not reached */
909 pmdaemonize(int argc, char *argv[])
915 struct itimerval prof_itimer;
919 /* see comments in BackendStartup */
920 getitimer(ITIMER_PROF, &prof_itimer);
924 if (pid == (pid_t) -1)
926 postmaster_error("could not fork background process: %s",
932 /* Parent should just exit, without doing any atexit cleanup */
937 setitimer(ITIMER_PROF, &prof_itimer, NULL);
940 MyProcPid = getpid(); /* reset MyProcPid to child */
942 /* GH: If there's no setsid(), we hopefully don't need silent mode.
943 * Until there's a better solution.
948 postmaster_error("could not dissociate from controlling TTY: %s",
953 i = open(NULL_DEV, O_RDWR | PG_BINARY);
963 * Print out help message
966 usage(const char *progname)
968 printf(gettext("%s is the PostgreSQL server.\n\n"), progname);
969 printf(gettext("Usage:\n %s [OPTION]...\n\n"), progname);
970 printf(gettext("Options:\n"));
971 #ifdef USE_ASSERT_CHECKING
972 printf(gettext(" -A 1|0 enable/disable run-time assert checking\n"));
974 printf(gettext(" -B NBUFFERS number of shared buffers\n"));
975 printf(gettext(" -c NAME=VALUE set run-time parameter\n"));
976 printf(gettext(" -d 1-5 debugging level\n"));
977 printf(gettext(" -D DATADIR database directory\n"));
978 printf(gettext(" -F turn fsync off\n"));
979 printf(gettext(" -h HOSTNAME host name or IP address to listen on\n"));
980 printf(gettext(" -i enable TCP/IP connections\n"));
981 printf(gettext(" -k DIRECTORY Unix-domain socket location\n"));
983 printf(gettext(" -l enable SSL connections\n"));
985 printf(gettext(" -N MAX-CONNECT maximum number of allowed connections\n"));
986 printf(gettext(" -o OPTIONS pass \"OPTIONS\" to each server process\n"));
987 printf(gettext(" -p PORT port number to listen on\n"));
988 printf(gettext(" -S silent mode (start in background without logging output)\n"));
989 printf(gettext(" --help show this help, then exit\n"));
990 printf(gettext(" --version output version information, then exit\n"));
992 printf(gettext("\nDeveloper options:\n"));
993 printf(gettext(" -n do not reinitialize shared memory after abnormal exit\n"));
994 printf(gettext(" -s send SIGSTOP to all backend servers if one dies\n"));
996 printf(gettext("\nPlease read the documentation for the complete list of run-time\n"
997 "configuration settings and how to set them on the command line or in\n"
998 "the configuration file.\n\n"
999 "Report bugs to <pgsql-bugs@postgresql.org>.\n"));
1012 gettimeofday(&now, &tz);
1014 nSockets = initMasks(&readmask);
1020 struct timeval timeout;
1023 * The timeout for the select() below is normally set on the basis
1024 * of the time to the next checkpoint. However, if for some
1025 * reason we don't have a next-checkpoint time, time out after 60
1026 * seconds. This keeps checkpoint scheduling from locking up when
1027 * we get new connection requests infrequently (since we are
1028 * likely to detect checkpoint completion just after enabling
1029 * signals below, after we've already made the decision about how
1030 * long to wait this time).
1032 timeout.tv_sec = 60;
1033 timeout.tv_usec = 0;
1035 if (CheckPointPID == 0 && checkpointed &&
1036 Shutdown == NoShutdown && !FatalError && random_seed != 0)
1038 time_t now = time(NULL);
1040 if (CheckPointTimeout + checkpointed > now)
1043 * Not time for checkpoint yet, so set select timeout
1045 timeout.tv_sec = CheckPointTimeout + checkpointed - now;
1049 /* Time to make the checkpoint... */
1050 CheckPointPID = CheckPointDataBase();
1053 * if fork failed, schedule another try at 0.1 normal
1056 if (CheckPointPID == 0)
1058 timeout.tv_sec = CheckPointTimeout / 10;
1059 checkpointed = now + timeout.tv_sec - CheckPointTimeout;
1065 * If no background writer process is running and we should
1066 * do background writing, start one. It doesn't matter if
1067 * this fails, we'll just try again later.
1069 if (BgWriterPID == 0 && BgWriterPercent > 0 &&
1070 Shutdown == NoShutdown && !FatalError && random_seed != 0)
1072 BgWriterPID = StartBackgroundWriter();
1076 * Wait for something to happen.
1078 memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
1080 PG_SETMASK(&UnBlockSig);
1082 if (select(nSockets, &rmask, (fd_set *) NULL,
1083 (fd_set *) NULL, &timeout) < 0)
1085 PG_SETMASK(&BlockSig);
1086 if (errno == EINTR || errno == EWOULDBLOCK)
1089 (errcode_for_socket_access(),
1090 errmsg("select() failed in postmaster: %m")));
1091 return STATUS_ERROR;
1095 * Block all signals until we wait again. (This makes it safe for
1096 * our signal handlers to do nontrivial work.)
1098 PG_SETMASK(&BlockSig);
1101 * Select a random seed at the time of first receiving a request.
1103 while (random_seed == 0)
1105 gettimeofday(&later, &tz);
1108 * We are not sure how much precision is in tv_usec, so we
1109 * swap the nibbles of 'later' and XOR them with 'now'. On the
1110 * off chance that the result is 0, we loop until it isn't.
1112 random_seed = now.tv_usec ^
1113 ((later.tv_usec << 16) |
1114 ((later.tv_usec >> 16) & 0xffff));
1118 * New connection pending on any of our sockets? If so, fork a
1119 * child process to deal with it.
1121 for (i = 0; i < MAXLISTEN; i++)
1123 if (ListenSocket[i] == -1)
1125 if (FD_ISSET(ListenSocket[i], &rmask))
1127 port = ConnCreate(ListenSocket[i]);
1130 BackendStartup(port);
1133 * We no longer need the open socket or port structure
1136 StreamClose(port->sock);
1142 /* If we have lost the stats collector, try to start a new one */
1143 if (!pgstat_is_running)
1150 * Initialise the masks for select() for the ports
1151 * we are listening on. Return the number of sockets to listen on.
1155 initMasks(fd_set *rmask)
1162 for (i = 0; i < MAXLISTEN; i++)
1164 int fd = ListenSocket[i];
1178 * Read the startup packet and do something according to it.
1180 * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
1181 * not return at all.
1183 * (Note that ereport(FATAL) stuff is sent to the client, so only use it
1184 * if that's what you want. Return STATUS_ERROR if you don't want to
1185 * send anything to the client, which would typically be appropriate
1186 * if we detect a communications failure.)
1189 ProcessStartupPacket(Port *port, bool SSLdone)
1193 ProtocolVersion proto;
1194 MemoryContext oldcontext;
1196 if (pq_getbytes((char *) &len, 4) == EOF)
1199 * EOF after SSLdone probably means the client didn't like our
1200 * response to NEGOTIATE_SSL_CODE. That's not an error condition,
1201 * so don't clutter the log with a complaint.
1205 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1206 errmsg("incomplete startup packet")));
1207 return STATUS_ERROR;
1213 if (len < (int32) sizeof(ProtocolVersion) ||
1214 len > MAX_STARTUP_PACKET_LENGTH)
1217 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1218 errmsg("invalid length of startup packet")));
1219 return STATUS_ERROR;
1223 * Allocate at least the size of an old-style startup packet, plus one
1224 * extra byte, and make sure all are zeroes. This ensures we will
1225 * have null termination of all strings, in both fixed- and
1226 * variable-length packet layouts.
1228 if (len <= (int32) sizeof(StartupPacket))
1229 buf = palloc0(sizeof(StartupPacket) + 1);
1231 buf = palloc0(len + 1);
1233 if (pq_getbytes(buf, len) == EOF)
1236 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1237 errmsg("incomplete startup packet")));
1238 return STATUS_ERROR;
1242 * The first field is either a protocol version number or a special
1245 port->proto = proto = ntohl(*((ProtocolVersion *) buf));
1247 if (proto == CANCEL_REQUEST_CODE)
1250 abort(); /* FIXME: [fork/exec] Whoops. Not handled... yet */
1252 processCancelRequest(port, buf);
1254 return 127; /* XXX */
1257 if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
1262 /* No SSL when disabled or on Unix sockets */
1263 if (!EnableSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
1266 SSLok = 'S'; /* Support for SSL */
1268 SSLok = 'N'; /* No support for SSL */
1270 if (send(port->sock, &SSLok, 1, 0) != 1)
1273 (errcode_for_socket_access(),
1274 errmsg("failed to send SSL negotiation response: %m")));
1275 return STATUS_ERROR; /* close the connection */
1279 if (SSLok == 'S' && secure_open_server(port) == -1)
1280 return STATUS_ERROR;
1282 /* regular startup packet, cancel, etc packet should follow... */
1283 /* but not another SSL negotiation request */
1284 return ProcessStartupPacket(port, true);
1287 /* Could add additional special packet types here */
1290 * Set FrontendProtocol now so that ereport() knows what format to
1291 * send if we fail during startup.
1293 FrontendProtocol = proto;
1295 /* Check we can handle the protocol the frontend is using. */
1297 if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
1298 PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
1299 (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
1300 PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
1302 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1303 errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
1304 PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
1305 PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST),
1306 PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST),
1307 PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))));
1310 * Now fetch parameters out of startup packet and save them into the
1311 * Port structure. All data structures attached to the Port struct
1312 * must be allocated in TopMemoryContext so that they won't disappear
1313 * when we pass them to PostgresMain (see BackendFork). We need not
1314 * worry about leaking this storage on failure, since we aren't in the
1315 * postmaster process anymore.
1317 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1319 if (PG_PROTOCOL_MAJOR(proto) >= 3)
1321 int32 offset = sizeof(ProtocolVersion);
1324 * Scan packet body for name/option pairs. We can assume any
1325 * string beginning within the packet body is null-terminated,
1326 * thanks to zeroing extra byte above.
1328 port->guc_options = NIL;
1330 while (offset < len)
1332 char *nameptr = ((char *) buf) + offset;
1336 if (*nameptr == '\0')
1337 break; /* found packet terminator */
1338 valoffset = offset + strlen(nameptr) + 1;
1339 if (valoffset >= len)
1340 break; /* missing value, will complain below */
1341 valptr = ((char *) buf) + valoffset;
1343 if (strcmp(nameptr, "database") == 0)
1344 port->database_name = pstrdup(valptr);
1345 else if (strcmp(nameptr, "user") == 0)
1346 port->user_name = pstrdup(valptr);
1347 else if (strcmp(nameptr, "options") == 0)
1348 port->cmdline_options = pstrdup(valptr);
1351 /* Assume it's a generic GUC option */
1352 port->guc_options = lappend(port->guc_options,
1354 port->guc_options = lappend(port->guc_options,
1357 offset = valoffset + strlen(valptr) + 1;
1361 * If we didn't find a packet terminator exactly at the end of the
1362 * given packet length, complain.
1364 if (offset != len - 1)
1366 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1367 errmsg("invalid startup packet layout: expected terminator as last byte")));
1372 * Get the parameters from the old-style, fixed-width-fields
1373 * startup packet as C strings. The packet destination was
1374 * cleared first so a short packet has zeros silently added. We
1375 * have to be prepared to truncate the pstrdup result for oversize
1378 StartupPacket *packet = (StartupPacket *) buf;
1380 port->database_name = pstrdup(packet->database);
1381 if (strlen(port->database_name) > sizeof(packet->database))
1382 port->database_name[sizeof(packet->database)] = '\0';
1383 port->user_name = pstrdup(packet->user);
1384 if (strlen(port->user_name) > sizeof(packet->user))
1385 port->user_name[sizeof(packet->user)] = '\0';
1386 port->cmdline_options = pstrdup(packet->options);
1387 if (strlen(port->cmdline_options) > sizeof(packet->options))
1388 port->cmdline_options[sizeof(packet->options)] = '\0';
1389 port->guc_options = NIL;
1392 /* Check a user name was given. */
1393 if (port->user_name == NULL || port->user_name[0] == '\0')
1395 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1396 errmsg("no PostgreSQL user name specified in startup packet")));
1398 /* The database defaults to the user name. */
1399 if (port->database_name == NULL || port->database_name[0] == '\0')
1400 port->database_name = pstrdup(port->user_name);
1402 if (Db_user_namespace)
1405 * If user@, it is a global user, remove '@'. We only want to do
1406 * this if there is an '@' at the end and no earlier in the user
1407 * string or they may fake as a local user of another database
1408 * attaching to this database.
1410 if (strchr(port->user_name, '@') ==
1411 port->user_name + strlen(port->user_name) - 1)
1412 *strchr(port->user_name, '@') = '\0';
1415 /* Append '@' and dbname */
1418 db_user = palloc(strlen(port->user_name) +
1419 strlen(port->database_name) + 2);
1420 sprintf(db_user, "%s@%s", port->user_name, port->database_name);
1421 port->user_name = db_user;
1426 * Truncate given database and user names to length of a Postgres
1427 * name. This avoids lookup failures when overlength names are given.
1429 if (strlen(port->database_name) >= NAMEDATALEN)
1430 port->database_name[NAMEDATALEN - 1] = '\0';
1431 if (strlen(port->user_name) >= NAMEDATALEN)
1432 port->user_name[NAMEDATALEN - 1] = '\0';
1435 * Done putting stuff in TopMemoryContext.
1437 MemoryContextSwitchTo(oldcontext);
1440 * If we're going to reject the connection due to database state, say
1441 * so now instead of wasting cycles on an authentication exchange.
1442 * (This also allows a pg_ping utility to be written.)
1444 switch (port->canAcceptConnections)
1448 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1449 errmsg("the database system is starting up")));
1453 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1454 errmsg("the database system is shutting down")));
1458 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1459 errmsg("the database system is in recovery mode")));
1463 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
1464 errmsg("sorry, too many clients already")));
1476 * The client has sent a cancel request packet, not a normal
1477 * start-a-new-connection packet. Perform the necessary processing.
1478 * Nothing is sent back to the client.
1481 processCancelRequest(Port *port, void *pkt)
1483 CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
1485 long cancelAuthCode;
1489 backendPID = (int) ntohl(canc->backendPID);
1490 cancelAuthCode = (long) ntohl(canc->cancelAuthCode);
1492 if (backendPID == CheckPointPID)
1495 (errmsg_internal("ignoring cancel request for checkpoint process %d",
1499 else if (backendPID == BgWriterPID)
1502 (errmsg_internal("ignoring cancel request for bgwriter process %d",
1508 AttachSharedMemoryAndSemaphores();
1511 /* See if we have a matching backend */
1513 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
1515 bp = (Backend *) DLE_VAL(curr);
1516 if (bp->pid == backendPID)
1518 if (bp->cancel_key == cancelAuthCode)
1520 /* Found a match; signal that backend to cancel current op */
1522 (errmsg_internal("processing cancel request: sending SIGINT to process %d",
1524 kill(bp->pid, SIGINT);
1527 /* Right PID, wrong key: no way, Jose */
1529 (errmsg_internal("bad key in cancel request for process %d",
1535 /* No matching backend */
1537 (errmsg_internal("bad pid in cancel request for process %d",
1542 * canAcceptConnections --- check to see if database state allows connections.
1544 static enum CAC_state
1545 canAcceptConnections(void)
1547 /* Can't start backends when in startup/shutdown/recovery state. */
1548 if (Shutdown > NoShutdown)
1549 return CAC_SHUTDOWN;
1553 return CAC_RECOVERY;
1556 * Don't start too many children.
1558 * We allow more connections than we can have backends here because some
1559 * might still be authenticating; they might fail auth, or some
1560 * existing backend might exit before the auth cycle is completed. The
1561 * exact MaxBackends limit is enforced when a new backend tries to
1562 * join the shared-inval backend array.
1564 if (CountChildren() >= 2 * MaxBackends)
1572 * ConnCreate -- create a local connection data structure
1575 ConnCreate(int serverFd)
1579 if (!(port = (Port *) calloc(1, sizeof(Port))))
1582 (errcode(ERRCODE_OUT_OF_MEMORY),
1583 errmsg("out of memory")));
1587 if (StreamConnection(serverFd, port) != STATUS_OK)
1589 StreamClose(port->sock);
1596 * Precompute password salt values to use for this connection.
1597 * It's slightly annoying to do this long in advance of knowing
1598 * whether we'll need 'em or not, but we must do the random()
1599 * calls before we fork, not after. Else the postmaster's random
1600 * sequence won't get advanced, and all backends would end up
1601 * using the same salt...
1603 RandomSalt(port->cryptSalt, port->md5Salt);
1611 * ConnFree -- free a local connection data structure
1614 ConnFree(Port *conn)
1624 * ClosePostmasterPorts -- close all the postmaster's open sockets
1626 * This is called during child process startup to release file descriptors
1627 * that are not needed by that child process. The postmaster still has
1628 * them open, of course.
1631 ClosePostmasterPorts(bool pgstat_too)
1635 /* Close the listen sockets */
1636 for (i = 0; i < MAXLISTEN; i++)
1638 if (ListenSocket[i] != -1)
1640 StreamClose(ListenSocket[i]);
1641 ListenSocket[i] = -1;
1645 /* Close pgstat control sockets, unless we're starting pgstat itself */
1647 pgstat_close_sockets();
1652 * reset_shared -- reset shared memory and semaphores
1655 reset_shared(unsigned short port)
1658 * Create or re-create shared memory and semaphores.
1660 * Note: in each "cycle of life" we will normally assign the same IPC
1661 * keys (if using SysV shmem and/or semas), since the port number is
1662 * used to determine IPC keys. This helps ensure that we will clean
1663 * up dead IPC objects if the postmaster crashes and is restarted.
1665 CreateSharedMemoryAndSemaphores(false, MaxBackends, port);
1670 * SIGHUP -- reread config files, and tell children to do same
1673 SIGHUP_handler(SIGNAL_ARGS)
1675 int save_errno = errno;
1677 PG_SETMASK(&BlockSig);
1679 if (Shutdown <= SmartShutdown)
1682 (errmsg("received SIGHUP, reloading configuration files")));
1683 ProcessConfigFile(PGC_SIGHUP);
1685 write_nondefault_variables(PGC_SIGHUP);
1687 SignalChildren(SIGHUP);
1692 * Tell the background writer to terminate so that we
1693 * will start a new one with a possibly changed config
1695 if (BgWriterPID != 0)
1696 kill(BgWriterPID, SIGTERM);
1699 PG_SETMASK(&UnBlockSig);
1707 * pmdie -- signal handler for processing various postmaster signals.
1712 int save_errno = errno;
1714 PG_SETMASK(&BlockSig);
1717 (errmsg_internal("postmaster received signal %d",
1718 postgres_signal_arg)));
1720 switch (postgres_signal_arg)
1727 * Wait for children to end their work and ShutdownDataBase.
1729 if (BgWriterPID != 0)
1730 kill(BgWriterPID, SIGTERM);
1731 if (Shutdown >= SmartShutdown)
1733 Shutdown = SmartShutdown;
1735 (errmsg("received smart shutdown request")));
1736 if (DLGetHead(BackendList)) /* let reaper() handle this */
1740 * No children left. Shutdown data base system.
1742 if (StartupPID > 0 || FatalError) /* let reaper() handle
1745 if (ShutdownPID > 0)
1747 elog(PANIC, "shutdown process %d already running",
1752 ShutdownPID = ShutdownDataBase();
1760 * abort all children with SIGTERM (rollback active transactions
1761 * and exit) and ShutdownDataBase when they are gone.
1763 if (BgWriterPID != 0)
1764 kill(BgWriterPID, SIGTERM);
1765 if (Shutdown >= FastShutdown)
1768 (errmsg("received fast shutdown request")));
1769 if (DLGetHead(BackendList)) /* let reaper() handle this */
1771 Shutdown = FastShutdown;
1775 (errmsg("aborting any active transactions")));
1776 SignalChildren(SIGTERM);
1780 if (Shutdown > NoShutdown)
1782 Shutdown = FastShutdown;
1785 Shutdown = FastShutdown;
1788 * No children left. Shutdown data base system.
1790 if (StartupPID > 0 || FatalError) /* let reaper() handle
1793 if (ShutdownPID > 0)
1795 elog(PANIC, "shutdown process %d already running",
1800 ShutdownPID = ShutdownDataBase();
1806 * Immediate Shutdown:
1808 * abort all children with SIGQUIT and exit without attempt to
1809 * properly shutdown data base system.
1811 if (BgWriterPID != 0)
1812 kill(BgWriterPID, SIGQUIT);
1814 (errmsg("received immediate shutdown request")));
1815 if (ShutdownPID > 0)
1816 kill(ShutdownPID, SIGQUIT);
1818 kill(StartupPID, SIGQUIT);
1819 if (DLGetHead(BackendList))
1820 SignalChildren(SIGQUIT);
1825 PG_SETMASK(&UnBlockSig);
1831 * Reaper -- signal handler to cleanup after a backend (child) dies.
1836 int save_errno = errno;
1839 #warning fix waidpid for Win32
1842 int status; /* backend exit status */
1845 union wait status; /* backend exit status */
1848 int pid; /* process id of dead backend */
1850 PG_SETMASK(&BlockSig);
1853 (errmsg_internal("reaping dead processes")));
1855 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1857 exitstatus = status;
1859 while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
1861 exitstatus = status.w_status;
1865 * Check if this child was the statistics collector. If so, try to
1866 * start a new one. (If fail, we'll try again in future cycles of
1869 if (pgstat_ispgstat(pid))
1871 LogChildExit(LOG, gettext("statistics collector process"),
1878 * Check if this child was a shutdown or startup process.
1880 if (ShutdownPID > 0 && pid == ShutdownPID)
1882 if (exitstatus != 0)
1884 LogChildExit(LOG, gettext("shutdown process"),
1888 /* Normal postmaster exit is here */
1892 if (StartupPID > 0 && pid == StartupPID)
1894 if (exitstatus != 0)
1896 LogChildExit(LOG, gettext("startup process"),
1899 (errmsg("aborting startup due to startup process failure")));
1905 * Startup succeeded - remember its ID and RedoRecPtr.
1907 * NB: this MUST happen before we fork a checkpoint or shutdown
1908 * subprocess, else they will have wrong local ThisStartUpId.
1912 FatalError = false; /* done with recovery */
1915 * Arrange for first checkpoint to occur after standard delay.
1918 checkpointed = time(NULL);
1920 if (BgWriterPID == 0 && BgWriterPercent > 0 &&
1921 Shutdown == NoShutdown && !FatalError && random_seed != 0)
1923 BgWriterPID = StartBackgroundWriter();
1927 * Go to shutdown mode if a shutdown request was pending.
1929 if (Shutdown > NoShutdown)
1931 if (ShutdownPID > 0)
1933 elog(PANIC, "startup process %d died while shutdown process %d already running",
1934 pid, (int) ShutdownPID);
1937 ShutdownPID = ShutdownDataBase();
1944 * Else do standard child cleanup.
1946 CleanupProc(pid, exitstatus);
1948 } /* loop over pending child-death reports */
1954 * Wait for all children exit, then reset shmem and
1957 if (DLGetHead(BackendList) || StartupPID > 0 || ShutdownPID > 0)
1960 (errmsg("all server processes terminated; reinitializing")));
1963 reset_shared(PostPortNumber);
1965 StartupPID = StartupDataBase();
1970 if (Shutdown > NoShutdown)
1972 if (DLGetHead(BackendList))
1974 if (StartupPID > 0 || ShutdownPID > 0)
1976 ShutdownPID = ShutdownDataBase();
1980 PG_SETMASK(&UnBlockSig);
1986 * CleanupProc -- cleanup after terminated backend.
1988 * Remove all local state associated with backend.
1991 CleanupProc(int pid,
1992 int exitstatus) /* child's exit status. */
1998 LogChildExit(DEBUG2, gettext("child process"), pid, exitstatus);
2001 * If a backend dies in an ugly way (i.e. exit status not 0) then we
2002 * must signal all other backends to quickdie. If exit status is zero
2003 * we assume everything is hunky dory and simply remove the backend
2004 * from the active backend list.
2006 if (exitstatus == 0)
2008 curr = DLGetHead(BackendList);
2011 bp = (Backend *) DLE_VAL(curr);
2019 curr = DLGetSucc(curr);
2022 if (pid == CheckPointPID)
2027 checkpointed = time(NULL);
2028 /* Update RedoRecPtr for future child backends */
2029 GetSavedRedoRecPtr();
2032 else if (pid == BgWriterPID)
2040 /* below here we're dealing with a non-normal exit */
2042 /* Make log entry unless we did so already */
2046 (pid == CheckPointPID) ? gettext("checkpoint process") :
2047 (pid == BgWriterPID) ? gettext("bgwriter process") :
2048 gettext("server process"),
2051 (errmsg("terminating any other active server processes")));
2054 curr = DLGetHead(BackendList);
2057 next = DLGetSucc(curr);
2058 bp = (Backend *) DLE_VAL(curr);
2062 * This backend is still alive. Unless we did so already,
2063 * tell it to commit hara-kiri.
2065 * SIGQUIT is the special signal that says exit without proc_exit
2066 * and let the user know what's going on. But if SendStop is
2067 * set (-s on command line), then we send SIGSTOP instead, so
2068 * that we can get core dumps from all backends by hand.
2073 (errmsg_internal("sending %s to process %d",
2074 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2076 kill(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
2082 * Found entry for freshly-dead backend, so remove it.
2091 if (pid == CheckPointPID)
2096 else if (pid == BgWriterPID)
2103 * Tell the collector about backend termination
2112 * Log the death of a child process.
2115 LogChildExit(int lev, const char *procname, int pid, int exitstatus)
2117 if (WIFEXITED(exitstatus))
2121 * translator: %s is a noun phrase describing a child process,
2122 * such as "server process"
2124 (errmsg("%s (PID %d) exited with exit code %d",
2125 procname, pid, WEXITSTATUS(exitstatus))));
2126 else if (WIFSIGNALED(exitstatus))
2130 * translator: %s is a noun phrase describing a child process,
2131 * such as "server process"
2133 (errmsg("%s (PID %d) was terminated by signal %d",
2134 procname, pid, WTERMSIG(exitstatus))));
2139 * translator: %s is a noun phrase describing a child process,
2140 * such as "server process"
2142 (errmsg("%s (PID %d) exited with unexpected status %d",
2143 procname, pid, exitstatus)));
2147 * Send a signal to all backend children.
2150 SignalChildren(int signal)
2156 curr = DLGetHead(BackendList);
2159 next = DLGetSucc(curr);
2160 bp = (Backend *) DLE_VAL(curr);
2162 if (bp->pid != MyProcPid)
2165 (errmsg_internal("sending signal %d to process %d",
2168 kill(bp->pid, signal);
2176 * BackendStartup -- start backend process
2178 * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
2181 BackendStartup(Port *port)
2183 Backend *bn; /* for backend cleanup */
2186 #ifdef LINUX_PROFILE
2187 struct itimerval prof_itimer;
2191 * Compute the cancel key that will be assigned to this backend. The
2192 * backend will have its own copy in the forked-off process' value of
2193 * MyCancelKey, so that it can transmit the key to the frontend.
2195 MyCancelKey = PostmasterRandom();
2198 * Make room for backend data structure. Better before the fork() so
2199 * we can handle failure cleanly.
2201 bn = (Backend *) malloc(sizeof(Backend));
2205 (errcode(ERRCODE_OUT_OF_MEMORY),
2206 errmsg("out of memory")));
2207 return STATUS_ERROR;
2211 * Flush stdio channels just before fork, to avoid double-output
2212 * problems. Ideally we'd use fflush(NULL) here, but there are still a
2213 * few non-ANSI stdio libraries out there (like SunOS 4.1.x) that
2214 * coredump if we do. Presently stdout and stderr are the only stdio
2215 * output channels used by the postmaster, so fflush'ing them should
2221 #ifdef LINUX_PROFILE
2224 * Linux's fork() resets the profiling timer in the child process. If
2225 * we want to profile child processes then we need to save and restore
2226 * the timer setting. This is a waste of time if not profiling,
2227 * however, so only do it if commanded by specific -DLINUX_PROFILE
2230 getitimer(ITIMER_PROF, &prof_itimer);
2234 /* Specific beos actions before backend startup */
2235 beos_before_backend_startup();
2240 if (pid == 0) /* child */
2244 #ifdef LINUX_PROFILE
2245 setitimer(ITIMER_PROF, &prof_itimer, NULL);
2249 /* Specific beos backend startup actions */
2250 beos_backend_startup();
2254 status = BackendFork(port);
2258 (errmsg("connection startup failed")));
2262 /* in parent, error */
2265 int save_errno = errno;
2268 /* Specific beos backend startup actions */
2269 beos_backend_startup_failed();
2274 (errmsg("could not fork new process for connection: %m")));
2275 report_fork_failure_to_client(port, save_errno);
2276 return STATUS_ERROR;
2279 /* in parent, normal */
2281 (errmsg_internal("forked new backend, pid=%d socket=%d",
2282 (int) pid, port->sock)));
2285 * Everything's been successful, it's safe to add this backend to our
2289 bn->cancel_key = MyCancelKey;
2290 DLAddHead(BackendList, DLNewElem(bn));
2296 * Try to report backend fork() failure to client before we close the
2297 * connection. Since we do not care to risk blocking the postmaster on
2298 * this connection, we set the connection to non-blocking and try only once.
2300 * This is grungy special-purpose code; we cannot use backend libpq since
2301 * it's not up and running.
2304 report_fork_failure_to_client(Port *port, int errnum)
2308 /* Format the error message packet (always V2 protocol) */
2309 snprintf(buffer, sizeof(buffer), "E%s%s\n",
2310 gettext("could not fork new process for connection: "),
2313 /* Set port to non-blocking. Don't do send() if this fails */
2314 if (FCNTL_NONBLOCK(port->sock) < 0)
2317 send(port->sock, buffer, strlen(buffer) + 1, 0);
2322 * split_opts -- split a string of options and append it to an argv array
2324 * NB: the string is destructively modified!
2326 * Since no current POSTGRES arguments require any quoting characters,
2327 * we can use the simple-minded tactic of assuming each set of space-
2328 * delimited characters is a separate argv element.
2330 * If you don't like that, well, we *used* to pass the whole option string
2331 * as ONE argument to execl(), which was even less intelligent...
2334 split_opts(char **argv, int *argcp, char *s)
2338 while (isspace((unsigned char) *s))
2342 argv[(*argcp)++] = s;
2343 while (*s && !isspace((unsigned char) *s))
2352 * BackendInit/Fork -- perform authentication [BackendInit], and if successful,
2353 * set up the backend's argument list [BackendFork] and invoke
2354 * backend main() [or exec in EXEC_BACKEND case]
2357 * Shouldn't return at all.
2358 * If PostgresMain() fails, return status.
2360 NON_EXEC_STATIC bool
2361 BackendInit(Port *port)
2366 char remote_host[NI_MAXHOST];
2367 char remote_port[NI_MAXSERV];
2369 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
2371 ClientAuthInProgress = true; /* limit visibility of log messages */
2373 /* We don't want the postmaster's proc_exit() handlers */
2377 * Signal handlers setting is moved to tcop/postgres...
2380 /* Save port etc. for ps status */
2383 /* Reset MyProcPid to new backend's pid */
2384 MyProcPid = getpid();
2387 * Initialize libpq and enable reporting of ereport errors to the
2388 * client. Must do this now because authentication uses libpq to send
2391 pq_init(); /* initialize libpq to talk to client */
2392 whereToSendOutput = Remote; /* now safe to ereport to client */
2395 * We arrange for a simple exit(0) if we receive SIGTERM or SIGQUIT
2396 * during any client authentication related communication. Otherwise
2397 * the postmaster cannot shutdown the database FAST or IMMED cleanly
2398 * if a buggy client blocks a backend during authentication.
2400 pqsignal(SIGTERM, authdie);
2401 pqsignal(SIGQUIT, authdie);
2402 pqsignal(SIGALRM, authdie);
2403 PG_SETMASK(&AuthBlockSig);
2406 * Get the remote host name and port for logging and status display.
2408 remote_host[0] = '\0';
2409 remote_port[0] = '\0';
2410 if (getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2411 remote_host, sizeof(remote_host),
2412 remote_port, sizeof(remote_port),
2413 (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV))
2415 getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2416 remote_host, sizeof(remote_host),
2417 remote_port, sizeof(remote_port),
2418 NI_NUMERICHOST | NI_NUMERICSERV);
2421 if (Log_connections)
2423 (errmsg("connection received: host=%s port=%s",
2424 remote_host, remote_port)));
2428 /* modify remote_host for use in ps status */
2429 char tmphost[NI_MAXHOST];
2431 snprintf(tmphost, sizeof(tmphost), "%s:%s", remote_host, remote_port);
2432 StrNCpy(remote_host, tmphost, sizeof(remote_host));
2436 * Ready to begin client interaction. We will give up and exit(0)
2437 * after a time delay, so that a broken client can't hog a connection
2438 * indefinitely. PreAuthDelay doesn't count against the time limit.
2440 if (!enable_sig_alarm(AuthenticationTimeout * 1000, false))
2441 elog(FATAL, "could not set timer for authorization timeout");
2444 * Receive the startup packet (which might turn out to be a cancel
2447 status = ProcessStartupPacket(port, false);
2449 if (status != STATUS_OK)
2450 return false; /* cancel request processed, or error */
2453 * Now that we have the user and database name, we can set the process
2454 * title for ps. It's good to do this as early as possible in
2457 init_ps_display(port->user_name, port->database_name, remote_host);
2458 set_ps_display("authentication");
2461 * Now perform authentication exchange.
2463 ClientAuthentication(port); /* might not return, if failure */
2466 * Done with authentication. Disable timeout, and prevent
2467 * SIGTERM/SIGQUIT again until backend startup is complete.
2469 if (!disable_sig_alarm(false))
2470 elog(FATAL, "could not disable timer for authorization timeout");
2471 PG_SETMASK(&BlockSig);
2473 if (Log_connections)
2475 (errmsg("connection authorized: user=%s database=%s",
2476 port->user_name, port->database_name)));
2479 * Don't want backend to be able to see the postmaster random number
2480 * generator state. We have to clobber the static random_seed *and*
2481 * start a new random sequence in the random() library function.
2484 gettimeofday(&now, &tz);
2485 srandom((unsigned int) now.tv_usec);
2488 ClientAuthInProgress = false; /* client_min_messages is active
2496 BackendFork(Port *port)
2502 #ifndef EXEC_BACKEND
2506 char tmpExtraOptions[MAXPGPATH];
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 port->canAcceptConnections = canAcceptConnections();
2526 #ifndef EXEC_BACKEND
2527 if (!BackendInit(port))
2532 * Now, build the argv vector that will be given to PostgresMain.
2534 * The layout of the command line is
2535 * postgres [secure switches] -p databasename [insecure switches]
2536 * where the switches after -p come from the client request.
2538 * The maximum possible number of commandline arguments that could come
2539 * from ExtraOptions or port->cmdline_options is (strlen + 1) / 2; see
2543 maxac = 10; /* for fixed args supplied below */
2544 maxac += (strlen(ExtraOptions) + 1) / 2;
2545 if (port->cmdline_options)
2546 maxac += (strlen(port->cmdline_options) + 1) / 2;
2548 av = (char **) MemoryContextAlloc(TopMemoryContext,
2549 maxac * sizeof(char *));
2552 av[ac++] = "postgres";
2555 * Pass the requested debugging level along to the backend.
2559 snprintf(debugbuf, sizeof(debugbuf), "-d%d", debug_flag);
2560 av[ac++] = debugbuf;
2564 * Pass any backend switches specified with -o in the postmaster's own
2565 * command line. We assume these are secure.
2566 * [Note: now makes a copy to protect against future fork/exec changes]
2568 strcpy(tmpExtraOptions,ExtraOptions);
2569 split_opts(av, &ac, tmpExtraOptions);
2571 #ifndef EXEC_BACKEND
2572 /* Tell the backend what protocol the frontend is using. */
2573 snprintf(protobuf, sizeof(protobuf), "-v%u", port->proto);
2574 av[ac++] = protobuf;
2578 * Tell the backend it is being called from the postmaster, and which
2579 * database to use. -p marks the end of secure switches.
2582 write_backend_variables(getpid(),port);
2584 /* pass data dir before end of secure switches (-p) */
2589 * This is totally bogus. We need to pass an arg to -p, but we'll
2590 * actually get the dbname by ProcessStartupPacket in the exec'd
2594 av[ac++] = "FORK_EXEC";
2597 av[ac++] = port->database_name;
2601 * Pass the (insecure) option switches from the connection request.
2602 * (It's OK to mangle port->cmdline_options now.)
2604 /* FIXME: [fork/exec] Hmmm.. we won't see these until after we BackendInit.
2605 * Should we add code to BackendInit to add these (somehow!) into
2606 * the PostgresMain argument list in the EXEC_BACKEND case?
2608 if (port->cmdline_options)
2609 split_opts(av, &ac, port->cmdline_options);
2611 av[ac] = (char *) NULL;
2616 * Release postmaster's working memory context so that backend can
2617 * recycle the space. Note this does not trash *MyProcPort, because
2618 * ConnCreate() allocated that space with malloc() ... else we'd need
2619 * to copy the Port data here. Also, subsidiary data such as the
2620 * username isn't lost either; see ProcessStartupPacket().
2622 MemoryContextSwitchTo(TopMemoryContext);
2623 MemoryContextDelete(PostmasterContext);
2624 PostmasterContext = NULL;
2627 * Debug: print arguments being passed to backend
2630 (errmsg_internal("%s child[%d]: starting with (",
2631 progname, getpid())));
2632 for (i = 0; i < ac; ++i)
2634 (errmsg_internal("\t%s", av[i])));
2636 (errmsg_internal(")")));
2639 return execv(pg_pathname,av);
2641 ClientAuthInProgress = false; /* client_min_messages is active
2644 return (PostgresMain(ac, av, port->user_name));
2649 * ExitPostmaster -- cleanup
2651 * Do NOT call exit() directly --- always go through here!
2654 ExitPostmaster(int status)
2656 /* should cleanup shared memory and kill all backends */
2659 * Not sure of the semantics here. When the Postmaster dies, should
2660 * the backends all be killed? probably not.
2662 * MUST -- vadim 05-10-1999
2664 /* Should I use true instead? */
2665 ClosePostmasterPorts(false);
2671 * sigusr1_handler - handle signal conditions from child processes
2674 sigusr1_handler(SIGNAL_ARGS)
2676 int save_errno = errno;
2678 PG_SETMASK(&BlockSig);
2680 if (CheckPostmasterSignal(PMSIGNAL_DO_CHECKPOINT))
2682 if (CheckPointWarning != 0)
2685 * This only times checkpoints forced by running out of
2686 * segment files. Other checkpoints could reduce the
2687 * frequency of forced checkpoints.
2689 time_t now = time(NULL);
2691 if (LastSignalledCheckpoint != 0)
2693 int elapsed_secs = now - LastSignalledCheckpoint;
2695 if (elapsed_secs < CheckPointWarning)
2697 (errmsg("checkpoints are occurring too frequently (%d seconds apart)",
2699 errhint("Consider increasing the configuration parameter \"checkpoint_segments\".")));
2701 LastSignalledCheckpoint = now;
2705 * Request to schedule a checkpoint
2707 * Ignore request if checkpoint is already running or checkpointing
2708 * is currently disabled
2710 if (CheckPointPID == 0 && checkpointed &&
2711 Shutdown == NoShutdown && !FatalError && random_seed != 0)
2713 CheckPointPID = CheckPointDataBase();
2714 /* note: if fork fails, CheckPointPID stays 0; nothing happens */
2718 if (CheckPostmasterSignal(PMSIGNAL_PASSWORD_CHANGE))
2721 * Password or group file has changed.
2727 if (CheckPostmasterSignal(PMSIGNAL_WAKEN_CHILDREN))
2730 * Send SIGUSR2 to all children (triggers AsyncNotifyHandler). See
2731 * storage/ipc/sinvaladt.c for the use of this.
2733 if (Shutdown == NoShutdown)
2734 SignalChildren(SIGUSR2);
2737 PG_SETMASK(&UnBlockSig);
2744 * Dummy signal handler
2746 * We use this for signals that we don't actually use in the postmaster,
2747 * but we do use in backends. If we SIG_IGN such signals in the postmaster,
2748 * then a newly started backend might drop a signal that arrives before it's
2749 * able to reconfigure its signal processing. (See notes in postgres.c.)
2752 dummy_handler(SIGNAL_ARGS)
2758 * CharRemap: given an int in range 0..61, produce textual encoding of it
2759 * per crypt(3) conventions.
2783 RandomSalt(char *cryptSalt, char *md5Salt)
2785 long rand = PostmasterRandom();
2787 cryptSalt[0] = CharRemap(rand % 62);
2788 cryptSalt[1] = CharRemap(rand / 62);
2791 * It's okay to reuse the first random value for one of the MD5 salt
2792 * bytes, since only one of the two salts will be sent to the client.
2793 * After that we need to compute more random bits.
2795 * We use % 255, sacrificing one possible byte value, so as to ensure
2796 * that all bits of the random() value participate in the result.
2797 * While at it, add one to avoid generating any null bytes.
2799 md5Salt[0] = (rand % 255) + 1;
2800 rand = PostmasterRandom();
2801 md5Salt[1] = (rand % 255) + 1;
2802 rand = PostmasterRandom();
2803 md5Salt[2] = (rand % 255) + 1;
2804 rand = PostmasterRandom();
2805 md5Salt[3] = (rand % 255) + 1;
2812 PostmasterRandom(void)
2814 static bool initialized = false;
2818 Assert(random_seed != 0);
2819 srandom(random_seed);
2827 * Count up number of child processes.
2836 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2838 bp = (Backend *) DLE_VAL(curr);
2839 if (bp->pid != MyProcPid)
2842 if (CheckPointPID != 0)
2844 if (BgWriterPID != 0)
2850 * Fire off a subprocess for startup/shutdown/checkpoint.
2852 * Return value of SSDataBase is subprocess' PID, or 0 if failed to start subprocess
2853 * (0 is returned only for checkpoint case).
2855 NON_EXEC_STATIC void
2856 SSDataBaseInit(int xlop)
2858 const char *statmsg;
2860 IsUnderPostmaster = true; /* we are a postmaster subprocess
2863 /* Lose the postmaster's on-exit routines and port connections */
2867 * Identify myself via ps
2871 case BS_XLOG_STARTUP:
2872 statmsg = "startup subprocess";
2874 case BS_XLOG_CHECKPOINT:
2875 statmsg = "checkpoint subprocess";
2877 case BS_XLOG_BGWRITER:
2878 statmsg = "bgwriter subprocess";
2880 case BS_XLOG_SHUTDOWN:
2881 statmsg = "shutdown subprocess";
2884 statmsg = "??? subprocess";
2887 init_ps_display(statmsg, "", "");
2893 SSDataBase(int xlop)
2898 #ifdef LINUX_PROFILE
2899 struct itimerval prof_itimer;
2905 #ifdef LINUX_PROFILE
2906 /* see comments in BackendStartup */
2907 getitimer(ITIMER_PROF, &prof_itimer);
2911 /* Specific beos actions before backend startup */
2912 beos_before_backend_startup();
2915 if ((pid = fork()) == 0) /* child */
2922 #ifdef LINUX_PROFILE
2923 setitimer(ITIMER_PROF, &prof_itimer, NULL);
2927 /* Specific beos actions after backend startup */
2928 beos_backend_startup();
2931 /* Close the postmaster's sockets */
2932 ClosePostmasterPorts(true);
2934 #ifndef EXEC_BACKEND
2935 SSDataBaseInit(xlop);
2938 /* Set up command-line arguments for subprocess */
2939 av[ac++] = "postgres";
2945 snprintf(nbbuf, sizeof(nbbuf), "-B%d", NBuffers);
2948 snprintf(xlbuf, sizeof(xlbuf), "-x%d", xlop);
2952 write_backend_variables(getpid(),NULL);
2954 /* pass data dir before end of secure switches (-p) */
2959 av[ac++] = "template1";
2961 av[ac] = (char *) NULL;
2963 Assert(ac < lengthof(av));
2966 if (execv(pg_pathname,av) == -1)
2967 elog(FATAL,"unable to execv in SSDataBase: %m");
2969 BootstrapMain(ac, av);
2978 /* Specific beos actions before backend startup */
2979 beos_backend_startup_failed();
2984 case BS_XLOG_STARTUP:
2986 (errmsg("could not fork startup process: %m")));
2988 case BS_XLOG_CHECKPOINT:
2990 (errmsg("could not fork checkpoint process: %m")));
2992 case BS_XLOG_BGWRITER:
2994 (errmsg("could not fork bgwriter process: %m")));
2996 case BS_XLOG_SHUTDOWN:
2998 (errmsg("could not fork shutdown process: %m")));
3002 (errmsg("could not fork process: %m")));
3007 * fork failure is fatal during startup/shutdown, but there's no
3008 * need to choke if a routine checkpoint or starting a background
3011 if (xlop == BS_XLOG_CHECKPOINT)
3013 if (xlop == BS_XLOG_BGWRITER)
3019 * The startup and shutdown processes are not considered normal
3020 * backends, but the checkpoint and bgwriter processes are.
3021 * They must be added to the list of backends.
3023 if (xlop == BS_XLOG_CHECKPOINT || xlop == BS_XLOG_BGWRITER)
3025 if (!(bn = (Backend *) malloc(sizeof(Backend))))
3028 (errcode(ERRCODE_OUT_OF_MEMORY),
3029 errmsg("out of memory")));
3034 bn->cancel_key = PostmasterRandom();
3035 DLAddHead(BackendList, DLNewElem(bn));
3038 * Since this code is executed periodically, it's a fine place to
3039 * do other actions that should happen every now and then on no
3040 * particular schedule. Such as...
3043 TouchSocketLockFile();
3051 * Create the opts file
3054 CreateOptsFile(int argc, char *argv[])
3056 char fullprogname[MAXPGPATH];
3057 char filename[MAXPGPATH];
3061 if (FindExec(fullprogname, argv[0], "postmaster") < 0)
3064 snprintf(filename, sizeof(filename), "%s/postmaster.opts", DataDir);
3066 if ((fp = fopen(filename, "w")) == NULL)
3068 elog(LOG, "could not create file \"%s\": %m", filename);
3072 fprintf(fp, "%s", fullprogname);
3073 for (i = 1; i < argc; i++)
3074 fprintf(fp, " '%s'", argv[i]);
3080 elog(LOG, "could not write file \"%s\": %m", filename);
3090 * This should be used only for reporting "interactive" errors (essentially,
3091 * bogus arguments on the command line). Once the postmaster is launched,
3092 * use ereport. In particular, don't use this for anything that occurs
3093 * after pmdaemonize.
3096 postmaster_error(const char *fmt,...)
3100 fprintf(stderr, "%s: ", progname);
3102 vfprintf(stderr, gettext(fmt), ap);
3104 fprintf(stderr, "\n");
3111 * The following need to be available to the read/write_backend_variables
3114 extern XLogRecPtr RedoRecPtr;
3115 extern XLogwrtResult LogwrtResult;
3116 extern slock_t *ShmemLock;
3117 extern slock_t *ShmemIndexLock;
3118 extern void *ShmemIndexAlloc;
3119 typedef struct LWLock LWLock;
3120 extern LWLock *LWLockArray;
3121 extern slock_t *ProcStructLock;
3122 extern int pgStatSock;
3124 #define write_var(var,fp) fwrite((void*)&(var),sizeof(var),1,fp)
3125 #define read_var(var,fp) fread((void*)&(var),sizeof(var),1,fp)
3126 #define get_tmp_backend_file_name(buf,id) \
3130 "%s/%s/%s.backend_var.%d", \
3132 PG_TEMP_FILES_DIR, \
3133 PG_TEMP_FILE_PREFIX, \
3138 write_backend_variables(pid_t pid, Port *port)
3140 char filename[MAXPGPATH];
3142 get_tmp_backend_file_name(filename,pid);
3145 fp = AllocateFile(filename, PG_BINARY_W);
3148 /* As per OpenTemporaryFile... */
3149 char dirname[MAXPGPATH];
3150 sprintf(dirname,"%s/%s",DataDir,PG_TEMP_FILES_DIR);
3151 mkdir(dirname, S_IRWXU);
3153 fp = AllocateFile(filename, PG_BINARY_W);
3157 (errcode_for_file_access(),
3158 errmsg("could not write to file \"%s\": %m", filename)));
3166 write_var(port->sock,fp);
3167 write_var(port->proto,fp);
3168 write_var(port->laddr,fp);
3169 write_var(port->raddr,fp);
3170 write_var(port->canAcceptConnections,fp);
3171 write_var(port->cryptSalt,fp);
3172 write_var(port->md5Salt,fp);
3174 write_var(MyCancelKey,fp);
3176 write_var(RedoRecPtr,fp);
3177 write_var(LogwrtResult,fp);
3179 write_var(UsedShmemSegID,fp);
3180 write_var(UsedShmemSegAddr,fp);
3182 write_var(ShmemLock,fp);
3183 write_var(ShmemIndexLock,fp);
3184 write_var(ShmemVariableCache,fp);
3185 write_var(ShmemIndexAlloc,fp);
3187 write_var(LWLockArray,fp);
3188 write_var(ProcStructLock,fp);
3189 write_var(pgStatSock,fp);
3196 read_backend_variables(pid_t pid, Port *port)
3198 char filename[MAXPGPATH];
3200 get_tmp_backend_file_name(filename,pid);
3203 fp = AllocateFile(filename, PG_BINARY_R);
3207 (errcode_for_file_access(),
3208 errmsg("could not read from backend_variables file \"%s\": %m", filename)));
3215 read_var(port->sock,fp);
3216 read_var(port->proto,fp);
3217 read_var(port->laddr,fp);
3218 read_var(port->raddr,fp);
3219 read_var(port->canAcceptConnections,fp);
3220 read_var(port->cryptSalt,fp);
3221 read_var(port->md5Salt,fp);
3223 read_var(MyCancelKey,fp);
3225 read_var(RedoRecPtr,fp);
3226 read_var(LogwrtResult,fp);
3228 read_var(UsedShmemSegID,fp);
3229 read_var(UsedShmemSegAddr,fp);
3231 read_var(ShmemLock,fp);
3232 read_var(ShmemIndexLock,fp);
3233 read_var(ShmemVariableCache,fp);
3234 read_var(ShmemIndexAlloc,fp);
3236 read_var(LWLockArray,fp);
3237 read_var(ProcStructLock,fp);
3238 read_var(pgStatSock,fp);
3242 if (unlink(filename) != 0)
3244 (errcode_for_file_access(),
3245 errmsg("could not remove file \"%s\": %m", filename)));