1 /*-------------------------------------------------------------------------
4 * This program acts as a clearing house for requests to the
5 * POSTGRES system. Frontend programs send a startup message
6 * to the Postmaster and the postmaster uses the info in the
7 * message to setup a backend process.
9 * The postmaster also manages system-wide operations such as
10 * startup and shutdown. The postmaster itself doesn't do those
11 * operations, mind you --- it just forks off a subprocess to do them
12 * at the right times. It also takes care of resetting the system
13 * if a backend crashes.
15 * The postmaster process creates the shared memory and semaphore
16 * pools during startup, but as a rule does not touch them itself.
17 * In particular, it is not a member of the PGPROC array of backends
18 * and so it cannot participate in lock-manager operations. Keeping
19 * the postmaster away from shared memory operations makes it simpler
20 * and more reliable. The postmaster is almost always able to recover
21 * from crashes of individual backends by resetting shared memory;
22 * if it did much with shared memory then it would be prone to crashing
23 * along with the backends.
25 * When a request message is received, we now fork() immediately.
26 * The child process performs authentication of the request, and
27 * then becomes a backend if successful. This allows the auth code
28 * to be written in a simple single-threaded style (as opposed to the
29 * crufty "poor man's multitasking" code that used to be needed).
30 * More importantly, it ensures that blockages in non-multithreaded
31 * libraries like SSL or PAM cannot cause denial of service to other
35 * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
36 * Portions Copyright (c) 1994, Regents of the University of California
40 * src/backend/postmaster/postmaster.c
45 * The Postmaster sets up shared memory data structures
49 * The Postmaster shares memory with the backends but should avoid
50 * touching shared memory, so as not to become stuck if a crashing
51 * backend screws up locks or shared memory. Likewise, the Postmaster
52 * should never block on messages from frontend clients.
55 * The Postmaster cleans up after backends if they have an emergency
56 * exit and/or core dump.
59 * Use write_stderr() only for reporting "interactive" errors
60 * (essentially, bogus arguments on the command line). Once the
61 * postmaster is launched, use ereport().
63 *-------------------------------------------------------------------------
74 #include <sys/socket.h>
76 #include <sys/param.h>
77 #include <netinet/in.h>
78 #include <arpa/inet.h>
82 #ifdef HAVE_SYS_SELECT_H
83 #include <sys/select.h>
94 #include "access/transam.h"
95 #include "access/xlog.h"
96 #include "bootstrap/bootstrap.h"
97 #include "catalog/pg_control.h"
98 #include "lib/dllist.h"
99 #include "libpq/auth.h"
100 #include "libpq/ip.h"
101 #include "libpq/libpq.h"
102 #include "libpq/pqsignal.h"
103 #include "miscadmin.h"
105 #include "postmaster/autovacuum.h"
106 #include "postmaster/fork_process.h"
107 #include "postmaster/pgarch.h"
108 #include "postmaster/postmaster.h"
109 #include "postmaster/syslogger.h"
110 #include "replication/walsender.h"
111 #include "storage/fd.h"
112 #include "storage/ipc.h"
113 #include "storage/pg_shmem.h"
114 #include "storage/pmsignal.h"
115 #include "storage/proc.h"
116 #include "tcop/tcopprot.h"
117 #include "utils/builtins.h"
118 #include "utils/datetime.h"
119 #include "utils/memutils.h"
120 #include "utils/ps_status.h"
121 #include "utils/timeout.h"
124 #include "storage/spin.h"
129 * List of active backends (or child processes anyway; we don't actually
130 * know whether a given child has become a backend or is still in the
131 * authorization phase). This is used mainly to keep track of how many
132 * children we have and send them appropriate signals when necessary.
134 * "Special" children such as the startup, bgwriter and autovacuum launcher
135 * tasks are not in this list. Autovacuum worker and walsender processes are
136 * in it. Also, "dead_end" children are in it: these are children launched just
137 * for the purpose of sending a friendly rejection message to a would-be
138 * client. We must track them because they are attached to shared memory,
139 * but we know they will never become live backends. dead_end children are
140 * not assigned a PMChildSlot.
144 pid_t pid; /* process id of backend */
145 long cancel_key; /* cancel key for cancels for this backend */
146 int child_slot; /* PMChildSlot for this backend, if any */
147 bool is_autovacuum; /* is it an autovacuum process? */
148 bool dead_end; /* is it going to send an error and quit? */
149 Dlelem elem; /* list link in BackendList */
152 static Dllist *BackendList;
155 static Backend *ShmemBackendArray;
158 /* The socket number we are listening for connections on */
160 /* The directory names for Unix socket(s) */
161 char *Unix_socket_directories;
162 /* The TCP listen address(es) */
163 char *ListenAddresses;
166 * ReservedBackends is the number of backends reserved for superuser use.
167 * This number is taken out of the pool size given by MaxBackends so
168 * number of backend slots available to non-superusers is
169 * (MaxBackends - ReservedBackends). Note what this really means is
170 * "if there are <= ReservedBackends connections available, only superusers
171 * can make new connections" --- pre-existing superuser connections don't
172 * count against the limit.
174 int ReservedBackends;
176 /* The socket(s) we're listening to. */
178 static pgsocket ListenSocket[MAXLISTEN];
181 * Set by the -o option
183 static char ExtraOptions[MAXPGPATH];
186 * These globals control the behavior of the postmaster in case some
187 * backend dumps core. Normally, it kills all peers of the dead backend
188 * and reinitializes shared memory. By specifying -s or -n, we can have
189 * the postmaster stop (rather than kill) peers and not reinitialize
190 * shared data structures. (Reinit is currently dead code, though.)
192 static bool Reinit = true;
193 static int SendStop = false;
195 /* still more option variables */
196 bool EnableSSL = false;
198 int PreAuthDelay = 0;
199 int AuthenticationTimeout = 60;
201 bool log_hostname; /* for ps display and logging */
202 bool Log_connections = false;
203 bool Db_user_namespace = false;
205 bool enable_bonjour = false;
207 bool restart_after_crash = true;
209 char *output_config_variable = NULL;
211 /* PIDs of special child processes; 0 when not running */
212 static pid_t StartupPID = 0,
222 /* Startup/shutdown state */
224 #define SmartShutdown 1
225 #define FastShutdown 2
227 static int Shutdown = NoShutdown;
229 static bool FatalError = false; /* T if recovering from backend crash */
230 static bool RecoveryError = false; /* T if WAL recovery failed */
233 * We use a simple state machine to control startup, shutdown, and
234 * crash recovery (which is rather like shutdown followed by startup).
236 * After doing all the postmaster initialization work, we enter PM_STARTUP
237 * state and the startup process is launched. The startup process begins by
238 * reading the control file and other preliminary initialization steps.
239 * In a normal startup, or after crash recovery, the startup process exits
240 * with exit code 0 and we switch to PM_RUN state. However, archive recovery
241 * is handled specially since it takes much longer and we would like to support
242 * hot standby during archive recovery.
244 * When the startup process is ready to start archive recovery, it signals the
245 * postmaster, and we switch to PM_RECOVERY state. The background writer and
246 * checkpointer are launched, while the startup process continues applying WAL.
247 * If Hot Standby is enabled, then, after reaching a consistent point in WAL
248 * redo, startup process signals us again, and we switch to PM_HOT_STANDBY
249 * state and begin accepting connections to perform read-only queries. When
250 * archive recovery is finished, the startup process exits with exit code 0
251 * and we switch to PM_RUN state.
253 * Normal child backends can only be launched when we are in PM_RUN or
254 * PM_HOT_STANDBY state. (We also allow launch of normal
255 * child backends in PM_WAIT_BACKUP state, but only for superusers.)
256 * In other states we handle connection requests by launching "dead_end"
257 * child processes, which will simply send the client an error message and
258 * quit. (We track these in the BackendList so that we can know when they
259 * are all gone; this is important because they're still connected to shared
260 * memory, and would interfere with an attempt to destroy the shmem segment,
261 * possibly leading to SHMALL failure when we try to make a new one.)
262 * In PM_WAIT_DEAD_END state we are waiting for all the dead_end children
263 * to drain out of the system, and therefore stop accepting connection
264 * requests at all until the last existing child has quit (which hopefully
265 * will not be very long).
267 * Notice that this state variable does not distinguish *why* we entered
268 * states later than PM_RUN --- Shutdown and FatalError must be consulted
269 * to find that out. FatalError is never true in PM_RECOVERY_* or PM_RUN
270 * states, nor in PM_SHUTDOWN states (because we don't enter those states
271 * when trying to recover from a crash). It can be true in PM_STARTUP state,
272 * because we don't clear it until we've successfully started WAL redo.
273 * Similarly, RecoveryError means that we have crashed during recovery, and
274 * should not try to restart.
278 PM_INIT, /* postmaster starting */
279 PM_STARTUP, /* waiting for startup subprocess */
280 PM_RECOVERY, /* in archive recovery mode */
281 PM_HOT_STANDBY, /* in hot standby mode */
282 PM_RUN, /* normal "database is alive" state */
283 PM_WAIT_BACKUP, /* waiting for online backup mode to end */
284 PM_WAIT_READONLY, /* waiting for read only backends to exit */
285 PM_WAIT_BACKENDS, /* waiting for live backends to exit */
286 PM_SHUTDOWN, /* waiting for checkpointer to do shutdown
288 PM_SHUTDOWN_2, /* waiting for archiver and walsenders to
290 PM_WAIT_DEAD_END, /* waiting for dead_end children to exit */
291 PM_NO_CHILDREN /* all important children have exited */
294 static PMState pmState = PM_INIT;
296 static bool ReachedNormalRunning = false; /* T if we've reached PM_RUN */
298 bool ClientAuthInProgress = false; /* T during new-client
301 bool redirection_done = false; /* stderr redirected for syslogger? */
303 /* received START_AUTOVAC_LAUNCHER signal */
304 static volatile sig_atomic_t start_autovac_launcher = false;
306 /* the launcher needs to be signalled to communicate some condition */
307 static volatile bool avlauncher_needs_signal = false;
310 * State for assigning random salts and cancel keys.
311 * Also, the global MyCancelKey passes the cancel key assigned to a given
312 * backend from the postmaster to that backend (via fork).
314 static unsigned int random_seed = 0;
315 static struct timeval random_start_time;
321 #ifdef HAVE_INT_OPTRESET
322 extern int optreset; /* might not be declared by system headers */
326 static DNSServiceRef bonjour_sdref = NULL;
330 * postmaster.c - function prototypes
332 static void unlink_external_pid_file(int status, Datum arg);
333 static void getInstallationPaths(const char *argv0);
334 static void checkDataDir(void);
335 static Port *ConnCreate(int serverFd);
336 static void ConnFree(Port *port);
337 static void reset_shared(int port);
338 static void SIGHUP_handler(SIGNAL_ARGS);
339 static void pmdie(SIGNAL_ARGS);
340 static void reaper(SIGNAL_ARGS);
341 static void sigusr1_handler(SIGNAL_ARGS);
342 static void startup_die(SIGNAL_ARGS);
343 static void dummy_handler(SIGNAL_ARGS);
344 static void StartupPacketTimeoutHandler(void);
345 static void CleanupBackend(int pid, int exitstatus);
346 static void HandleChildCrash(int pid, int exitstatus, const char *procname);
347 static void LogChildExit(int lev, const char *procname,
348 int pid, int exitstatus);
349 static void PostmasterStateMachine(void);
350 static void BackendInitialize(Port *port);
351 static void BackendRun(Port *port) __attribute__((noreturn));
352 static void ExitPostmaster(int status) __attribute__((noreturn));
353 static int ServerLoop(void);
354 static int BackendStartup(Port *port);
355 static int ProcessStartupPacket(Port *port, bool SSLdone);
356 static void processCancelRequest(Port *port, void *pkt);
357 static int initMasks(fd_set *rmask);
358 static void report_fork_failure_to_client(Port *port, int errnum);
359 static CAC_state canAcceptConnections(void);
360 static long PostmasterRandom(void);
361 static void RandomSalt(char *md5Salt);
362 static void signal_child(pid_t pid, int signal);
363 static bool SignalSomeChildren(int signal, int targets);
365 #define SignalChildren(sig) SignalSomeChildren(sig, BACKEND_TYPE_ALL)
368 * Possible types of a backend. These are OR-able request flag bits
369 * for SignalSomeChildren() and CountChildren().
371 #define BACKEND_TYPE_NORMAL 0x0001 /* normal backend */
372 #define BACKEND_TYPE_AUTOVAC 0x0002 /* autovacuum worker process */
373 #define BACKEND_TYPE_WALSND 0x0004 /* walsender process */
374 #define BACKEND_TYPE_ALL 0x0007 /* OR of all the above */
376 static int CountChildren(int target);
377 static bool CreateOptsFile(int argc, char *argv[], char *fullprogname);
378 static pid_t StartChildProcess(AuxProcType type);
379 static void StartAutovacuumWorker(void);
380 static void InitPostmasterDeathWatchHandle(void);
385 #define WNOHANG 0 /* ignored, so any integer value will do */
387 static pid_t waitpid(pid_t pid, int *exitstatus, int options);
388 static void WINAPI pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired);
390 static HANDLE win32ChildQueue;
397 } win32_deadchild_waitinfo;
400 static pid_t backend_forkexec(Port *port);
401 static pid_t internal_forkexec(int argc, char *argv[], Port *port);
403 /* Type for a socket that can be inherited to a client process */
407 SOCKET origsocket; /* Original socket value, or PGINVALID_SOCKET
409 WSAPROTOCOL_INFO wsainfo;
412 typedef int InheritableSocket;
415 typedef struct LWLock LWLock; /* ugly kluge */
418 * Structure contains all variables passed to exec:ed backends
423 InheritableSocket portsocket;
424 char DataDir[MAXPGPATH];
425 pgsocket ListenSocket[MAXLISTEN];
429 unsigned long UsedShmemSegID;
431 HANDLE UsedShmemSegID;
433 void *UsedShmemSegAddr;
435 VariableCache ShmemVariableCache;
436 Backend *ShmemBackendArray;
438 slock_t *ProcStructLock;
439 PROC_HDR *ProcGlobal;
440 PGPROC *AuxiliaryProcs;
441 PGPROC *PreparedXactProcs;
442 PMSignalData *PMSignalState;
443 InheritableSocket pgStatSock;
445 TimestampTz PgStartTime;
446 TimestampTz PgReloadTime;
447 pg_time_t first_syslogger_file_time;
448 bool redirection_done;
449 bool IsBinaryUpgrade;
452 HANDLE PostmasterHandle;
453 HANDLE initial_signal_pipe;
454 HANDLE syslogPipe[2];
456 int postmaster_alive_fds[2];
459 char my_exec_path[MAXPGPATH];
460 char pkglib_path[MAXPGPATH];
461 char ExtraOptions[MAXPGPATH];
464 static void read_backend_variables(char *id, Port *port);
465 static void restore_backend_variables(BackendParameters *param, Port *port);
468 static bool save_backend_variables(BackendParameters *param, Port *port);
470 static bool save_backend_variables(BackendParameters *param, Port *port,
471 HANDLE childProcess, pid_t childPid);
474 static void ShmemBackendArrayAdd(Backend *bn);
475 static void ShmemBackendArrayRemove(Backend *bn);
476 #endif /* EXEC_BACKEND */
478 #define StartupDataBase() StartChildProcess(StartupProcess)
479 #define StartBackgroundWriter() StartChildProcess(BgWriterProcess)
480 #define StartCheckpointer() StartChildProcess(CheckpointerProcess)
481 #define StartWalWriter() StartChildProcess(WalWriterProcess)
482 #define StartWalReceiver() StartChildProcess(WalReceiverProcess)
484 /* Macros to check exit status of a child process */
485 #define EXIT_STATUS_0(st) ((st) == 0)
486 #define EXIT_STATUS_1(st) (WIFEXITED(st) && WEXITSTATUS(st) == 1)
490 * File descriptors for pipe used to monitor if postmaster is alive.
491 * First is POSTMASTER_FD_WATCH, second is POSTMASTER_FD_OWN.
493 int postmaster_alive_fds[2] = {-1, -1};
495 /* Process handle of postmaster used for the same purpose on Windows */
496 HANDLE PostmasterHandle;
500 * Postmaster main entry point
503 PostmasterMain(int argc, char *argv[])
507 char *userDoption = NULL;
508 bool listen_addr_saved = false;
511 MyProcPid = PostmasterPid = getpid();
513 MyStartTime = time(NULL);
515 IsPostmasterEnvironment = true;
518 * for security, no dir or file created can be group or other accessible
520 umask(S_IRWXG | S_IRWXO);
523 * Fire up essential subsystems: memory management
528 * By default, palloc() requests in the postmaster will be allocated in
529 * the PostmasterContext, which is space that can be recycled by backends.
530 * Allocated data that needs to be available to backends should be
531 * allocated in TopMemoryContext.
533 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
535 ALLOCSET_DEFAULT_MINSIZE,
536 ALLOCSET_DEFAULT_INITSIZE,
537 ALLOCSET_DEFAULT_MAXSIZE);
538 MemoryContextSwitchTo(PostmasterContext);
540 /* Initialize paths to installation files */
541 getInstallationPaths(argv[0]);
546 InitializeGUCOptions();
551 * Parse command-line options. CAUTION: keep this in sync with
552 * tcop/postgres.c (the option sets should not conflict) and with the
553 * common help() function in main/main.c.
555 while ((opt = getopt(argc, argv, "A:B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:W:-:")) != -1)
560 SetConfigOption("debug_assertions", optarg, PGC_POSTMASTER, PGC_S_ARGV);
564 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
568 /* Undocumented flag used for binary upgrades */
569 IsBinaryUpgrade = true;
573 output_config_variable = optarg;
577 userDoption = optarg;
581 set_debug_options(atoi(optarg), PGC_POSTMASTER, PGC_S_ARGV);
585 SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
589 SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
593 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
597 if (!set_plan_disabling_options(optarg, PGC_POSTMASTER, PGC_S_ARGV))
599 write_stderr("%s: invalid argument for option -f: \"%s\"\n",
606 SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
610 SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
614 /* only used by interactive backend */
618 SetConfigOption("unix_socket_directories", optarg, PGC_POSTMASTER, PGC_S_ARGV);
622 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
626 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
630 /* Don't reinit shared mem after abnormal exit */
635 SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
639 /* Other options to pass to the backend on the command line */
640 snprintf(ExtraOptions + strlen(ExtraOptions),
641 sizeof(ExtraOptions) - strlen(ExtraOptions),
646 SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
650 SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
654 /* only used by single-user backend */
658 SetConfigOption("work_mem", optarg, PGC_POSTMASTER, PGC_S_ARGV);
662 SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
668 * In the event that some backend dumps core, send SIGSTOP,
669 * rather than SIGQUIT, to all its peers. This lets the wily
670 * post_hacker collect core dumps from everyone.
677 const char *tmp = get_stats_option_name(optarg);
681 SetConfigOption(tmp, "true", PGC_POSTMASTER, PGC_S_ARGV);
685 write_stderr("%s: invalid argument for option -t: \"%s\"\n",
693 SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
702 ParseLongOption(optarg, &name, &value);
707 (errcode(ERRCODE_SYNTAX_ERROR),
708 errmsg("--%s requires a value",
712 (errcode(ERRCODE_SYNTAX_ERROR),
713 errmsg("-c %s requires a value",
717 SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
725 write_stderr("Try \"%s --help\" for more information.\n",
732 * Postmaster accepts no non-option switch arguments.
736 write_stderr("%s: invalid argument: \"%s\"\n",
737 progname, argv[optind]);
738 write_stderr("Try \"%s --help\" for more information.\n",
744 * Locate the proper configuration files and data directory, and read
745 * postgresql.conf for the first time.
747 if (!SelectConfigFiles(userDoption, progname))
750 if (output_config_variable != NULL)
753 * permission is handled because the user is reading inside the data
756 puts(GetConfigOption(output_config_variable, false, false));
760 /* Verify that DataDir looks reasonable */
763 /* And switch working directory into it */
767 * Check for invalid combinations of GUC settings.
769 if (ReservedBackends >= MaxConnections)
771 write_stderr("%s: superuser_reserved_connections must be less than max_connections\n", progname);
774 if (max_wal_senders >= MaxConnections)
776 write_stderr("%s: max_wal_senders must be less than max_connections\n", progname);
779 if (XLogArchiveMode && wal_level == WAL_LEVEL_MINIMAL)
781 (errmsg("WAL archival (archive_mode=on) requires wal_level \"archive\" or \"hot_standby\"")));
782 if (max_wal_senders > 0 && wal_level == WAL_LEVEL_MINIMAL)
784 (errmsg("WAL streaming (max_wal_senders > 0) requires wal_level \"archive\" or \"hot_standby\"")));
787 * Other one-time internal sanity checks can go here, if they are fast.
788 * (Put any slow processing further down, after postmaster.pid creation.)
790 if (!CheckDateTokenTables())
792 write_stderr("%s: invalid datetoken tables, please fix\n", progname);
797 * Now that we are done processing the postmaster arguments, reset
798 * getopt(3) library so that it will work correctly in subprocesses.
801 #ifdef HAVE_INT_OPTRESET
802 optreset = 1; /* some systems need this too */
805 /* For debugging: display postmaster environment */
807 extern char **environ;
811 (errmsg_internal("%s: PostmasterMain: initial environment dump:",
814 (errmsg_internal("-----------------------------------------")));
815 for (p = environ; *p; ++p)
817 (errmsg_internal("\t%s", *p)));
819 (errmsg_internal("-----------------------------------------")));
823 * Create lockfile for data directory.
825 * We want to do this before we try to grab the input sockets, because the
826 * data directory interlock is more reliable than the socket-file
827 * interlock (thanks to whoever decided to put socket files in /tmp :-().
828 * For the same reason, it's best to grab the TCP socket(s) before the
831 CreateDataDirLockFile(true);
834 * Initialize SSL library, if specified.
842 * process any libraries that should be preloaded at postmaster start
844 process_shared_preload_libraries();
847 * Establish input sockets.
849 for (i = 0; i < MAXLISTEN; i++)
850 ListenSocket[i] = PGINVALID_SOCKET;
859 /* Need a modifiable copy of ListenAddresses */
860 rawstring = pstrdup(ListenAddresses);
862 /* Parse string into list of hostnames */
863 if (!SplitIdentifierString(rawstring, ',', &elemlist))
865 /* syntax error in list */
867 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
868 errmsg("invalid list syntax for \"listen_addresses\"")));
873 char *curhost = (char *) lfirst(l);
875 if (strcmp(curhost, "*") == 0)
876 status = StreamServerPort(AF_UNSPEC, NULL,
877 (unsigned short) PostPortNumber,
879 ListenSocket, MAXLISTEN);
881 status = StreamServerPort(AF_UNSPEC, curhost,
882 (unsigned short) PostPortNumber,
884 ListenSocket, MAXLISTEN);
886 if (status == STATUS_OK)
889 /* record the first successful host addr in lockfile */
890 if (!listen_addr_saved)
892 AddToDataDirLockFile(LOCK_FILE_LINE_LISTEN_ADDR, curhost);
893 listen_addr_saved = true;
898 (errmsg("could not create listen socket for \"%s\"",
902 if (!success && elemlist != NIL)
904 (errmsg("could not create any TCP/IP sockets")));
911 /* Register for Bonjour only if we opened TCP socket(s) */
912 if (enable_bonjour && ListenSocket[0] != PGINVALID_SOCKET)
914 DNSServiceErrorType err;
917 * We pass 0 for interface_index, which will result in registering on
918 * all "applicable" interfaces. It's not entirely clear from the
919 * DNS-SD docs whether this would be appropriate if we have bound to
920 * just a subset of the available network interfaces.
922 err = DNSServiceRegister(&bonjour_sdref,
929 htons(PostPortNumber),
934 if (err != kDNSServiceErr_NoError)
935 elog(LOG, "DNSServiceRegister() failed: error code %ld",
939 * We don't bother to read the mDNS daemon's reply, and we expect that
940 * it will automatically terminate our registration when the socket is
941 * closed at postmaster termination. So there's nothing more to be
942 * done here. However, the bonjour_sdref is kept around so that
943 * forked children can close their copies of the socket.
948 #ifdef HAVE_UNIX_SOCKETS
949 if (Unix_socket_directories)
956 /* Need a modifiable copy of Unix_socket_directories */
957 rawstring = pstrdup(Unix_socket_directories);
959 /* Parse string into list of directories */
960 if (!SplitDirectoriesString(rawstring, ',', &elemlist))
962 /* syntax error in list */
964 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
965 errmsg("invalid list syntax for \"unix_socket_directories\"")));
970 char *socketdir = (char *) lfirst(l);
972 status = StreamServerPort(AF_UNIX, NULL,
973 (unsigned short) PostPortNumber,
975 ListenSocket, MAXLISTEN);
977 if (status == STATUS_OK)
980 /* record the first successful Unix socket in lockfile */
982 AddToDataDirLockFile(LOCK_FILE_LINE_SOCKET_DIR, socketdir);
986 (errmsg("could not create Unix-domain socket in directory \"%s\"",
990 if (!success && elemlist != NIL)
992 (errmsg("could not create any Unix-domain sockets")));
994 list_free_deep(elemlist);
1000 * check that we have some socket to listen on
1002 if (ListenSocket[0] == PGINVALID_SOCKET)
1004 (errmsg("no socket created for listening")));
1007 * If no valid TCP ports, write an empty line for listen address,
1008 * indicating the Unix socket must be used. Note that this line is not
1009 * added to the lock file until there is a socket backing it.
1011 if (!listen_addr_saved)
1012 AddToDataDirLockFile(LOCK_FILE_LINE_LISTEN_ADDR, "");
1015 * Set up shared memory and semaphores.
1017 reset_shared(PostPortNumber);
1020 * Estimate number of openable files. This must happen after setting up
1021 * semaphores, because on some platforms semaphores count as open files.
1026 * Set reference point for stack-depth checking.
1031 * Initialize the list of active backends.
1033 BackendList = DLNewList();
1036 * Initialize pipe (or process handle on Windows) that allows children to
1037 * wake up from sleep on postmaster death.
1039 InitPostmasterDeathWatchHandle();
1044 * Initialize I/O completion port used to deliver list of dead children.
1046 win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
1047 if (win32ChildQueue == NULL)
1049 (errmsg("could not create I/O completion port for child queue")));
1053 * Record postmaster options. We delay this till now to avoid recording
1054 * bogus options (eg, NBuffers too high for available memory).
1056 if (!CreateOptsFile(argc, argv, my_exec_path))
1060 /* Write out nondefault GUC settings for child processes to use */
1061 write_nondefault_variables(PGC_POSTMASTER);
1065 * Write the external PID file if requested
1067 if (external_pid_file)
1069 FILE *fpidfile = fopen(external_pid_file, "w");
1073 fprintf(fpidfile, "%d\n", MyProcPid);
1076 /* Make PID file world readable */
1077 if (chmod(external_pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) != 0)
1078 write_stderr("%s: could not change permissions of external PID file \"%s\": %s\n",
1079 progname, external_pid_file, strerror(errno));
1082 write_stderr("%s: could not write external PID file \"%s\": %s\n",
1083 progname, external_pid_file, strerror(errno));
1085 on_proc_exit(unlink_external_pid_file, 0);
1089 * Set up signal handlers for the postmaster process.
1091 * CAUTION: when changing this list, check for side-effects on the signal
1092 * handling setup of child processes. See tcop/postgres.c,
1093 * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/walwriter.c,
1094 * postmaster/autovacuum.c, postmaster/pgarch.c, postmaster/pgstat.c,
1095 * postmaster/syslogger.c and postmaster/checkpointer.c.
1098 PG_SETMASK(&BlockSig);
1100 pqsignal(SIGHUP, SIGHUP_handler); /* reread config file and have
1101 * children do same */
1102 pqsignal(SIGINT, pmdie); /* send SIGTERM and shut down */
1103 pqsignal(SIGQUIT, pmdie); /* send SIGQUIT and die */
1104 pqsignal(SIGTERM, pmdie); /* wait for children and shut down */
1105 pqsignal(SIGALRM, SIG_IGN); /* ignored */
1106 pqsignal(SIGPIPE, SIG_IGN); /* ignored */
1107 pqsignal(SIGUSR1, sigusr1_handler); /* message from child process */
1108 pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
1109 pqsignal(SIGCHLD, reaper); /* handle child termination */
1110 pqsignal(SIGTTIN, SIG_IGN); /* ignored */
1111 pqsignal(SIGTTOU, SIG_IGN); /* ignored */
1112 /* ignore SIGXFSZ, so that ulimit violations work like disk full */
1114 pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
1118 * If enabled, start up syslogger collection subprocess
1120 SysLoggerPID = SysLogger_Start();
1123 * Reset whereToSendOutput from DestDebug (its starting state) to
1124 * DestNone. This stops ereport from sending log messages to stderr unless
1125 * Log_destination permits. We don't do this until the postmaster is
1126 * fully launched, since startup failures may as well be reported to
1129 whereToSendOutput = DestNone;
1132 * Initialize stats collection subsystem (this does NOT start the
1133 * collector process!)
1138 * Initialize the autovacuum subsystem (again, no process start yet)
1143 * Load configuration files for client authentication.
1148 * It makes no sense to continue if we fail to load the HBA file,
1149 * since there is no way to connect to the database in this case.
1152 (errmsg("could not load pg_hba.conf")));
1157 * We can start up without the IDENT file, although it means that you
1158 * cannot log in using any of the authentication methods that need a
1159 * user name mapping. load_ident() already logged the details of
1166 * Remove old temporary files. At this point there can be no other
1167 * Postgres processes running in this directory, so this should be safe.
1169 RemovePgTempFiles();
1172 * Remember postmaster startup time
1174 PgStartTime = GetCurrentTimestamp();
1175 /* PostmasterRandom wants its own copy */
1176 gettimeofday(&random_start_time, NULL);
1179 * We're ready to rock and roll...
1181 StartupPID = StartupDataBase();
1182 Assert(StartupPID != 0);
1183 pmState = PM_STARTUP;
1185 status = ServerLoop();
1188 * ServerLoop probably shouldn't ever return, but if it does, close down.
1190 ExitPostmaster(status != STATUS_OK);
1192 abort(); /* not reached */
1197 * on_proc_exit callback to delete external_pid_file
1200 unlink_external_pid_file(int status, Datum arg)
1202 if (external_pid_file)
1203 unlink(external_pid_file);
1208 * Compute and check the directory paths to files that are part of the
1209 * installation (as deduced from the postgres executable's own location)
1212 getInstallationPaths(const char *argv0)
1216 /* Locate the postgres executable itself */
1217 if (find_my_exec(argv0, my_exec_path) < 0)
1218 elog(FATAL, "%s: could not locate my own executable path", argv0);
1221 /* Locate executable backend before we change working directory */
1222 if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1223 postgres_exec_path) < 0)
1225 (errmsg("%s: could not locate matching postgres executable",
1230 * Locate the pkglib directory --- this has to be set early in case we try
1231 * to load any modules from it in response to postgresql.conf entries.
1233 get_pkglib_path(my_exec_path, pkglib_path);
1236 * Verify that there's a readable directory there; otherwise the Postgres
1237 * installation is incomplete or corrupt. (A typical cause of this
1238 * failure is that the postgres executable has been moved or hardlinked to
1239 * some directory that's not a sibling of the installation lib/
1242 pdir = AllocateDir(pkglib_path);
1245 (errcode_for_file_access(),
1246 errmsg("could not open directory \"%s\": %m",
1248 errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1253 * XXX is it worth similarly checking the share/ directory? If the lib/
1254 * directory is there, then share/ probably is too.
1260 * Validate the proposed data directory
1265 char path[MAXPGPATH];
1267 struct stat stat_buf;
1271 if (stat(DataDir, &stat_buf) != 0)
1273 if (errno == ENOENT)
1275 (errcode_for_file_access(),
1276 errmsg("data directory \"%s\" does not exist",
1280 (errcode_for_file_access(),
1281 errmsg("could not read permissions of directory \"%s\": %m",
1285 /* eventual chdir would fail anyway, but let's test ... */
1286 if (!S_ISDIR(stat_buf.st_mode))
1288 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1289 errmsg("specified data directory \"%s\" is not a directory",
1293 * Check that the directory belongs to my userid; if not, reject.
1295 * This check is an essential part of the interlock that prevents two
1296 * postmasters from starting in the same directory (see CreateLockFile()).
1297 * Do not remove or weaken it.
1299 * XXX can we safely enable this check on Windows?
1301 #if !defined(WIN32) && !defined(__CYGWIN__)
1302 if (stat_buf.st_uid != geteuid())
1304 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1305 errmsg("data directory \"%s\" has wrong ownership",
1307 errhint("The server must be started by the user that owns the data directory.")));
1311 * Check if the directory has group or world access. If so, reject.
1313 * It would be possible to allow weaker constraints (for example, allow
1314 * group access) but we cannot make a general assumption that that is
1315 * okay; for example there are platforms where nearly all users
1316 * customarily belong to the same group. Perhaps this test should be
1319 * XXX temporarily suppress check when on Windows, because there may not
1320 * be proper support for Unix-y file permissions. Need to think of a
1321 * reasonable check to apply on Windows.
1323 #if !defined(WIN32) && !defined(__CYGWIN__)
1324 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
1326 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1327 errmsg("data directory \"%s\" has group or world access",
1329 errdetail("Permissions should be u=rwx (0700).")));
1332 /* Look for PG_VERSION before looking for pg_control */
1333 ValidatePgVersion(DataDir);
1335 snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1337 fp = AllocateFile(path, PG_BINARY_R);
1340 write_stderr("%s: could not find the database system\n"
1341 "Expected to find it in the directory \"%s\",\n"
1342 "but could not open file \"%s\": %s\n",
1343 progname, DataDir, path, strerror(errno));
1350 * Main idle loop of postmaster
1360 last_touch_time = time(NULL);
1362 nSockets = initMasks(&readmask);
1370 * Wait for a connection request to arrive.
1372 * We wait at most one minute, to ensure that the other background
1373 * tasks handled below get done even when no requests are arriving.
1375 * If we are in PM_WAIT_DEAD_END state, then we don't want to accept
1376 * any new connections, so we don't call select() at all; just sleep
1377 * for a little bit with signals unblocked.
1379 memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
1381 PG_SETMASK(&UnBlockSig);
1383 if (pmState == PM_WAIT_DEAD_END)
1385 pg_usleep(100000L); /* 100 msec seems reasonable */
1390 /* must set timeout each time; some OSes change it! */
1391 struct timeval timeout;
1393 timeout.tv_sec = 60;
1394 timeout.tv_usec = 0;
1396 selres = select(nSockets, &rmask, NULL, NULL, &timeout);
1400 * Block all signals until we wait again. (This makes it safe for our
1401 * signal handlers to do nontrivial work.)
1403 PG_SETMASK(&BlockSig);
1405 /* Now check the select() result */
1408 if (errno != EINTR && errno != EWOULDBLOCK)
1411 (errcode_for_socket_access(),
1412 errmsg("select() failed in postmaster: %m")));
1413 return STATUS_ERROR;
1418 * New connection pending on any of our sockets? If so, fork a child
1419 * process to deal with it.
1425 for (i = 0; i < MAXLISTEN; i++)
1427 if (ListenSocket[i] == PGINVALID_SOCKET)
1429 if (FD_ISSET(ListenSocket[i], &rmask))
1433 port = ConnCreate(ListenSocket[i]);
1436 BackendStartup(port);
1439 * We no longer need the open socket or port structure
1442 StreamClose(port->sock);
1449 /* If we have lost the log collector, try to start a new one */
1450 if (SysLoggerPID == 0 && Logging_collector)
1451 SysLoggerPID = SysLogger_Start();
1454 * If no background writer process is running, and we are not in a
1455 * state that prevents it, start one. It doesn't matter if this
1456 * fails, we'll just try again later. Likewise for the checkpointer.
1458 if (pmState == PM_RUN || pmState == PM_RECOVERY ||
1459 pmState == PM_HOT_STANDBY)
1461 if (CheckpointerPID == 0)
1462 CheckpointerPID = StartCheckpointer();
1463 if (BgWriterPID == 0)
1464 BgWriterPID = StartBackgroundWriter();
1468 * Likewise, if we have lost the walwriter process, try to start a new
1469 * one. But this is needed only in normal operation (else we cannot
1470 * be writing any new WAL).
1472 if (WalWriterPID == 0 && pmState == PM_RUN)
1473 WalWriterPID = StartWalWriter();
1476 * If we have lost the autovacuum launcher, try to start a new one. We
1477 * don't want autovacuum to run in binary upgrade mode because
1478 * autovacuum might update relfrozenxid for empty tables before the
1479 * physical files are put in place.
1481 if (!IsBinaryUpgrade && AutoVacPID == 0 &&
1482 (AutoVacuumingActive() || start_autovac_launcher) &&
1485 AutoVacPID = StartAutoVacLauncher();
1486 if (AutoVacPID != 0)
1487 start_autovac_launcher = false; /* signal processed */
1490 /* If we have lost the archiver, try to start a new one */
1491 if (XLogArchivingActive() && PgArchPID == 0 && pmState == PM_RUN)
1492 PgArchPID = pgarch_start();
1494 /* If we have lost the stats collector, try to start a new one */
1495 if (PgStatPID == 0 && pmState == PM_RUN)
1496 PgStatPID = pgstat_start();
1498 /* If we need to signal the autovacuum launcher, do so now */
1499 if (avlauncher_needs_signal)
1501 avlauncher_needs_signal = false;
1502 if (AutoVacPID != 0)
1503 kill(AutoVacPID, SIGUSR2);
1507 * Touch Unix socket and lock files every 58 minutes, to ensure that
1508 * they are not removed by overzealous /tmp-cleaning tasks. We assume
1509 * no one runs cleaners with cutoff times of less than an hour ...
1512 if (now - last_touch_time >= 58 * SECS_PER_MINUTE)
1515 TouchSocketLockFiles();
1516 last_touch_time = now;
1523 * Initialise the masks for select() for the ports we are listening on.
1524 * Return the number of sockets to listen on.
1527 initMasks(fd_set *rmask)
1534 for (i = 0; i < MAXLISTEN; i++)
1536 int fd = ListenSocket[i];
1538 if (fd == PGINVALID_SOCKET)
1551 * Read a client's startup packet and do something according to it.
1553 * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
1554 * not return at all.
1556 * (Note that ereport(FATAL) stuff is sent to the client, so only use it
1557 * if that's what you want. Return STATUS_ERROR if you don't want to
1558 * send anything to the client, which would typically be appropriate
1559 * if we detect a communications failure.)
1562 ProcessStartupPacket(Port *port, bool SSLdone)
1566 ProtocolVersion proto;
1567 MemoryContext oldcontext;
1569 if (pq_getbytes((char *) &len, 4) == EOF)
1572 * EOF after SSLdone probably means the client didn't like our
1573 * response to NEGOTIATE_SSL_CODE. That's not an error condition, so
1574 * don't clutter the log with a complaint.
1578 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1579 errmsg("incomplete startup packet")));
1580 return STATUS_ERROR;
1586 if (len < (int32) sizeof(ProtocolVersion) ||
1587 len > MAX_STARTUP_PACKET_LENGTH)
1590 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1591 errmsg("invalid length of startup packet")));
1592 return STATUS_ERROR;
1596 * Allocate at least the size of an old-style startup packet, plus one
1597 * extra byte, and make sure all are zeroes. This ensures we will have
1598 * null termination of all strings, in both fixed- and variable-length
1601 if (len <= (int32) sizeof(StartupPacket))
1602 buf = palloc0(sizeof(StartupPacket) + 1);
1604 buf = palloc0(len + 1);
1606 if (pq_getbytes(buf, len) == EOF)
1609 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1610 errmsg("incomplete startup packet")));
1611 return STATUS_ERROR;
1615 * The first field is either a protocol version number or a special
1618 port->proto = proto = ntohl(*((ProtocolVersion *) buf));
1620 if (proto == CANCEL_REQUEST_CODE)
1622 processCancelRequest(port, buf);
1623 /* Not really an error, but we don't want to proceed further */
1624 return STATUS_ERROR;
1627 if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
1632 /* No SSL when disabled or on Unix sockets */
1633 if (!EnableSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
1636 SSLok = 'S'; /* Support for SSL */
1638 SSLok = 'N'; /* No support for SSL */
1642 if (send(port->sock, &SSLok, 1, 0) != 1)
1645 goto retry1; /* if interrupted, just retry */
1647 (errcode_for_socket_access(),
1648 errmsg("failed to send SSL negotiation response: %m")));
1649 return STATUS_ERROR; /* close the connection */
1653 if (SSLok == 'S' && secure_open_server(port) == -1)
1654 return STATUS_ERROR;
1656 /* regular startup packet, cancel, etc packet should follow... */
1657 /* but not another SSL negotiation request */
1658 return ProcessStartupPacket(port, true);
1661 /* Could add additional special packet types here */
1664 * Set FrontendProtocol now so that ereport() knows what format to send if
1665 * we fail during startup.
1667 FrontendProtocol = proto;
1669 /* Check we can handle the protocol the frontend is using. */
1671 if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
1672 PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
1673 (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
1674 PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
1676 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1677 errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
1678 PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
1679 PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST),
1680 PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST),
1681 PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))));
1684 * Now fetch parameters out of startup packet and save them into the Port
1685 * structure. All data structures attached to the Port struct must be
1686 * allocated in TopMemoryContext so that they will remain available in a
1687 * running backend (even after PostmasterContext is destroyed). We need
1688 * not worry about leaking this storage on failure, since we aren't in the
1689 * postmaster process anymore.
1691 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1693 if (PG_PROTOCOL_MAJOR(proto) >= 3)
1695 int32 offset = sizeof(ProtocolVersion);
1698 * Scan packet body for name/option pairs. We can assume any string
1699 * beginning within the packet body is null-terminated, thanks to
1700 * zeroing extra byte above.
1702 port->guc_options = NIL;
1704 while (offset < len)
1706 char *nameptr = ((char *) buf) + offset;
1710 if (*nameptr == '\0')
1711 break; /* found packet terminator */
1712 valoffset = offset + strlen(nameptr) + 1;
1713 if (valoffset >= len)
1714 break; /* missing value, will complain below */
1715 valptr = ((char *) buf) + valoffset;
1717 if (strcmp(nameptr, "database") == 0)
1718 port->database_name = pstrdup(valptr);
1719 else if (strcmp(nameptr, "user") == 0)
1720 port->user_name = pstrdup(valptr);
1721 else if (strcmp(nameptr, "options") == 0)
1722 port->cmdline_options = pstrdup(valptr);
1723 else if (strcmp(nameptr, "replication") == 0)
1725 if (!parse_bool(valptr, &am_walsender))
1727 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1728 errmsg("invalid value for boolean option \"replication\"")));
1732 /* Assume it's a generic GUC option */
1733 port->guc_options = lappend(port->guc_options,
1735 port->guc_options = lappend(port->guc_options,
1738 offset = valoffset + strlen(valptr) + 1;
1742 * If we didn't find a packet terminator exactly at the end of the
1743 * given packet length, complain.
1745 if (offset != len - 1)
1747 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1748 errmsg("invalid startup packet layout: expected terminator as last byte")));
1753 * Get the parameters from the old-style, fixed-width-fields startup
1754 * packet as C strings. The packet destination was cleared first so a
1755 * short packet has zeros silently added. We have to be prepared to
1756 * truncate the pstrdup result for oversize fields, though.
1758 StartupPacket *packet = (StartupPacket *) buf;
1760 port->database_name = pstrdup(packet->database);
1761 if (strlen(port->database_name) > sizeof(packet->database))
1762 port->database_name[sizeof(packet->database)] = '\0';
1763 port->user_name = pstrdup(packet->user);
1764 if (strlen(port->user_name) > sizeof(packet->user))
1765 port->user_name[sizeof(packet->user)] = '\0';
1766 port->cmdline_options = pstrdup(packet->options);
1767 if (strlen(port->cmdline_options) > sizeof(packet->options))
1768 port->cmdline_options[sizeof(packet->options)] = '\0';
1769 port->guc_options = NIL;
1772 /* Check a user name was given. */
1773 if (port->user_name == NULL || port->user_name[0] == '\0')
1775 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1776 errmsg("no PostgreSQL user name specified in startup packet")));
1778 /* The database defaults to the user name. */
1779 if (port->database_name == NULL || port->database_name[0] == '\0')
1780 port->database_name = pstrdup(port->user_name);
1782 if (Db_user_namespace)
1785 * If user@, it is a global user, remove '@'. We only want to do this
1786 * if there is an '@' at the end and no earlier in the user string or
1787 * they may fake as a local user of another database attaching to this
1790 if (strchr(port->user_name, '@') ==
1791 port->user_name + strlen(port->user_name) - 1)
1792 *strchr(port->user_name, '@') = '\0';
1795 /* Append '@' and dbname */
1798 db_user = palloc(strlen(port->user_name) +
1799 strlen(port->database_name) + 2);
1800 sprintf(db_user, "%s@%s", port->user_name, port->database_name);
1801 port->user_name = db_user;
1806 * Truncate given database and user names to length of a Postgres name.
1807 * This avoids lookup failures when overlength names are given.
1809 if (strlen(port->database_name) >= NAMEDATALEN)
1810 port->database_name[NAMEDATALEN - 1] = '\0';
1811 if (strlen(port->user_name) >= NAMEDATALEN)
1812 port->user_name[NAMEDATALEN - 1] = '\0';
1814 /* Walsender is not related to a particular database */
1816 port->database_name[0] = '\0';
1819 * Done putting stuff in TopMemoryContext.
1821 MemoryContextSwitchTo(oldcontext);
1824 * If we're going to reject the connection due to database state, say so
1825 * now instead of wasting cycles on an authentication exchange. (This also
1826 * allows a pg_ping utility to be written.)
1828 switch (port->canAcceptConnections)
1832 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1833 errmsg("the database system is starting up")));
1837 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1838 errmsg("the database system is shutting down")));
1842 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1843 errmsg("the database system is in recovery mode")));
1847 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
1848 errmsg("sorry, too many clients already")));
1850 case CAC_WAITBACKUP:
1851 /* OK for now, will check in InitPostgres */
1862 * The client has sent a cancel request packet, not a normal
1863 * start-a-new-connection packet. Perform the necessary processing.
1864 * Nothing is sent back to the client.
1867 processCancelRequest(Port *port, void *pkt)
1869 CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
1871 long cancelAuthCode;
1874 #ifndef EXEC_BACKEND
1880 backendPID = (int) ntohl(canc->backendPID);
1881 cancelAuthCode = (long) ntohl(canc->cancelAuthCode);
1884 * See if we have a matching backend. In the EXEC_BACKEND case, we can no
1885 * longer access the postmaster's own backend list, and must rely on the
1886 * duplicate array in shared memory.
1888 #ifndef EXEC_BACKEND
1889 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
1891 bp = (Backend *) DLE_VAL(curr);
1893 for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
1895 bp = (Backend *) &ShmemBackendArray[i];
1897 if (bp->pid == backendPID)
1899 if (bp->cancel_key == cancelAuthCode)
1901 /* Found a match; signal that backend to cancel current op */
1903 (errmsg_internal("processing cancel request: sending SIGINT to process %d",
1905 signal_child(bp->pid, SIGINT);
1908 /* Right PID, wrong key: no way, Jose */
1910 (errmsg("wrong key in cancel request for process %d",
1916 /* No matching backend */
1918 (errmsg("PID %d in cancel request did not match any process",
1923 * canAcceptConnections --- check to see if database state allows connections.
1926 canAcceptConnections(void)
1928 CAC_state result = CAC_OK;
1931 * Can't start backends when in startup/shutdown/inconsistent recovery
1934 * In state PM_WAIT_BACKUP only superusers can connect (this must be
1935 * allowed so that a superuser can end online backup mode); we return
1936 * CAC_WAITBACKUP code to indicate that this must be checked later. Note
1937 * that neither CAC_OK nor CAC_WAITBACKUP can safely be returned until we
1938 * have checked for too many children.
1940 if (pmState != PM_RUN)
1942 if (pmState == PM_WAIT_BACKUP)
1943 result = CAC_WAITBACKUP; /* allow superusers only */
1944 else if (Shutdown > NoShutdown)
1945 return CAC_SHUTDOWN; /* shutdown is pending */
1946 else if (!FatalError &&
1947 (pmState == PM_STARTUP ||
1948 pmState == PM_RECOVERY))
1949 return CAC_STARTUP; /* normal startup */
1950 else if (!FatalError &&
1951 pmState == PM_HOT_STANDBY)
1952 result = CAC_OK; /* connection OK during hot standby */
1954 return CAC_RECOVERY; /* else must be crash recovery */
1958 * Don't start too many children.
1960 * We allow more connections than we can have backends here because some
1961 * might still be authenticating; they might fail auth, or some existing
1962 * backend might exit before the auth cycle is completed. The exact
1963 * MaxBackends limit is enforced when a new backend tries to join the
1964 * shared-inval backend array.
1966 * The limit here must match the sizes of the per-child-process arrays;
1967 * see comments for MaxLivePostmasterChildren().
1969 if (CountChildren(BACKEND_TYPE_ALL) >= MaxLivePostmasterChildren())
1970 result = CAC_TOOMANY;
1977 * ConnCreate -- create a local connection data structure
1979 * Returns NULL on failure, other than out-of-memory which is fatal.
1982 ConnCreate(int serverFd)
1986 if (!(port = (Port *) calloc(1, sizeof(Port))))
1989 (errcode(ERRCODE_OUT_OF_MEMORY),
1990 errmsg("out of memory")));
1994 if (StreamConnection(serverFd, port) != STATUS_OK)
1996 if (port->sock >= 0)
1997 StreamClose(port->sock);
2003 * Precompute password salt values to use for this connection. It's
2004 * slightly annoying to do this long in advance of knowing whether we'll
2005 * need 'em or not, but we must do the random() calls before we fork, not
2006 * after. Else the postmaster's random sequence won't get advanced, and
2007 * all backends would end up using the same salt...
2009 RandomSalt(port->md5Salt);
2012 * Allocate GSSAPI specific state struct
2014 #ifndef EXEC_BACKEND
2015 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2016 port->gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
2020 (errcode(ERRCODE_OUT_OF_MEMORY),
2021 errmsg("out of memory")));
2032 * ConnFree -- free a local connection data structure
2035 ConnFree(Port *conn)
2047 * ClosePostmasterPorts -- close all the postmaster's open sockets
2049 * This is called during child process startup to release file descriptors
2050 * that are not needed by that child process. The postmaster still has
2051 * them open, of course.
2053 * Note: we pass am_syslogger as a boolean because we don't want to set
2054 * the global variable yet when this is called.
2057 ClosePostmasterPorts(bool am_syslogger)
2064 * Close the write end of postmaster death watch pipe. It's important to
2065 * do this as early as possible, so that if postmaster dies, others won't
2066 * think that it's still running because we're holding the pipe open.
2068 if (close(postmaster_alive_fds[POSTMASTER_FD_OWN]))
2070 (errcode_for_file_access(),
2071 errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
2072 postmaster_alive_fds[POSTMASTER_FD_OWN] = -1;
2075 /* Close the listen sockets */
2076 for (i = 0; i < MAXLISTEN; i++)
2078 if (ListenSocket[i] != PGINVALID_SOCKET)
2080 StreamClose(ListenSocket[i]);
2081 ListenSocket[i] = PGINVALID_SOCKET;
2085 /* If using syslogger, close the read side of the pipe */
2089 if (syslogPipe[0] >= 0)
2090 close(syslogPipe[0]);
2094 CloseHandle(syslogPipe[0]);
2100 /* If using Bonjour, close the connection to the mDNS daemon */
2102 close(DNSServiceRefSockFD(bonjour_sdref));
2108 * reset_shared -- reset shared memory and semaphores
2111 reset_shared(int port)
2114 * Create or re-create shared memory and semaphores.
2116 * Note: in each "cycle of life" we will normally assign the same IPC keys
2117 * (if using SysV shmem and/or semas), since the port number is used to
2118 * determine IPC keys. This helps ensure that we will clean up dead IPC
2119 * objects if the postmaster crashes and is restarted.
2121 CreateSharedMemoryAndSemaphores(false, port);
2126 * SIGHUP -- reread config files, and tell children to do same
2129 SIGHUP_handler(SIGNAL_ARGS)
2131 int save_errno = errno;
2133 PG_SETMASK(&BlockSig);
2135 if (Shutdown <= SmartShutdown)
2138 (errmsg("received SIGHUP, reloading configuration files")));
2139 ProcessConfigFile(PGC_SIGHUP);
2140 SignalChildren(SIGHUP);
2141 if (StartupPID != 0)
2142 signal_child(StartupPID, SIGHUP);
2143 if (BgWriterPID != 0)
2144 signal_child(BgWriterPID, SIGHUP);
2145 if (CheckpointerPID != 0)
2146 signal_child(CheckpointerPID, SIGHUP);
2147 if (WalWriterPID != 0)
2148 signal_child(WalWriterPID, SIGHUP);
2149 if (WalReceiverPID != 0)
2150 signal_child(WalReceiverPID, SIGHUP);
2151 if (AutoVacPID != 0)
2152 signal_child(AutoVacPID, SIGHUP);
2154 signal_child(PgArchPID, SIGHUP);
2155 if (SysLoggerPID != 0)
2156 signal_child(SysLoggerPID, SIGHUP);
2158 signal_child(PgStatPID, SIGHUP);
2160 /* Reload authentication config files too */
2163 (errmsg("pg_hba.conf not reloaded")));
2167 (errmsg("pg_ident.conf not reloaded")));
2170 /* Update the starting-point file for future children */
2171 write_nondefault_variables(PGC_SIGHUP);
2175 PG_SETMASK(&UnBlockSig);
2182 * pmdie -- signal handler for processing various postmaster signals.
2187 int save_errno = errno;
2189 PG_SETMASK(&BlockSig);
2192 (errmsg_internal("postmaster received signal %d",
2193 postgres_signal_arg)));
2195 switch (postgres_signal_arg)
2202 * Wait for children to end their work, then shut down.
2204 if (Shutdown >= SmartShutdown)
2206 Shutdown = SmartShutdown;
2208 (errmsg("received smart shutdown request")));
2210 if (pmState == PM_RUN || pmState == PM_RECOVERY ||
2211 pmState == PM_HOT_STANDBY || pmState == PM_STARTUP)
2213 /* autovacuum workers are told to shut down immediately */
2214 SignalSomeChildren(SIGTERM, BACKEND_TYPE_AUTOVAC);
2215 /* and the autovac launcher too */
2216 if (AutoVacPID != 0)
2217 signal_child(AutoVacPID, SIGTERM);
2218 /* and the bgwriter too */
2219 if (BgWriterPID != 0)
2220 signal_child(BgWriterPID, SIGTERM);
2221 /* and the walwriter too */
2222 if (WalWriterPID != 0)
2223 signal_child(WalWriterPID, SIGTERM);
2226 * If we're in recovery, we can't kill the startup process
2227 * right away, because at present doing so does not release
2228 * its locks. We might want to change this in a future
2229 * release. For the time being, the PM_WAIT_READONLY state
2230 * indicates that we're waiting for the regular (read only)
2231 * backends to die off; once they do, we'll kill the startup
2232 * and walreceiver processes.
2234 pmState = (pmState == PM_RUN) ?
2235 PM_WAIT_BACKUP : PM_WAIT_READONLY;
2239 * Now wait for online backup mode to end and backends to exit. If
2240 * that is already the case, PostmasterStateMachine will take the
2243 PostmasterStateMachine();
2251 * Abort all children with SIGTERM (rollback active transactions
2252 * and exit) and shut down when they are gone.
2254 if (Shutdown >= FastShutdown)
2256 Shutdown = FastShutdown;
2258 (errmsg("received fast shutdown request")));
2260 if (StartupPID != 0)
2261 signal_child(StartupPID, SIGTERM);
2262 if (BgWriterPID != 0)
2263 signal_child(BgWriterPID, SIGTERM);
2264 if (WalReceiverPID != 0)
2265 signal_child(WalReceiverPID, SIGTERM);
2266 if (pmState == PM_RECOVERY)
2269 * Only startup, bgwriter, and checkpointer should be active
2270 * in this state; we just signaled the first two, and we don't
2271 * want to kill checkpointer yet.
2273 pmState = PM_WAIT_BACKENDS;
2275 else if (pmState == PM_RUN ||
2276 pmState == PM_WAIT_BACKUP ||
2277 pmState == PM_WAIT_READONLY ||
2278 pmState == PM_WAIT_BACKENDS ||
2279 pmState == PM_HOT_STANDBY)
2282 (errmsg("aborting any active transactions")));
2283 /* shut down all backends and autovac workers */
2284 SignalSomeChildren(SIGTERM,
2285 BACKEND_TYPE_NORMAL | BACKEND_TYPE_AUTOVAC);
2286 /* and the autovac launcher too */
2287 if (AutoVacPID != 0)
2288 signal_child(AutoVacPID, SIGTERM);
2289 /* and the walwriter too */
2290 if (WalWriterPID != 0)
2291 signal_child(WalWriterPID, SIGTERM);
2292 pmState = PM_WAIT_BACKENDS;
2296 * Now wait for backends to exit. If there are none,
2297 * PostmasterStateMachine will take the next step.
2299 PostmasterStateMachine();
2305 * Immediate Shutdown:
2307 * abort all children with SIGQUIT and exit without attempt to
2308 * properly shut down data base system.
2311 (errmsg("received immediate shutdown request")));
2312 SignalChildren(SIGQUIT);
2313 if (StartupPID != 0)
2314 signal_child(StartupPID, SIGQUIT);
2315 if (BgWriterPID != 0)
2316 signal_child(BgWriterPID, SIGQUIT);
2317 if (CheckpointerPID != 0)
2318 signal_child(CheckpointerPID, SIGQUIT);
2319 if (WalWriterPID != 0)
2320 signal_child(WalWriterPID, SIGQUIT);
2321 if (WalReceiverPID != 0)
2322 signal_child(WalReceiverPID, SIGQUIT);
2323 if (AutoVacPID != 0)
2324 signal_child(AutoVacPID, SIGQUIT);
2326 signal_child(PgArchPID, SIGQUIT);
2328 signal_child(PgStatPID, SIGQUIT);
2333 PG_SETMASK(&UnBlockSig);
2339 * Reaper -- signal handler to cleanup after a child process dies.
2344 int save_errno = errno;
2345 int pid; /* process id of dead child process */
2346 int exitstatus; /* its exit status */
2348 PG_SETMASK(&BlockSig);
2351 (errmsg_internal("reaping dead processes")));
2353 while ((pid = waitpid(-1, &exitstatus, WNOHANG)) > 0)
2356 * Check if this child was a startup process.
2358 if (pid == StartupPID)
2363 * Unexpected exit of startup process (including FATAL exit)
2364 * during PM_STARTUP is treated as catastrophic. There are no
2365 * other processes running yet, so we can just exit.
2367 if (pmState == PM_STARTUP && !EXIT_STATUS_0(exitstatus))
2369 LogChildExit(LOG, _("startup process"),
2372 (errmsg("aborting startup due to startup process failure")));
2377 * Startup process exited in response to a shutdown request (or it
2378 * completed normally regardless of the shutdown request).
2380 if (Shutdown > NoShutdown &&
2381 (EXIT_STATUS_0(exitstatus) || EXIT_STATUS_1(exitstatus)))
2383 pmState = PM_WAIT_BACKENDS;
2384 /* PostmasterStateMachine logic does the rest */
2389 * After PM_STARTUP, any unexpected exit (including FATAL exit) of
2390 * the startup process is catastrophic, so kill other children,
2391 * and set RecoveryError so we don't try to reinitialize after
2392 * they're gone. Exception: if FatalError is already set, that
2393 * implies we previously sent the startup process a SIGQUIT, so
2394 * that's probably the reason it died, and we do want to try to
2395 * restart in that case.
2397 if (!EXIT_STATUS_0(exitstatus))
2400 RecoveryError = true;
2401 HandleChildCrash(pid, exitstatus,
2402 _("startup process"));
2407 * Startup succeeded, commence normal operations
2410 ReachedNormalRunning = true;
2414 * Kill any walsenders to force the downstream standby(s) to
2415 * reread the timeline history file, adjust their timelines and
2416 * establish replication connections again. This is required
2417 * because the timeline of cascading standby is not consistent
2418 * with that of cascaded one just after failover. We LOG this
2419 * message since we need to leave a record to explain this
2422 * XXX should avoid the need for disconnection. When we do,
2423 * am_cascading_walsender should be replaced with
2424 * RecoveryInProgress()
2426 if (max_wal_senders > 0 && CountChildren(BACKEND_TYPE_WALSND) > 0)
2429 (errmsg("terminating all walsender processes to force cascaded "
2430 "standby(s) to update timeline and reconnect")));
2431 SignalSomeChildren(SIGUSR2, BACKEND_TYPE_WALSND);
2435 * Crank up the background tasks, if we didn't do that already
2436 * when we entered consistent recovery state. It doesn't matter
2437 * if this fails, we'll just try again later.
2439 if (CheckpointerPID == 0)
2440 CheckpointerPID = StartCheckpointer();
2441 if (BgWriterPID == 0)
2442 BgWriterPID = StartBackgroundWriter();
2443 if (WalWriterPID == 0)
2444 WalWriterPID = StartWalWriter();
2447 * Likewise, start other special children as needed. In a restart
2448 * situation, some of them may be alive already.
2450 if (!IsBinaryUpgrade && AutoVacuumingActive() && AutoVacPID == 0)
2451 AutoVacPID = StartAutoVacLauncher();
2452 if (XLogArchivingActive() && PgArchPID == 0)
2453 PgArchPID = pgarch_start();
2455 PgStatPID = pgstat_start();
2457 /* at this point we are really open for business */
2459 (errmsg("database system is ready to accept connections")));
2465 * Was it the bgwriter? Normal exit can be ignored; we'll start a new
2466 * one at the next iteration of the postmaster's main loop, if
2467 * necessary. Any other exit condition is treated as a crash.
2469 if (pid == BgWriterPID)
2472 if (!EXIT_STATUS_0(exitstatus))
2473 HandleChildCrash(pid, exitstatus,
2474 _("background writer process"));
2479 * Was it the checkpointer?
2481 if (pid == CheckpointerPID)
2483 CheckpointerPID = 0;
2484 if (EXIT_STATUS_0(exitstatus) && pmState == PM_SHUTDOWN)
2487 * OK, we saw normal exit of the checkpointer after it's been
2488 * told to shut down. We expect that it wrote a shutdown
2489 * checkpoint. (If for some reason it didn't, recovery will
2490 * occur on next postmaster start.)
2492 * At this point we should have no normal backend children
2493 * left (else we'd not be in PM_SHUTDOWN state) but we might
2494 * have dead_end children to wait for.
2496 * If we have an archiver subprocess, tell it to do a last
2497 * archive cycle and quit. Likewise, if we have walsender
2498 * processes, tell them to send any remaining WAL and quit.
2500 Assert(Shutdown > NoShutdown);
2502 /* Waken archiver for the last time */
2504 signal_child(PgArchPID, SIGUSR2);
2507 * Waken walsenders for the last time. No regular backends
2508 * should be around anymore.
2510 SignalChildren(SIGUSR2);
2512 pmState = PM_SHUTDOWN_2;
2515 * We can also shut down the stats collector now; there's
2516 * nothing left for it to do.
2519 signal_child(PgStatPID, SIGQUIT);
2524 * Any unexpected exit of the checkpointer (including FATAL
2525 * exit) is treated as a crash.
2527 HandleChildCrash(pid, exitstatus,
2528 _("checkpointer process"));
2535 * Was it the wal writer? Normal exit can be ignored; we'll start a
2536 * new one at the next iteration of the postmaster's main loop, if
2537 * necessary. Any other exit condition is treated as a crash.
2539 if (pid == WalWriterPID)
2542 if (!EXIT_STATUS_0(exitstatus))
2543 HandleChildCrash(pid, exitstatus,
2544 _("WAL writer process"));
2549 * Was it the wal receiver? If exit status is zero (normal) or one
2550 * (FATAL exit), we assume everything is all right just like normal
2553 if (pid == WalReceiverPID)
2556 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2557 HandleChildCrash(pid, exitstatus,
2558 _("WAL receiver process"));
2563 * Was it the autovacuum launcher? Normal exit can be ignored; we'll
2564 * start a new one at the next iteration of the postmaster's main
2565 * loop, if necessary. Any other exit condition is treated as a
2568 if (pid == AutoVacPID)
2571 if (!EXIT_STATUS_0(exitstatus))
2572 HandleChildCrash(pid, exitstatus,
2573 _("autovacuum launcher process"));
2578 * Was it the archiver? If so, just try to start a new one; no need
2579 * to force reset of the rest of the system. (If fail, we'll try
2580 * again in future cycles of the main loop.). Unless we were waiting
2581 * for it to shut down; don't restart it in that case, and
2582 * PostmasterStateMachine() will advance to the next shutdown step.
2584 if (pid == PgArchPID)
2587 if (!EXIT_STATUS_0(exitstatus))
2588 LogChildExit(LOG, _("archiver process"),
2590 if (XLogArchivingActive() && pmState == PM_RUN)
2591 PgArchPID = pgarch_start();
2596 * Was it the statistics collector? If so, just try to start a new
2597 * one; no need to force reset of the rest of the system. (If fail,
2598 * we'll try again in future cycles of the main loop.)
2600 if (pid == PgStatPID)
2603 if (!EXIT_STATUS_0(exitstatus))
2604 LogChildExit(LOG, _("statistics collector process"),
2606 if (pmState == PM_RUN)
2607 PgStatPID = pgstat_start();
2611 /* Was it the system logger? If so, try to start a new one */
2612 if (pid == SysLoggerPID)
2615 /* for safety's sake, launch new logger *first* */
2616 SysLoggerPID = SysLogger_Start();
2617 if (!EXIT_STATUS_0(exitstatus))
2618 LogChildExit(LOG, _("system logger process"),
2624 * Else do standard backend child cleanup.
2626 CleanupBackend(pid, exitstatus);
2627 } /* loop over pending child-death reports */
2630 * After cleaning out the SIGCHLD queue, see if we have any state changes
2631 * or actions to make.
2633 PostmasterStateMachine();
2635 /* Done with signal handler */
2636 PG_SETMASK(&UnBlockSig);
2643 * CleanupBackend -- cleanup after terminated backend.
2645 * Remove all local state associated with backend.
2648 CleanupBackend(int pid,
2649 int exitstatus) /* child's exit status. */
2653 LogChildExit(DEBUG2, _("server process"), pid, exitstatus);
2656 * If a backend dies in an ugly way then we must signal all other backends
2657 * to quickdie. If exit status is zero (normal) or one (FATAL exit), we
2658 * assume everything is all right and proceed to remove the backend from
2659 * the active backend list.
2664 * On win32, also treat ERROR_WAIT_NO_CHILDREN (128) as nonfatal case,
2665 * since that sometimes happens under load when the process fails to start
2666 * properly (long before it starts using shared memory). Microsoft reports
2667 * it is related to mutex failure:
2668 * http://archives.postgresql.org/pgsql-hackers/2010-09/msg00790.php
2670 if (exitstatus == ERROR_WAIT_NO_CHILDREN)
2672 LogChildExit(LOG, _("server process"), pid, exitstatus);
2677 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2679 HandleChildCrash(pid, exitstatus, _("server process"));
2683 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2685 Backend *bp = (Backend *) DLE_VAL(curr);
2691 if (!ReleasePostmasterChildSlot(bp->child_slot))
2694 * Uh-oh, the child failed to clean itself up. Treat as a
2697 HandleChildCrash(pid, exitstatus, _("server process"));
2701 ShmemBackendArrayRemove(bp);
2712 * HandleChildCrash -- cleanup after failed backend, bgwriter, checkpointer,
2713 * walwriter or autovacuum.
2715 * The objectives here are to clean up our local state about the child
2716 * process, and to signal all other remaining children to quickdie.
2719 HandleChildCrash(int pid, int exitstatus, const char *procname)
2726 * Make log entry unless there was a previous crash (if so, nonzero exit
2727 * status is to be expected in SIGQUIT response; don't clutter log)
2731 LogChildExit(LOG, procname, pid, exitstatus);
2733 (errmsg("terminating any other active server processes")));
2736 /* Process regular backends */
2737 for (curr = DLGetHead(BackendList); curr; curr = next)
2739 next = DLGetSucc(curr);
2740 bp = (Backend *) DLE_VAL(curr);
2744 * Found entry for freshly-dead backend, so remove it.
2748 (void) ReleasePostmasterChildSlot(bp->child_slot);
2750 ShmemBackendArrayRemove(bp);
2755 /* Keep looping so we can signal remaining backends */
2760 * This backend is still alive. Unless we did so already, tell it
2761 * to commit hara-kiri.
2763 * SIGQUIT is the special signal that says exit without proc_exit
2764 * and let the user know what's going on. But if SendStop is set
2765 * (-s on command line), then we send SIGSTOP instead, so that we
2766 * can get core dumps from all backends by hand.
2768 * We could exclude dead_end children here, but at least in the
2769 * SIGSTOP case it seems better to include them.
2774 (errmsg_internal("sending %s to process %d",
2775 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2777 signal_child(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
2782 /* Take care of the startup process too */
2783 if (pid == StartupPID)
2785 else if (StartupPID != 0 && !FatalError)
2788 (errmsg_internal("sending %s to process %d",
2789 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2790 (int) StartupPID)));
2791 signal_child(StartupPID, (SendStop ? SIGSTOP : SIGQUIT));
2794 /* Take care of the bgwriter too */
2795 if (pid == BgWriterPID)
2797 else if (BgWriterPID != 0 && !FatalError)
2800 (errmsg_internal("sending %s to process %d",
2801 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2802 (int) BgWriterPID)));
2803 signal_child(BgWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
2806 /* Take care of the checkpointer too */
2807 if (pid == CheckpointerPID)
2808 CheckpointerPID = 0;
2809 else if (CheckpointerPID != 0 && !FatalError)
2812 (errmsg_internal("sending %s to process %d",
2813 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2814 (int) CheckpointerPID)));
2815 signal_child(CheckpointerPID, (SendStop ? SIGSTOP : SIGQUIT));
2818 /* Take care of the walwriter too */
2819 if (pid == WalWriterPID)
2821 else if (WalWriterPID != 0 && !FatalError)
2824 (errmsg_internal("sending %s to process %d",
2825 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2826 (int) WalWriterPID)));
2827 signal_child(WalWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
2830 /* Take care of the walreceiver too */
2831 if (pid == WalReceiverPID)
2833 else if (WalReceiverPID != 0 && !FatalError)
2836 (errmsg_internal("sending %s to process %d",
2837 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2838 (int) WalReceiverPID)));
2839 signal_child(WalReceiverPID, (SendStop ? SIGSTOP : SIGQUIT));
2842 /* Take care of the autovacuum launcher too */
2843 if (pid == AutoVacPID)
2845 else if (AutoVacPID != 0 && !FatalError)
2848 (errmsg_internal("sending %s to process %d",
2849 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2850 (int) AutoVacPID)));
2851 signal_child(AutoVacPID, (SendStop ? SIGSTOP : SIGQUIT));
2855 * Force a power-cycle of the pgarch process too. (This isn't absolutely
2856 * necessary, but it seems like a good idea for robustness, and it
2857 * simplifies the state-machine logic in the case where a shutdown request
2858 * arrives during crash processing.)
2860 if (PgArchPID != 0 && !FatalError)
2863 (errmsg_internal("sending %s to process %d",
2866 signal_child(PgArchPID, SIGQUIT);
2870 * Force a power-cycle of the pgstat process too. (This isn't absolutely
2871 * necessary, but it seems like a good idea for robustness, and it
2872 * simplifies the state-machine logic in the case where a shutdown request
2873 * arrives during crash processing.)
2875 if (PgStatPID != 0 && !FatalError)
2878 (errmsg_internal("sending %s to process %d",
2881 signal_child(PgStatPID, SIGQUIT);
2882 allow_immediate_pgstat_restart();
2885 /* We do NOT restart the syslogger */
2888 /* We now transit into a state of waiting for children to die */
2889 if (pmState == PM_RECOVERY ||
2890 pmState == PM_HOT_STANDBY ||
2891 pmState == PM_RUN ||
2892 pmState == PM_WAIT_BACKUP ||
2893 pmState == PM_WAIT_READONLY ||
2894 pmState == PM_SHUTDOWN)
2895 pmState = PM_WAIT_BACKENDS;
2899 * Log the death of a child process.
2902 LogChildExit(int lev, const char *procname, int pid, int exitstatus)
2905 * size of activity_buffer is arbitrary, but set equal to default
2906 * track_activity_query_size
2908 char activity_buffer[1024];
2909 const char *activity = NULL;
2911 if (!EXIT_STATUS_0(exitstatus))
2912 activity = pgstat_get_crashed_backend_activity(pid,
2914 sizeof(activity_buffer));
2916 if (WIFEXITED(exitstatus))
2920 translator: %s is a noun phrase describing a child process, such as
2922 (errmsg("%s (PID %d) exited with exit code %d",
2923 procname, pid, WEXITSTATUS(exitstatus)),
2924 activity ? errdetail("Failed process was running: %s", activity) : 0));
2925 else if (WIFSIGNALED(exitstatus))
2930 translator: %s is a noun phrase describing a child process, such as
2932 (errmsg("%s (PID %d) was terminated by exception 0x%X",
2933 procname, pid, WTERMSIG(exitstatus)),
2934 errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
2935 activity ? errdetail("Failed process was running: %s", activity) : 0));
2936 #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST
2940 translator: %s is a noun phrase describing a child process, such as
2942 (errmsg("%s (PID %d) was terminated by signal %d: %s",
2943 procname, pid, WTERMSIG(exitstatus),
2944 WTERMSIG(exitstatus) < NSIG ?
2945 sys_siglist[WTERMSIG(exitstatus)] : "(unknown)"),
2946 activity ? errdetail("Failed process was running: %s", activity) : 0));
2951 translator: %s is a noun phrase describing a child process, such as
2953 (errmsg("%s (PID %d) was terminated by signal %d",
2954 procname, pid, WTERMSIG(exitstatus)),
2955 activity ? errdetail("Failed process was running: %s", activity) : 0));
2961 translator: %s is a noun phrase describing a child process, such as
2963 (errmsg("%s (PID %d) exited with unrecognized status %d",
2964 procname, pid, exitstatus),
2965 activity ? errdetail("Failed process was running: %s", activity) : 0));
2969 * Advance the postmaster's state machine and take actions as appropriate
2971 * This is common code for pmdie(), reaper() and sigusr1_handler(), which
2972 * receive the signals that might mean we need to change state.
2975 PostmasterStateMachine(void)
2977 if (pmState == PM_WAIT_BACKUP)
2980 * PM_WAIT_BACKUP state ends when online backup mode is not active.
2982 if (!BackupInProgress())
2983 pmState = PM_WAIT_BACKENDS;
2986 if (pmState == PM_WAIT_READONLY)
2989 * PM_WAIT_READONLY state ends when we have no regular backends that
2990 * have been started during recovery. We kill the startup and
2991 * walreceiver processes and transition to PM_WAIT_BACKENDS. Ideally,
2992 * we might like to kill these processes first and then wait for
2993 * backends to die off, but that doesn't work at present because
2994 * killing the startup process doesn't release its locks.
2996 if (CountChildren(BACKEND_TYPE_NORMAL) == 0)
2998 if (StartupPID != 0)
2999 signal_child(StartupPID, SIGTERM);
3000 if (WalReceiverPID != 0)
3001 signal_child(WalReceiverPID, SIGTERM);
3002 pmState = PM_WAIT_BACKENDS;
3007 * If we are in a state-machine state that implies waiting for backends to
3008 * exit, see if they're all gone, and change state if so.
3010 if (pmState == PM_WAIT_BACKENDS)
3013 * PM_WAIT_BACKENDS state ends when we have no regular backends
3014 * (including autovac workers) and no walwriter, autovac launcher or
3015 * bgwriter. If we are doing crash recovery then we expect the
3016 * checkpointer to exit as well, otherwise not. The archiver, stats,
3017 * and syslogger processes are disregarded since they are not
3018 * connected to shared memory; we also disregard dead_end children
3019 * here. Walsenders are also disregarded, they will be terminated
3020 * later after writing the checkpoint record, like the archiver
3023 if (CountChildren(BACKEND_TYPE_NORMAL | BACKEND_TYPE_AUTOVAC) == 0 &&
3025 WalReceiverPID == 0 &&
3027 (CheckpointerPID == 0 || !FatalError) &&
3028 WalWriterPID == 0 &&
3034 * Start waiting for dead_end children to die. This state
3035 * change causes ServerLoop to stop creating new ones.
3037 pmState = PM_WAIT_DEAD_END;
3040 * We already SIGQUIT'd the archiver and stats processes, if
3041 * any, when we entered FatalError state.
3047 * If we get here, we are proceeding with normal shutdown. All
3048 * the regular children are gone, and it's time to tell the
3049 * checkpointer to do a shutdown checkpoint.
3051 Assert(Shutdown > NoShutdown);
3052 /* Start the checkpointer if not running */
3053 if (CheckpointerPID == 0)
3054 CheckpointerPID = StartCheckpointer();
3055 /* And tell it to shut down */
3056 if (CheckpointerPID != 0)
3058 signal_child(CheckpointerPID, SIGUSR2);
3059 pmState = PM_SHUTDOWN;
3064 * If we failed to fork a checkpointer, just shut down.
3065 * Any required cleanup will happen at next restart. We
3066 * set FatalError so that an "abnormal shutdown" message
3067 * gets logged when we exit.
3070 pmState = PM_WAIT_DEAD_END;
3072 /* Kill the walsenders, archiver and stats collector too */
3073 SignalChildren(SIGQUIT);
3075 signal_child(PgArchPID, SIGQUIT);
3077 signal_child(PgStatPID, SIGQUIT);
3083 if (pmState == PM_SHUTDOWN_2)
3086 * PM_SHUTDOWN_2 state ends when there's no other children than
3087 * dead_end children left. There shouldn't be any regular backends
3088 * left by now anyway; what we're really waiting for is walsenders and
3091 * Walreceiver should normally be dead by now, but not when a fast
3092 * shutdown is performed during recovery.
3094 if (PgArchPID == 0 && CountChildren(BACKEND_TYPE_ALL) == 0 &&
3095 WalReceiverPID == 0)
3097 pmState = PM_WAIT_DEAD_END;
3101 if (pmState == PM_WAIT_DEAD_END)
3104 * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
3105 * (ie, no dead_end children remain), and the archiver and stats
3106 * collector are gone too.
3108 * The reason we wait for those two is to protect them against a new
3109 * postmaster starting conflicting subprocesses; this isn't an
3110 * ironclad protection, but it at least helps in the
3111 * shutdown-and-immediately-restart scenario. Note that they have
3112 * already been sent appropriate shutdown signals, either during a
3113 * normal state transition leading up to PM_WAIT_DEAD_END, or during
3114 * FatalError processing.
3116 if (DLGetHead(BackendList) == NULL &&
3117 PgArchPID == 0 && PgStatPID == 0)
3119 /* These other guys should be dead already */
3120 Assert(StartupPID == 0);
3121 Assert(WalReceiverPID == 0);
3122 Assert(BgWriterPID == 0);
3123 Assert(CheckpointerPID == 0);
3124 Assert(WalWriterPID == 0);
3125 Assert(AutoVacPID == 0);
3126 /* syslogger is not considered here */
3127 pmState = PM_NO_CHILDREN;
3132 * If we've been told to shut down, we exit as soon as there are no
3133 * remaining children. If there was a crash, cleanup will occur at the
3134 * next startup. (Before PostgreSQL 8.3, we tried to recover from the
3135 * crash before exiting, but that seems unwise if we are quitting because
3136 * we got SIGTERM from init --- there may well not be time for recovery
3137 * before init decides to SIGKILL us.)
3139 * Note that the syslogger continues to run. It will exit when it sees
3140 * EOF on its input pipe, which happens when there are no more upstream
3143 if (Shutdown > NoShutdown && pmState == PM_NO_CHILDREN)
3147 ereport(LOG, (errmsg("abnormal database system shutdown")));
3153 * Terminate exclusive backup mode to avoid recovery after a clean
3154 * fast shutdown. Since an exclusive backup can only be taken
3155 * during normal running (and not, for example, while running
3156 * under Hot Standby) it only makes sense to do this if we reached
3157 * normal running. If we're still in recovery, the backup file is
3158 * one we're recovering *from*, and we must keep it around so that
3159 * recovery restarts from the right place.
3161 if (ReachedNormalRunning)
3164 /* Normal exit from the postmaster is here */
3170 * If recovery failed, or the user does not want an automatic restart
3171 * after backend crashes, wait for all non-syslogger children to exit, and
3172 * then exit postmaster. We don't try to reinitialize when recovery fails,
3173 * because more than likely it will just fail again and we will keep
3176 if (pmState == PM_NO_CHILDREN && (RecoveryError || !restart_after_crash))
3180 * If we need to recover from a crash, wait for all non-syslogger children
3181 * to exit, then reset shmem and StartupDataBase.
3183 if (FatalError && pmState == PM_NO_CHILDREN)
3186 (errmsg("all server processes terminated; reinitializing")));
3189 reset_shared(PostPortNumber);
3191 StartupPID = StartupDataBase();
3192 Assert(StartupPID != 0);
3193 pmState = PM_STARTUP;
3199 * Send a signal to a postmaster child process
3201 * On systems that have setsid(), each child process sets itself up as a
3202 * process group leader. For signals that are generally interpreted in the
3203 * appropriate fashion, we signal the entire process group not just the
3204 * direct child process. This allows us to, for example, SIGQUIT a blocked
3205 * archive_recovery script, or SIGINT a script being run by a backend via
3208 * There is a race condition for recently-forked children: they might not
3209 * have executed setsid() yet. So we signal the child directly as well as
3210 * the group. We assume such a child will handle the signal before trying
3211 * to spawn any grandchild processes. We also assume that signaling the
3212 * child twice will not cause any problems.
3215 signal_child(pid_t pid, int signal)
3217 if (kill(pid, signal) < 0)
3218 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
3226 if (kill(-pid, signal) < 0)
3227 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) (-pid), signal);
3236 * Send a signal to the targeted children (but NOT special children;
3237 * dead_end children are never signaled, either).
3240 SignalSomeChildren(int signal, int target)
3243 bool signaled = false;
3245 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
3247 Backend *bp = (Backend *) DLE_VAL(curr);
3253 * Since target == BACKEND_TYPE_ALL is the most common case, we test
3254 * it first and avoid touching shared memory for every child.
3256 if (target != BACKEND_TYPE_ALL)
3260 if (bp->is_autovacuum)
3261 child = BACKEND_TYPE_AUTOVAC;
3262 else if (IsPostmasterChildWalSender(bp->child_slot))
3263 child = BACKEND_TYPE_WALSND;
3265 child = BACKEND_TYPE_NORMAL;
3266 if (!(target & child))
3271 (errmsg_internal("sending signal %d to process %d",
3272 signal, (int) bp->pid)));
3273 signal_child(bp->pid, signal);
3280 * BackendStartup -- start backend process
3282 * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
3284 * Note: if you change this code, also consider StartAutovacuumWorker.
3287 BackendStartup(Port *port)
3289 Backend *bn; /* for backend cleanup */
3293 * Create backend data structure. Better before the fork() so we can
3294 * handle failure cleanly.
3296 bn = (Backend *) malloc(sizeof(Backend));
3300 (errcode(ERRCODE_OUT_OF_MEMORY),
3301 errmsg("out of memory")));
3302 return STATUS_ERROR;
3306 * Compute the cancel key that will be assigned to this backend. The
3307 * backend will have its own copy in the forked-off process' value of
3308 * MyCancelKey, so that it can transmit the key to the frontend.
3310 MyCancelKey = PostmasterRandom();
3311 bn->cancel_key = MyCancelKey;
3313 /* Pass down canAcceptConnections state */
3314 port->canAcceptConnections = canAcceptConnections();
3315 bn->dead_end = (port->canAcceptConnections != CAC_OK &&
3316 port->canAcceptConnections != CAC_WAITBACKUP);
3319 * Unless it's a dead_end child, assign it a child slot number
3322 bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
3327 pid = backend_forkexec(port);
3328 #else /* !EXEC_BACKEND */
3329 pid = fork_process();
3330 if (pid == 0) /* child */
3335 * Let's clean up ourselves as the postmaster child, and close the
3336 * postmaster's listen sockets. (In EXEC_BACKEND case this is all
3337 * done in SubPostmasterMain.)
3339 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
3341 MyProcPid = getpid(); /* reset MyProcPid */
3343 MyStartTime = time(NULL);
3345 /* We don't want the postmaster's proc_exit() handlers */
3348 /* Close the postmaster's sockets */
3349 ClosePostmasterPorts(false);
3351 /* Perform additional initialization and collect startup packet */
3352 BackendInitialize(port);
3354 /* And run the backend */
3357 #endif /* EXEC_BACKEND */
3361 /* in parent, fork failed */
3362 int save_errno = errno;
3365 (void) ReleasePostmasterChildSlot(bn->child_slot);
3369 (errmsg("could not fork new process for connection: %m")));
3370 report_fork_failure_to_client(port, save_errno);
3371 return STATUS_ERROR;
3374 /* in parent, successful fork */
3376 (errmsg_internal("forked new backend, pid=%d socket=%d",
3377 (int) pid, (int) port->sock)));
3380 * Everything's been successful, it's safe to add this backend to our list
3384 bn->is_autovacuum = false;
3385 DLInitElem(&bn->elem, bn);
3386 DLAddHead(BackendList, &bn->elem);
3389 ShmemBackendArrayAdd(bn);
3396 * Try to report backend fork() failure to client before we close the
3397 * connection. Since we do not care to risk blocking the postmaster on
3398 * this connection, we set the connection to non-blocking and try only once.
3400 * This is grungy special-purpose code; we cannot use backend libpq since
3401 * it's not up and running.
3404 report_fork_failure_to_client(Port *port, int errnum)
3409 /* Format the error message packet (always V2 protocol) */
3410 snprintf(buffer, sizeof(buffer), "E%s%s\n",
3411 _("could not fork new process for connection: "),
3414 /* Set port to non-blocking. Don't do send() if this fails */
3415 if (!pg_set_noblock(port->sock))
3418 /* We'll retry after EINTR, but ignore all other failures */
3421 rc = send(port->sock, buffer, strlen(buffer) + 1, 0);
3422 } while (rc < 0 && errno == EINTR);
3427 * BackendInitialize -- initialize an interactive (postmaster-child)
3428 * backend process, and collect the client's startup packet.
3430 * returns: nothing. Will not return at all if there's any failure.
3432 * Note: this code does not depend on having any access to shared memory.
3433 * In the EXEC_BACKEND case, we are physically attached to shared memory
3434 * but have not yet set up most of our local pointers to shmem structures.
3437 BackendInitialize(Port *port)
3440 char remote_host[NI_MAXHOST];
3441 char remote_port[NI_MAXSERV];
3442 char remote_ps_data[NI_MAXHOST];
3444 /* Save port etc. for ps status */
3448 * PreAuthDelay is a debugging aid for investigating problems in the
3449 * authentication cycle: it can be set in postgresql.conf to allow time to
3450 * attach to the newly-forked backend with a debugger. (See also
3451 * PostAuthDelay, which we allow clients to pass through PGOPTIONS, but it
3452 * is not honored until after authentication.)
3454 if (PreAuthDelay > 0)
3455 pg_usleep(PreAuthDelay * 1000000L);
3457 /* This flag will remain set until InitPostgres finishes authentication */
3458 ClientAuthInProgress = true; /* limit visibility of log messages */
3460 /* save process start time */
3461 port->SessionStartTime = GetCurrentTimestamp();
3462 MyStartTime = timestamptz_to_time_t(port->SessionStartTime);
3464 /* set these to empty in case they are needed before we set them up */
3465 port->remote_host = "";
3466 port->remote_port = "";
3469 * Initialize libpq and enable reporting of ereport errors to the client.
3470 * Must do this now because authentication uses libpq to send messages.
3472 pq_init(); /* initialize libpq to talk to client */
3473 whereToSendOutput = DestRemote; /* now safe to ereport to client */
3476 * If possible, make this process a group leader, so that the postmaster
3477 * can signal any child processes too. (We do this now on the off chance
3478 * that something might spawn a child process during authentication.)
3482 elog(FATAL, "setsid() failed: %m");
3486 * We arrange for a simple exit(1) if we receive SIGTERM or SIGQUIT or
3487 * timeout while trying to collect the startup packet. Otherwise the
3488 * postmaster cannot shutdown the database FAST or IMMED cleanly if a
3489 * buggy client fails to send the packet promptly.
3491 pqsignal(SIGTERM, startup_die);
3492 pqsignal(SIGQUIT, startup_die);
3493 InitializeTimeouts(); /* establishes SIGALRM handler */
3494 PG_SETMASK(&StartupBlockSig);
3497 * Get the remote host name and port for logging and status display.
3499 remote_host[0] = '\0';
3500 remote_port[0] = '\0';
3501 if (pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
3502 remote_host, sizeof(remote_host),
3503 remote_port, sizeof(remote_port),
3504 (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV) != 0)
3506 int ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
3507 remote_host, sizeof(remote_host),
3508 remote_port, sizeof(remote_port),
3509 NI_NUMERICHOST | NI_NUMERICSERV);
3513 (errmsg_internal("pg_getnameinfo_all() failed: %s",
3514 gai_strerror(ret))));
3516 if (remote_port[0] == '\0')
3517 snprintf(remote_ps_data, sizeof(remote_ps_data), "%s", remote_host);
3519 snprintf(remote_ps_data, sizeof(remote_ps_data), "%s(%s)", remote_host, remote_port);
3521 if (Log_connections)
3525 (errmsg("connection received: host=%s port=%s",
3530 (errmsg("connection received: host=%s",
3535 * save remote_host and remote_port in port structure
3537 port->remote_host = strdup(remote_host);
3538 port->remote_port = strdup(remote_port);
3540 port->remote_hostname = port->remote_host;
3543 * Ready to begin client interaction. We will give up and exit(1) after a
3544 * time delay, so that a broken client can't hog a connection
3545 * indefinitely. PreAuthDelay and any DNS interactions above don't count
3546 * against the time limit.
3548 * Note: AuthenticationTimeout is applied here while waiting for the
3549 * startup packet, and then again in InitPostgres for the duration of any
3550 * authentication operations. So a hostile client could tie up the
3551 * process for nearly twice AuthenticationTimeout before we kick him off.
3553 * Note: because PostgresMain will call InitializeTimeouts again, the
3554 * registration of STARTUP_PACKET_TIMEOUT will be lost. This is okay
3555 * since we never use it again after this function.
3557 RegisterTimeout(STARTUP_PACKET_TIMEOUT, StartupPacketTimeoutHandler);
3558 enable_timeout_after(STARTUP_PACKET_TIMEOUT, AuthenticationTimeout * 1000);
3561 * Receive the startup packet (which might turn out to be a cancel request
3564 status = ProcessStartupPacket(port, false);
3567 * Stop here if it was bad or a cancel packet. ProcessStartupPacket
3568 * already did any appropriate error reporting.
3570 if (status != STATUS_OK)
3574 * Now that we have the user and database name, we can set the process
3575 * title for ps. It's good to do this as early as possible in startup.
3577 * For a walsender, the ps display is set in the following form:
3579 * postgres: wal sender process <user> <host> <activity>
3581 * To achieve that, we pass "wal sender process" as username and username
3582 * as dbname to init_ps_display(). XXX: should add a new variant of
3583 * init_ps_display() to avoid abusing the parameters like this.
3586 init_ps_display("wal sender process", port->user_name, remote_ps_data,
3587 update_process_title ? "authentication" : "");
3589 init_ps_display(port->user_name, port->database_name, remote_ps_data,
3590 update_process_title ? "authentication" : "");
3593 * Disable the timeout, and prevent SIGTERM/SIGQUIT again.
3595 disable_timeout(STARTUP_PACKET_TIMEOUT, false);
3596 PG_SETMASK(&BlockSig);
3601 * BackendRun -- set up the backend's argument list and invoke PostgresMain()
3604 * Shouldn't return at all.
3605 * If PostgresMain() fails, return status.
3608 BackendRun(Port *port)
3618 * Don't want backend to be able to see the postmaster random number
3619 * generator state. We have to clobber the static random_seed *and* start
3620 * a new random sequence in the random() library function.
3623 random_start_time.tv_usec = 0;
3624 /* slightly hacky way to get integer microseconds part of timestamptz */
3625 TimestampDifference(0, port->SessionStartTime, &secs, &usecs);
3626 srandom((unsigned int) (MyProcPid ^ usecs));
3629 * Now, build the argv vector that will be given to PostgresMain.
3631 * The maximum possible number of commandline arguments that could come
3632 * from ExtraOptions is (strlen(ExtraOptions) + 1) / 2; see
3635 maxac = 5; /* for fixed args supplied below */
3636 maxac += (strlen(ExtraOptions) + 1) / 2;
3638 av = (char **) MemoryContextAlloc(TopMemoryContext,
3639 maxac * sizeof(char *));
3642 av[ac++] = "postgres";
3645 * Pass any backend switches specified with -o on the postmaster's own
3646 * command line. We assume these are secure. (It's OK to mangle
3647 * ExtraOptions now, since we're safely inside a subprocess.)
3649 pg_split_opts(av, &ac, ExtraOptions);
3652 * Tell the backend which database to use.
3654 av[ac++] = port->database_name;
3661 * Debug: print arguments being passed to backend
3664 (errmsg_internal("%s child[%d]: starting with (",
3665 progname, (int) getpid())));
3666 for (i = 0; i < ac; ++i)
3668 (errmsg_internal("\t%s", av[i])));
3670 (errmsg_internal(")")));
3673 * Make sure we aren't in PostmasterContext anymore. (We can't delete it
3674 * just yet, though, because InitPostgres will need the HBA data.)
3676 MemoryContextSwitchTo(TopMemoryContext);
3678 PostgresMain(ac, av, port->user_name);
3685 * postmaster_forkexec -- fork and exec a postmaster subprocess
3687 * The caller must have set up the argv array already, except for argv[2]
3688 * which will be filled with the name of the temp variable file.
3690 * Returns the child process PID, or -1 on fork failure (a suitable error
3691 * message has been logged on failure).
3693 * All uses of this routine will dispatch to SubPostmasterMain in the
3697 postmaster_forkexec(int argc, char *argv[])
3701 /* This entry point passes dummy values for the Port variables */
3702 memset(&port, 0, sizeof(port));
3703 return internal_forkexec(argc, argv, &port);
3707 * backend_forkexec -- fork/exec off a backend process
3709 * Some operating systems (WIN32) don't have fork() so we have to simulate
3710 * it by storing parameters that need to be passed to the child and
3711 * then create a new child process.
3713 * returns the pid of the fork/exec'd process, or -1 on failure
3716 backend_forkexec(Port *port)
3721 av[ac++] = "postgres";
3722 av[ac++] = "--forkbackend";
3723 av[ac++] = NULL; /* filled in by internal_forkexec */
3726 Assert(ac < lengthof(av));
3728 return internal_forkexec(ac, av, port);
3734 * internal_forkexec non-win32 implementation
3736 * - writes out backend variables to the parameter file
3737 * - fork():s, and then exec():s the child process
3740 internal_forkexec(int argc, char *argv[], Port *port)
3742 static unsigned long tmpBackendFileNum = 0;
3744 char tmpfilename[MAXPGPATH];
3745 BackendParameters param;
3748 if (!save_backend_variables(¶m, port))
3749 return -1; /* log made by save_backend_variables */
3751 /* Calculate name for temp file */
3752 snprintf(tmpfilename, MAXPGPATH, "%s/%s.backend_var.%d.%lu",
3753 PG_TEMP_FILES_DIR, PG_TEMP_FILE_PREFIX,
3754 MyProcPid, ++tmpBackendFileNum);
3757 fp = AllocateFile(tmpfilename, PG_BINARY_W);
3760 /* As in OpenTemporaryFile, try to make the temp-file directory */
3761 mkdir(PG_TEMP_FILES_DIR, S_IRWXU);
3763 fp = AllocateFile(tmpfilename, PG_BINARY_W);
3767 (errcode_for_file_access(),
3768 errmsg("could not create file \"%s\": %m",
3774 if (fwrite(¶m, sizeof(param), 1, fp) != 1)
3777 (errcode_for_file_access(),
3778 errmsg("could not write to file \"%s\": %m", tmpfilename)));
3787 (errcode_for_file_access(),
3788 errmsg("could not write to file \"%s\": %m", tmpfilename)));
3792 /* Make sure caller set up argv properly */
3794 Assert(argv[argc] == NULL);
3795 Assert(strncmp(argv[1], "--fork", 6) == 0);
3796 Assert(argv[2] == NULL);
3798 /* Insert temp file name after --fork argument */
3799 argv[2] = tmpfilename;
3801 /* Fire off execv in child */
3802 if ((pid = fork_process()) == 0)
3804 if (execv(postgres_exec_path, argv) < 0)
3807 (errmsg("could not execute server process \"%s\": %m",
3808 postgres_exec_path)));
3809 /* We're already in the child process here, can't return */
3814 return pid; /* Parent returns pid, or -1 on fork failure */
3819 * internal_forkexec win32 implementation
3821 * - starts backend using CreateProcess(), in suspended state
3822 * - writes out backend variables to the parameter file
3823 * - during this, duplicates handles and sockets required for
3824 * inheritance into the new process
3825 * - resumes execution of the new process once the backend parameter
3829 internal_forkexec(int argc, char *argv[], Port *port)
3832 PROCESS_INFORMATION pi;
3835 char cmdLine[MAXPGPATH * 2];
3837 BackendParameters *param;
3838 SECURITY_ATTRIBUTES sa;
3839 char paramHandleStr[32];
3840 win32_deadchild_waitinfo *childinfo;
3842 /* Make sure caller set up argv properly */
3844 Assert(argv[argc] == NULL);
3845 Assert(strncmp(argv[1], "--fork", 6) == 0);
3846 Assert(argv[2] == NULL);
3848 /* Set up shared memory for parameter passing */
3849 ZeroMemory(&sa, sizeof(sa));
3850 sa.nLength = sizeof(sa);
3851 sa.bInheritHandle = TRUE;
3852 paramHandle = CreateFileMapping(INVALID_HANDLE_VALUE,
3856 sizeof(BackendParameters),
3858 if (paramHandle == INVALID_HANDLE_VALUE)
3860 elog(LOG, "could not create backend parameter file mapping: error code %lu",
3865 param = MapViewOfFile(paramHandle, FILE_MAP_WRITE, 0, 0, sizeof(BackendParameters));
3868 elog(LOG, "could not map backend parameter memory: error code %lu",
3870 CloseHandle(paramHandle);
3874 /* Insert temp file name after --fork argument */
3876 sprintf(paramHandleStr, "%llu", (LONG_PTR) paramHandle);
3878 sprintf(paramHandleStr, "%lu", (DWORD) paramHandle);
3880 argv[2] = paramHandleStr;
3882 /* Format the cmd line */
3883 cmdLine[sizeof(cmdLine) - 1] = '\0';
3884 cmdLine[sizeof(cmdLine) - 2] = '\0';
3885 snprintf(cmdLine, sizeof(cmdLine) - 1, "\"%s\"", postgres_exec_path);
3887 while (argv[++i] != NULL)
3889 j = strlen(cmdLine);
3890 snprintf(cmdLine + j, sizeof(cmdLine) - 1 - j, " \"%s\"", argv[i]);
3892 if (cmdLine[sizeof(cmdLine) - 2] != '\0')
3894 elog(LOG, "subprocess command line too long");
3898 memset(&pi, 0, sizeof(pi));
3899 memset(&si, 0, sizeof(si));
3903 * Create the subprocess in a suspended state. This will be resumed later,
3904 * once we have written out the parameter file.
3906 if (!CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, CREATE_SUSPENDED,
3907 NULL, NULL, &si, &pi))
3909 elog(LOG, "CreateProcess call failed: %m (error code %lu)",
3914 if (!save_backend_variables(param, port, pi.hProcess, pi.dwProcessId))
3917 * log made by save_backend_variables, but we have to clean up the
3918 * mess with the half-started process
3920 if (!TerminateProcess(pi.hProcess, 255))
3922 (errmsg_internal("could not terminate unstarted process: error code %lu",
3924 CloseHandle(pi.hProcess);
3925 CloseHandle(pi.hThread);
3926 return -1; /* log made by save_backend_variables */
3929 /* Drop the parameter shared memory that is now inherited to the backend */
3930 if (!UnmapViewOfFile(param))
3931 elog(LOG, "could not unmap view of backend parameter file: error code %lu",
3933 if (!CloseHandle(paramHandle))
3934 elog(LOG, "could not close handle to backend parameter file: error code %lu",
3938 * Reserve the memory region used by our main shared memory segment before
3939 * we resume the child process.
3941 if (!pgwin32_ReserveSharedMemoryRegion(pi.hProcess))
3944 * Failed to reserve the memory, so terminate the newly created
3945 * process and give up.
3947 if (!TerminateProcess(pi.hProcess, 255))
3949 (errmsg_internal("could not terminate process that failed to reserve memory: error code %lu",
3951 CloseHandle(pi.hProcess);
3952 CloseHandle(pi.hThread);
3953 return -1; /* logging done made by
3954 * pgwin32_ReserveSharedMemoryRegion() */
3958 * Now that the backend variables are written out, we start the child
3959 * thread so it can start initializing while we set up the rest of the
3962 if (ResumeThread(pi.hThread) == -1)
3964 if (!TerminateProcess(pi.hProcess, 255))
3967 (errmsg_internal("could not terminate unstartable process: error code %lu",
3969 CloseHandle(pi.hProcess);
3970 CloseHandle(pi.hThread);
3973 CloseHandle(pi.hProcess);
3974 CloseHandle(pi.hThread);
3976 (errmsg_internal("could not resume thread of unstarted process: error code %lu",
3982 * Queue a waiter for to signal when this child dies. The wait will be
3983 * handled automatically by an operating system thread pool.
3985 * Note: use malloc instead of palloc, since it needs to be thread-safe.
3986 * Struct will be free():d from the callback function that runs on a
3989 childinfo = malloc(sizeof(win32_deadchild_waitinfo));
3992 (errcode(ERRCODE_OUT_OF_MEMORY),
3993 errmsg("out of memory")));
3995 childinfo->procHandle = pi.hProcess;
3996 childinfo->procId = pi.dwProcessId;
3998 if (!RegisterWaitForSingleObject(&childinfo->waitHandle,
4000 pgwin32_deadchild_callback,
4003 WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD))
4005 (errmsg_internal("could not register process for wait: error code %lu",
4008 /* Don't close pi.hProcess here - the wait thread needs access to it */
4010 CloseHandle(pi.hThread);
4012 return pi.dwProcessId;
4018 * SubPostmasterMain -- Get the fork/exec'd process into a state equivalent
4019 * to what it would be if we'd simply forked on Unix, and then
4020 * dispatch to the appropriate place.
4022 * The first two command line arguments are expected to be "--forkFOO"
4023 * (where FOO indicates which postmaster child we are to become), and
4024 * the name of a variables file that we can read to load data that would
4025 * have been inherited by fork() on Unix. Remaining arguments go to the
4026 * subprocess FooMain() routine.
4029 SubPostmasterMain(int argc, char *argv[])
4033 /* Do this sooner rather than later... */
4034 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
4036 MyProcPid = getpid(); /* reset MyProcPid */
4038 MyStartTime = time(NULL);
4041 * make sure stderr is in binary mode before anything can possibly be
4042 * written to it, in case it's actually the syslogger pipe, so the pipe
4043 * chunking protocol isn't disturbed. Non-logpipe data gets translated on
4044 * redirection (e.g. via pg_ctl -l) anyway.
4047 _setmode(fileno(stderr), _O_BINARY);
4050 /* Lose the postmaster's on-exit routines (really a no-op) */
4053 /* In EXEC_BACKEND case we will not have inherited these settings */
4054 IsPostmasterEnvironment = true;
4055 whereToSendOutput = DestNone;
4057 /* Setup essential subsystems (to ensure elog() behaves sanely) */
4058 MemoryContextInit();
4059 InitializeGUCOptions();
4061 /* Read in the variables file */
4062 memset(&port, 0, sizeof(Port));
4063 read_backend_variables(argv[2], &port);
4066 * Set reference point for stack-depth checking
4071 * Set up memory area for GSS information. Mirrors the code in ConnCreate
4072 * for the non-exec case.
4074 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
4075 port.gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
4078 (errcode(ERRCODE_OUT_OF_MEMORY),
4079 errmsg("out of memory")));
4082 /* Check we got appropriate args */
4084 elog(FATAL, "invalid subpostmaster invocation");
4087 * If appropriate, physically re-attach to shared memory segment. We want
4088 * to do this before going any further to ensure that we can attach at the
4089 * same address the postmaster used.
4091 if (strcmp(argv[1], "--forkbackend") == 0 ||
4092 strcmp(argv[1], "--forkavlauncher") == 0 ||
4093 strcmp(argv[1], "--forkavworker") == 0 ||
4094 strcmp(argv[1], "--forkboot") == 0)
4095 PGSharedMemoryReAttach();
4097 /* autovacuum needs this set before calling InitProcess */
4098 if (strcmp(argv[1], "--forkavlauncher") == 0)
4099 AutovacuumLauncherIAm();
4100 if (strcmp(argv[1], "--forkavworker") == 0)
4101 AutovacuumWorkerIAm();
4104 * Start our win32 signal implementation. This has to be done after we
4105 * read the backend variables, because we need to pick up the signal pipe
4106 * from the parent process.
4109 pgwin32_signal_initialize();
4112 /* In EXEC_BACKEND case we will not have inherited these settings */
4114 PG_SETMASK(&BlockSig);
4116 /* Read in remaining GUC variables */
4117 read_nondefault_variables();
4120 * Reload any libraries that were preloaded by the postmaster. Since we
4121 * exec'd this process, those libraries didn't come along with us; but we
4122 * should load them into all child processes to be consistent with the
4123 * non-EXEC_BACKEND behavior.
4125 process_shared_preload_libraries();
4127 /* Run backend or appropriate child */
4128 if (strcmp(argv[1], "--forkbackend") == 0)
4130 Assert(argc == 3); /* shouldn't be any more args */
4132 /* Close the postmaster's sockets */
4133 ClosePostmasterPorts(false);
4136 * Need to reinitialize the SSL library in the backend, since the
4137 * context structures contain function pointers and cannot be passed
4138 * through the parameter file.
4140 * XXX should we do this in all child processes? For the moment it's
4141 * enough to do it in backend children.
4145 secure_initialize();
4149 * Perform additional initialization and collect startup packet.
4151 * We want to do this before InitProcess() for a couple of reasons: 1.
4152 * so that we aren't eating up a PGPROC slot while waiting on the
4153 * client. 2. so that if InitProcess() fails due to being out of
4154 * PGPROC slots, we have already initialized libpq and are able to
4155 * report the error to the client.
4157 BackendInitialize(&port);
4159 /* Restore basic shared memory pointers */
4160 InitShmemAccess(UsedShmemSegAddr);
4162 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
4166 * Attach process to shared data structures. If testing EXEC_BACKEND
4167 * on Linux, you must run this as root before starting the postmaster:
4169 * echo 0 >/proc/sys/kernel/randomize_va_space
4171 * This prevents a randomized stack base address that causes child
4172 * shared memory to be at a different address than the parent, making
4173 * it impossible to attached to shared memory. Return the value to
4174 * '1' when finished.
4176 CreateSharedMemoryAndSemaphores(false, 0);
4178 /* And run the backend */
4179 BackendRun(&port); /* does not return */
4181 if (strcmp(argv[1], "--forkboot") == 0)
4183 /* Close the postmaster's sockets */
4184 ClosePostmasterPorts(false);
4186 /* Restore basic shared memory pointers */
4187 InitShmemAccess(UsedShmemSegAddr);
4189 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
4190 InitAuxiliaryProcess();
4192 /* Attach process to shared data structures */
4193 CreateSharedMemoryAndSemaphores(false, 0);
4195 AuxiliaryProcessMain(argc - 2, argv + 2); /* does not return */
4197 if (strcmp(argv[1], "--forkavlauncher") == 0)
4199 /* Close the postmaster's sockets */
4200 ClosePostmasterPorts(false);
4202 /* Restore basic shared memory pointers */
4203 InitShmemAccess(UsedShmemSegAddr);
4205 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
4208 /* Attach process to shared data structures */
4209 CreateSharedMemoryAndSemaphores(false, 0);
4211 AutoVacLauncherMain(argc - 2, argv + 2); /* does not return */
4213 if (strcmp(argv[1], "--forkavworker") == 0)
4215 /* Close the postmaster's sockets */
4216 ClosePostmasterPorts(false);
4218 /* Restore basic shared memory pointers */
4219 InitShmemAccess(UsedShmemSegAddr);
4221 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
4224 /* Attach process to shared data structures */
4225 CreateSharedMemoryAndSemaphores(false, 0);
4227 AutoVacWorkerMain(argc - 2, argv + 2); /* does not return */
4229 if (strcmp(argv[1], "--forkarch") == 0)
4231 /* Close the postmaster's sockets */
4232 ClosePostmasterPorts(false);
4234 /* Do not want to attach to shared memory */
4236 PgArchiverMain(argc, argv); /* does not return */
4238 if (strcmp(argv[1], "--forkcol") == 0)
4240 /* Close the postmaster's sockets */
4241 ClosePostmasterPorts(false);
4243 /* Do not want to attach to shared memory */
4245 PgstatCollectorMain(argc, argv); /* does not return */
4247 if (strcmp(argv[1], "--forklog") == 0)
4249 /* Close the postmaster's sockets */
4250 ClosePostmasterPorts(true);
4252 /* Do not want to attach to shared memory */
4254 SysLoggerMain(argc, argv); /* does not return */
4257 abort(); /* shouldn't get here */
4259 #endif /* EXEC_BACKEND */
4263 * ExitPostmaster -- cleanup
4265 * Do NOT call exit() directly --- always go through here!
4268 ExitPostmaster(int status)
4270 /* should cleanup shared memory and kill all backends */
4273 * Not sure of the semantics here. When the Postmaster dies, should the
4274 * backends all be killed? probably not.
4276 * MUST -- vadim 05-10-1999
4283 * sigusr1_handler - handle signal conditions from child processes
4286 sigusr1_handler(SIGNAL_ARGS)
4288 int save_errno = errno;
4290 PG_SETMASK(&BlockSig);
4293 * RECOVERY_STARTED and BEGIN_HOT_STANDBY signals are ignored in
4294 * unexpected states. If the startup process quickly starts up, completes
4295 * recovery, exits, we might process the death of the startup process
4296 * first. We don't want to go back to recovery in that case.
4298 if (CheckPostmasterSignal(PMSIGNAL_RECOVERY_STARTED) &&
4299 pmState == PM_STARTUP)
4301 /* WAL redo has started. We're out of reinitialization. */
4305 * Crank up the background tasks. It doesn't matter if this fails,
4306 * we'll just try again later.
4308 Assert(CheckpointerPID == 0);
4309 CheckpointerPID = StartCheckpointer();
4310 Assert(BgWriterPID == 0);
4311 BgWriterPID = StartBackgroundWriter();
4313 pmState = PM_RECOVERY;
4315 if (CheckPostmasterSignal(PMSIGNAL_BEGIN_HOT_STANDBY) &&
4316 pmState == PM_RECOVERY)
4319 * Likewise, start other special children as needed.
4321 Assert(PgStatPID == 0);
4322 PgStatPID = pgstat_start();
4325 (errmsg("database system is ready to accept read only connections")));
4327 pmState = PM_HOT_STANDBY;
4330 if (CheckPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER) &&
4334 * Send SIGUSR1 to archiver process, to wake it up and begin archiving
4335 * next transaction log file.
4337 signal_child(PgArchPID, SIGUSR1);
4340 if (CheckPostmasterSignal(PMSIGNAL_ROTATE_LOGFILE) &&
4343 /* Tell syslogger to rotate logfile */
4344 signal_child(SysLoggerPID, SIGUSR1);
4347 if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER))
4350 * Start one iteration of the autovacuum daemon, even if autovacuuming
4351 * is nominally not enabled. This is so we can have an active defense
4352 * against transaction ID wraparound. We set a flag for the main loop
4353 * to do it rather than trying to do it here --- this is because the
4354 * autovac process itself may send the signal, and we want to handle
4355 * that by launching another iteration as soon as the current one
4358 start_autovac_launcher = true;
4361 if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER))
4363 /* The autovacuum launcher wants us to start a worker process. */
4364 StartAutovacuumWorker();
4367 if (CheckPostmasterSignal(PMSIGNAL_START_WALRECEIVER) &&
4368 WalReceiverPID == 0 &&
4369 (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
4370 pmState == PM_HOT_STANDBY || pmState == PM_WAIT_READONLY))
4372 /* Startup Process wants us to start the walreceiver process. */
4373 WalReceiverPID = StartWalReceiver();
4376 if (CheckPostmasterSignal(PMSIGNAL_ADVANCE_STATE_MACHINE) &&
4377 (pmState == PM_WAIT_BACKUP || pmState == PM_WAIT_BACKENDS))
4379 /* Advance postmaster's state machine */
4380 PostmasterStateMachine();
4383 if (CheckPromoteSignal() && StartupPID != 0 &&
4384 (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
4385 pmState == PM_HOT_STANDBY || pmState == PM_WAIT_READONLY))
4387 /* Tell startup process to finish recovery */
4388 signal_child(StartupPID, SIGUSR2);
4391 PG_SETMASK(&UnBlockSig);
4397 * SIGTERM or SIGQUIT while processing startup packet.
4398 * Clean up and exit(1).
4400 * XXX: possible future improvement: try to send a message indicating
4401 * why we are disconnecting. Problem is to be sure we don't block while
4402 * doing so, nor mess up SSL initialization. In practice, if the client
4403 * has wedged here, it probably couldn't do anything with the message anyway.
4406 startup_die(SIGNAL_ARGS)
4412 * Dummy signal handler
4414 * We use this for signals that we don't actually use in the postmaster,
4415 * but we do use in backends. If we were to SIG_IGN such signals in the
4416 * postmaster, then a newly started backend might drop a signal that arrives
4417 * before it's able to reconfigure its signal processing. (See notes in
4421 dummy_handler(SIGNAL_ARGS)
4426 * Timeout while processing startup packet.
4427 * As for startup_die(), we clean up and exit(1).
4430 StartupPacketTimeoutHandler(void)
4440 RandomSalt(char *md5Salt)
4445 * We use % 255, sacrificing one possible byte value, so as to ensure that
4446 * all bits of the random() value participate in the result. While at it,
4447 * add one to avoid generating any null bytes.
4449 rand = PostmasterRandom();
4450 md5Salt[0] = (rand % 255) + 1;
4451 rand = PostmasterRandom();
4452 md5Salt[1] = (rand % 255) + 1;
4453 rand = PostmasterRandom();
4454 md5Salt[2] = (rand % 255) + 1;
4455 rand = PostmasterRandom();
4456 md5Salt[3] = (rand % 255) + 1;
4463 PostmasterRandom(void)
4466 * Select a random seed at the time of first receiving a request.
4468 if (random_seed == 0)
4472 struct timeval random_stop_time;
4474 gettimeofday(&random_stop_time, NULL);
4477 * We are not sure how much precision is in tv_usec, so we swap
4478 * the high and low 16 bits of 'random_stop_time' and XOR them
4479 * with 'random_start_time'. On the off chance that the result is
4480 * 0, we loop until it isn't.
4482 random_seed = random_start_time.tv_usec ^
4483 ((random_stop_time.tv_usec << 16) |
4484 ((random_stop_time.tv_usec >> 16) & 0xffff));
4486 while (random_seed == 0);
4488 srandom(random_seed);
4495 * Count up number of child processes of specified types (dead_end chidren
4496 * are always excluded).
4499 CountChildren(int target)
4504 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
4506 Backend *bp = (Backend *) DLE_VAL(curr);
4512 * Since target == BACKEND_TYPE_ALL is the most common case, we test
4513 * it first and avoid touching shared memory for every child.
4515 if (target != BACKEND_TYPE_ALL)
4519 if (bp->is_autovacuum)
4520 child = BACKEND_TYPE_AUTOVAC;
4521 else if (IsPostmasterChildWalSender(bp->child_slot))
4522 child = BACKEND_TYPE_WALSND;
4524 child = BACKEND_TYPE_NORMAL;
4525 if (!(target & child))
4536 * StartChildProcess -- start an auxiliary process for the postmaster
4538 * xlop determines what kind of child will be started. All child types
4539 * initially go to AuxiliaryProcessMain, which will handle common setup.
4541 * Return value of StartChildProcess is subprocess' PID, or 0 if failed
4542 * to start subprocess.
4545 StartChildProcess(AuxProcType type)
4553 * Set up command-line arguments for subprocess
4555 av[ac++] = "postgres";
4558 av[ac++] = "--forkboot";
4559 av[ac++] = NULL; /* filled in by postmaster_forkexec */
4562 snprintf(typebuf, sizeof(typebuf), "-x%d", type);
4566 Assert(ac < lengthof(av));
4569 pid = postmaster_forkexec(ac, av);
4570 #else /* !EXEC_BACKEND */
4571 pid = fork_process();
4573 if (pid == 0) /* child */
4575 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
4577 /* Close the postmaster's sockets */
4578 ClosePostmasterPorts(false);
4580 /* Lose the postmaster's on-exit routines and port connections */
4583 /* Release postmaster's working memory context */
4584 MemoryContextSwitchTo(TopMemoryContext);
4585 MemoryContextDelete(PostmasterContext);
4586 PostmasterContext = NULL;
4588 AuxiliaryProcessMain(ac, av);
4591 #endif /* EXEC_BACKEND */
4595 /* in parent, fork failed */
4596 int save_errno = errno;
4601 case StartupProcess:
4603 (errmsg("could not fork startup process: %m")));
4605 case BgWriterProcess:
4607 (errmsg("could not fork background writer process: %m")));
4609 case CheckpointerProcess:
4611 (errmsg("could not fork checkpointer process: %m")));
4613 case WalWriterProcess:
4615 (errmsg("could not fork WAL writer process: %m")));
4617 case WalReceiverProcess:
4619 (errmsg("could not fork WAL receiver process: %m")));
4623 (errmsg("could not fork process: %m")));
4628 * fork failure is fatal during startup, but there's no need to choke
4629 * immediately if starting other child types fails.
4631 if (type == StartupProcess)
4637 * in parent, successful fork
4643 * StartAutovacuumWorker
4644 * Start an autovac worker process.
4646 * This function is here because it enters the resulting PID into the
4647 * postmaster's private backends list.
4649 * NB -- this code very roughly matches BackendStartup.
4652 StartAutovacuumWorker(void)
4657 * If not in condition to run a process, don't try, but handle it like a
4658 * fork failure. This does not normally happen, since the signal is only
4659 * supposed to be sent by autovacuum launcher when it's OK to do it, but
4660 * we have to check to avoid race-condition problems during DB state
4663 if (canAcceptConnections() == CAC_OK)
4665 bn = (Backend *) malloc(sizeof(Backend));
4669 * Compute the cancel key that will be assigned to this session.
4670 * We probably don't need cancel keys for autovac workers, but
4671 * we'd better have something random in the field to prevent
4672 * unfriendly people from sending cancels to them.
4674 MyCancelKey = PostmasterRandom();
4675 bn->cancel_key = MyCancelKey;
4677 /* Autovac workers are not dead_end and need a child slot */
4678 bn->dead_end = false;
4679 bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
4681 bn->pid = StartAutoVacWorker();
4684 bn->is_autovacuum = true;
4685 DLInitElem(&bn->elem, bn);
4686 DLAddHead(BackendList, &bn->elem);
4688 ShmemBackendArrayAdd(bn);
4695 * fork failed, fall through to report -- actual error message was
4696 * logged by StartAutoVacWorker
4698 (void) ReleasePostmasterChildSlot(bn->child_slot);
4703 (errcode(ERRCODE_OUT_OF_MEMORY),
4704 errmsg("out of memory")));
4708 * Report the failure to the launcher, if it's running. (If it's not, we
4709 * might not even be connected to shared memory, so don't try to call
4710 * AutoVacWorkerFailed.) Note that we also need to signal it so that it
4711 * responds to the condition, but we don't do that here, instead waiting
4712 * for ServerLoop to do it. This way we avoid a ping-pong signalling in
4713 * quick succession between the autovac launcher and postmaster in case
4716 if (AutoVacPID != 0)
4718 AutoVacWorkerFailed();
4719 avlauncher_needs_signal = true;
4724 * Create the opts file
4727 CreateOptsFile(int argc, char *argv[], char *fullprogname)
4732 #define OPTS_FILE "postmaster.opts"
4734 if ((fp = fopen(OPTS_FILE, "w")) == NULL)
4736 elog(LOG, "could not create file \"%s\": %m", OPTS_FILE);
4740 fprintf(fp, "%s", fullprogname);
4741 for (i = 1; i < argc; i++)
4742 fprintf(fp, " \"%s\"", argv[i]);
4747 elog(LOG, "could not write file \"%s\": %m", OPTS_FILE);
4756 * MaxLivePostmasterChildren
4758 * This reports the number of entries needed in per-child-process arrays
4759 * (the PMChildFlags array, and if EXEC_BACKEND the ShmemBackendArray).
4760 * These arrays include regular backends, autovac workers and walsenders,
4761 * but not special children nor dead_end children. This allows the arrays
4762 * to have a fixed maximum size, to wit the same too-many-children limit
4763 * enforced by canAcceptConnections(). The exact value isn't too critical
4764 * as long as it's more than MaxBackends.
4767 MaxLivePostmasterChildren(void)
4769 return 2 * MaxBackends;
4776 * The following need to be available to the save/restore_backend_variables
4777 * functions. They are marked NON_EXEC_STATIC in their home modules.
4779 extern slock_t *ShmemLock;
4780 extern LWLock *LWLockArray;
4781 extern slock_t *ProcStructLock;
4782 extern PGPROC *AuxiliaryProcs;
4783 extern PMSignalData *PMSignalState;
4784 extern pgsocket pgStatSock;
4785 extern pg_time_t first_syslogger_file_time;
4788 #define write_inheritable_socket(dest, src, childpid) ((*(dest) = (src)), true)
4789 #define read_inheritable_socket(dest, src) (*(dest) = *(src))
4791 static bool write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE child);
4792 static bool write_inheritable_socket(InheritableSocket *dest, SOCKET src,
4794 static void read_inheritable_socket(SOCKET *dest, InheritableSocket *src);
4798 /* Save critical backend variables into the BackendParameters struct */
4801 save_backend_variables(BackendParameters *param, Port *port)
4804 save_backend_variables(BackendParameters *param, Port *port,
4805 HANDLE childProcess, pid_t childPid)
4808 memcpy(¶m->port, port, sizeof(Port));
4809 if (!write_inheritable_socket(¶m->portsocket, port->sock, childPid))
4812 strlcpy(param->DataDir, DataDir, MAXPGPATH);
4814 memcpy(¶m->ListenSocket, &ListenSocket, sizeof(ListenSocket));
4816 param->MyCancelKey = MyCancelKey;
4817 param->MyPMChildSlot = MyPMChildSlot;
4819 param->UsedShmemSegID = UsedShmemSegID;
4820 param->UsedShmemSegAddr = UsedShmemSegAddr;
4822 param->ShmemLock = ShmemLock;
4823 param->ShmemVariableCache = ShmemVariableCache;
4824 param->ShmemBackendArray = ShmemBackendArray;
4826 param->LWLockArray = LWLockArray;
4827 param->ProcStructLock = ProcStructLock;
4828 param->ProcGlobal = ProcGlobal;
4829 param->AuxiliaryProcs = AuxiliaryProcs;
4830 param->PreparedXactProcs = PreparedXactProcs;
4831 param->PMSignalState = PMSignalState;
4832 if (!write_inheritable_socket(¶m->pgStatSock, pgStatSock, childPid))
4835 param->PostmasterPid = PostmasterPid;
4836 param->PgStartTime = PgStartTime;
4837 param->PgReloadTime = PgReloadTime;
4838 param->first_syslogger_file_time = first_syslogger_file_time;
4840 param->redirection_done = redirection_done;
4841 param->IsBinaryUpgrade = IsBinaryUpgrade;
4842 param->max_safe_fds = max_safe_fds;
4845 param->PostmasterHandle = PostmasterHandle;
4846 if (!write_duplicated_handle(¶m->initial_signal_pipe,
4847 pgwin32_create_signal_listener(childPid),
4851 memcpy(¶m->postmaster_alive_fds, &postmaster_alive_fds,
4852 sizeof(postmaster_alive_fds));
4855 memcpy(¶m->syslogPipe, &syslogPipe, sizeof(syslogPipe));
4857 strlcpy(param->my_exec_path, my_exec_path, MAXPGPATH);
4859 strlcpy(param->pkglib_path, pkglib_path, MAXPGPATH);
4861 strlcpy(param->ExtraOptions, ExtraOptions, MAXPGPATH);
4869 * Duplicate a handle for usage in a child process, and write the child
4870 * process instance of the handle to the parameter file.
4873 write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE childProcess)
4875 HANDLE hChild = INVALID_HANDLE_VALUE;
4877 if (!DuplicateHandle(GetCurrentProcess(),
4883 DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS))
4886 (errmsg_internal("could not duplicate handle to be written to backend parameter file: error code %lu",
4896 * Duplicate a socket for usage in a child process, and write the resulting
4897 * structure to the parameter file.
4898 * This is required because a number of LSPs (Layered Service Providers) very
4899 * common on Windows (antivirus, firewalls, download managers etc) break
4900 * straight socket inheritance.
4903 write_inheritable_socket(InheritableSocket *dest, SOCKET src, pid_t childpid)
4905 dest->origsocket = src;
4906 if (src != 0 && src != PGINVALID_SOCKET)
4909 if (WSADuplicateSocket(src, childpid, &dest->wsainfo) != 0)
4912 (errmsg("could not duplicate socket %d for use in backend: error code %d",
4913 (int) src, WSAGetLastError())));
4921 * Read a duplicate socket structure back, and get the socket descriptor.
4924 read_inheritable_socket(SOCKET *dest, InheritableSocket *src)
4928 if (src->origsocket == PGINVALID_SOCKET || src->origsocket == 0)
4930 /* Not a real socket! */
4931 *dest = src->origsocket;
4935 /* Actual socket, so create from structure */
4936 s = WSASocket(FROM_PROTOCOL_INFO,
4942 if (s == INVALID_SOCKET)
4944 write_stderr("could not create inherited socket: error code %d\n",
4951 * To make sure we don't get two references to the same socket, close
4952 * the original one. (This would happen when inheritance actually
4955 closesocket(src->origsocket);
4961 read_backend_variables(char *id, Port *port)
4963 BackendParameters param;
4966 /* Non-win32 implementation reads from file */
4970 fp = AllocateFile(id, PG_BINARY_R);
4973 write_stderr("could not read from backend variables file \"%s\": %s\n",
4974 id, strerror(errno));
4978 if (fread(¶m, sizeof(param), 1, fp) != 1)
4980 write_stderr("could not read from backend variables file \"%s\": %s\n",
4981 id, strerror(errno));
4987 if (unlink(id) != 0)
4989 write_stderr("could not remove file \"%s\": %s\n",
4990 id, strerror(errno));
4994 /* Win32 version uses mapped file */
4996 BackendParameters *paramp;
4999 paramHandle = (HANDLE) _atoi64(id);
5001 paramHandle = (HANDLE) atol(id);
5003 paramp = MapViewOfFile(paramHandle, FILE_MAP_READ, 0, 0, 0);
5006 write_stderr("could not map view of backend variables: error code %lu\n",
5011 memcpy(¶m, paramp, sizeof(BackendParameters));
5013 if (!UnmapViewOfFile(paramp))
5015 write_stderr("could not unmap view of backend variables: error code %lu\n",
5020 if (!CloseHandle(paramHandle))
5022 write_stderr("could not close handle to backend parameter variables: error code %lu\n",
5028 restore_backend_variables(¶m, port);
5031 /* Restore critical backend variables from the BackendParameters struct */
5033 restore_backend_variables(BackendParameters *param, Port *port)
5035 memcpy(port, ¶m->port, sizeof(Port));
5036 read_inheritable_socket(&port->sock, ¶m->portsocket);
5038 SetDataDir(param->DataDir);
5040 memcpy(&ListenSocket, ¶m->ListenSocket, sizeof(ListenSocket));
5042 MyCancelKey = param->MyCancelKey;
5043 MyPMChildSlot = param->MyPMChildSlot;
5045 UsedShmemSegID = param->UsedShmemSegID;
5046 UsedShmemSegAddr = param->UsedShmemSegAddr;
5048 ShmemLock = param->ShmemLock;
5049 ShmemVariableCache = param->ShmemVariableCache;
5050 ShmemBackendArray = param->ShmemBackendArray;
5052 LWLockArray = param->LWLockArray;
5053 ProcStructLock = param->ProcStructLock;
5054 ProcGlobal = param->ProcGlobal;
5055 AuxiliaryProcs = param->AuxiliaryProcs;
5056 PreparedXactProcs = param->PreparedXactProcs;
5057 PMSignalState = param->PMSignalState;
5058 read_inheritable_socket(&pgStatSock, ¶m->pgStatSock);
5060 PostmasterPid = param->PostmasterPid;
5061 PgStartTime = param->PgStartTime;
5062 PgReloadTime = param->PgReloadTime;
5063 first_syslogger_file_time = param->first_syslogger_file_time;
5065 redirection_done = param->redirection_done;
5066 IsBinaryUpgrade = param->IsBinaryUpgrade;
5067 max_safe_fds = param->max_safe_fds;
5070 PostmasterHandle = param->PostmasterHandle;
5071 pgwin32_initial_signal_pipe = param->initial_signal_pipe;
5073 memcpy(&postmaster_alive_fds, ¶m->postmaster_alive_fds,
5074 sizeof(postmaster_alive_fds));
5077 memcpy(&syslogPipe, ¶m->syslogPipe, sizeof(syslogPipe));
5079 strlcpy(my_exec_path, param->my_exec_path, MAXPGPATH);
5081 strlcpy(pkglib_path, param->pkglib_path, MAXPGPATH);
5083 strlcpy(ExtraOptions, param->ExtraOptions, MAXPGPATH);
5088 ShmemBackendArraySize(void)
5090 return mul_size(MaxLivePostmasterChildren(), sizeof(Backend));
5094 ShmemBackendArrayAllocation(void)
5096 Size size = ShmemBackendArraySize();
5098 ShmemBackendArray = (Backend *) ShmemAlloc(size);
5099 /* Mark all slots as empty */
5100 memset(ShmemBackendArray, 0, size);
5104 ShmemBackendArrayAdd(Backend *bn)
5106 /* The array slot corresponding to my PMChildSlot should be free */
5107 int i = bn->child_slot - 1;
5109 Assert(ShmemBackendArray[i].pid == 0);
5110 ShmemBackendArray[i] = *bn;
5114 ShmemBackendArrayRemove(Backend *bn)
5116 int i = bn->child_slot - 1;
5118 Assert(ShmemBackendArray[i].pid == bn->pid);
5119 /* Mark the slot as empty */
5120 ShmemBackendArray[i].pid = 0;
5122 #endif /* EXEC_BACKEND */
5128 * Subset implementation of waitpid() for Windows. We assume pid is -1
5129 * (that is, check all child processes) and options is WNOHANG (don't wait).
5132 waitpid(pid_t pid, int *exitstatus, int options)
5139 * Check if there are any dead children. If there are, return the pid of
5140 * the first one that died.
5142 if (GetQueuedCompletionStatus(win32ChildQueue, &dwd, &key, &ovl, 0))
5144 *exitstatus = (int) key;
5152 * Note! Code below executes on a thread pool! All operations must
5153 * be thread safe! Note that elog() and friends must *not* be used.
5156 pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
5158 win32_deadchild_waitinfo *childinfo = (win32_deadchild_waitinfo *) lpParameter;
5161 if (TimerOrWaitFired)
5162 return; /* timeout. Should never happen, since we use
5163 * INFINITE as timeout value. */
5166 * Remove handle from wait - required even though it's set to wait only
5169 UnregisterWaitEx(childinfo->waitHandle, NULL);
5171 if (!GetExitCodeProcess(childinfo->procHandle, &exitcode))
5174 * Should never happen. Inform user and set a fixed exitcode.
5176 write_stderr("could not read exit code for process\n");
5180 if (!PostQueuedCompletionStatus(win32ChildQueue, childinfo->procId, (ULONG_PTR) exitcode, NULL))
5181 write_stderr("could not post child completion status\n");
5184 * Handle is per-process, so we close it here instead of in the
5185 * originating thread
5187 CloseHandle(childinfo->procHandle);
5190 * Free struct that was allocated before the call to
5191 * RegisterWaitForSingleObject()
5195 /* Queue SIGCHLD signal */
5196 pg_queue_signal(SIGCHLD);
5201 * Initialize one and only handle for monitoring postmaster death.
5203 * Called once in the postmaster, so that child processes can subsequently
5204 * monitor if their parent is dead.
5207 InitPostmasterDeathWatchHandle(void)
5212 * Create a pipe. Postmaster holds the write end of the pipe open
5213 * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
5214 * the read file descriptor to select() to wake up in case postmaster
5215 * dies, or check for postmaster death with a (read() == 0). Children must
5216 * close the write end as soon as possible after forking, because EOF
5217 * won't be signaled in the read end until all processes have closed the
5218 * write fd. That is taken care of in ClosePostmasterPorts().
5220 Assert(MyProcPid == PostmasterPid);
5221 if (pipe(postmaster_alive_fds))
5223 (errcode_for_file_access(),
5224 errmsg_internal("could not create pipe to monitor postmaster death: %m")));
5227 * Set O_NONBLOCK to allow testing for the fd's presence with a read()
5230 if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK))
5232 (errcode_for_socket_access(),
5233 errmsg_internal("could not set postmaster death monitoring pipe to non-blocking mode: %m")));
5237 * On Windows, we use a process handle for the same purpose.
5239 if (DuplicateHandle(GetCurrentProcess(),
5240 GetCurrentProcess(),
5241 GetCurrentProcess(),
5245 DUPLICATE_SAME_ACCESS) == 0)
5247 (errmsg_internal("could not duplicate postmaster handle: error code %lu",