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 * Remove old temporary files. At this point there can be no other
1158 * Postgres processes running in this directory, so this should be safe.
1160 RemovePgTempFiles();
1163 * Remember postmaster startup time
1165 PgStartTime = GetCurrentTimestamp();
1166 /* PostmasterRandom wants its own copy */
1167 gettimeofday(&random_start_time, NULL);
1170 * We're ready to rock and roll...
1172 StartupPID = StartupDataBase();
1173 Assert(StartupPID != 0);
1174 pmState = PM_STARTUP;
1176 status = ServerLoop();
1179 * ServerLoop probably shouldn't ever return, but if it does, close down.
1181 ExitPostmaster(status != STATUS_OK);
1183 abort(); /* not reached */
1188 * on_proc_exit callback to delete external_pid_file
1191 unlink_external_pid_file(int status, Datum arg)
1193 if (external_pid_file)
1194 unlink(external_pid_file);
1199 * Compute and check the directory paths to files that are part of the
1200 * installation (as deduced from the postgres executable's own location)
1203 getInstallationPaths(const char *argv0)
1207 /* Locate the postgres executable itself */
1208 if (find_my_exec(argv0, my_exec_path) < 0)
1209 elog(FATAL, "%s: could not locate my own executable path", argv0);
1212 /* Locate executable backend before we change working directory */
1213 if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1214 postgres_exec_path) < 0)
1216 (errmsg("%s: could not locate matching postgres executable",
1221 * Locate the pkglib directory --- this has to be set early in case we try
1222 * to load any modules from it in response to postgresql.conf entries.
1224 get_pkglib_path(my_exec_path, pkglib_path);
1227 * Verify that there's a readable directory there; otherwise the Postgres
1228 * installation is incomplete or corrupt. (A typical cause of this
1229 * failure is that the postgres executable has been moved or hardlinked to
1230 * some directory that's not a sibling of the installation lib/
1233 pdir = AllocateDir(pkglib_path);
1236 (errcode_for_file_access(),
1237 errmsg("could not open directory \"%s\": %m",
1239 errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1244 * XXX is it worth similarly checking the share/ directory? If the lib/
1245 * directory is there, then share/ probably is too.
1251 * Validate the proposed data directory
1256 char path[MAXPGPATH];
1258 struct stat stat_buf;
1262 if (stat(DataDir, &stat_buf) != 0)
1264 if (errno == ENOENT)
1266 (errcode_for_file_access(),
1267 errmsg("data directory \"%s\" does not exist",
1271 (errcode_for_file_access(),
1272 errmsg("could not read permissions of directory \"%s\": %m",
1276 /* eventual chdir would fail anyway, but let's test ... */
1277 if (!S_ISDIR(stat_buf.st_mode))
1279 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1280 errmsg("specified data directory \"%s\" is not a directory",
1284 * Check that the directory belongs to my userid; if not, reject.
1286 * This check is an essential part of the interlock that prevents two
1287 * postmasters from starting in the same directory (see CreateLockFile()).
1288 * Do not remove or weaken it.
1290 * XXX can we safely enable this check on Windows?
1292 #if !defined(WIN32) && !defined(__CYGWIN__)
1293 if (stat_buf.st_uid != geteuid())
1295 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1296 errmsg("data directory \"%s\" has wrong ownership",
1298 errhint("The server must be started by the user that owns the data directory.")));
1302 * Check if the directory has group or world access. If so, reject.
1304 * It would be possible to allow weaker constraints (for example, allow
1305 * group access) but we cannot make a general assumption that that is
1306 * okay; for example there are platforms where nearly all users
1307 * customarily belong to the same group. Perhaps this test should be
1310 * XXX temporarily suppress check when on Windows, because there may not
1311 * be proper support for Unix-y file permissions. Need to think of a
1312 * reasonable check to apply on Windows.
1314 #if !defined(WIN32) && !defined(__CYGWIN__)
1315 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
1317 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1318 errmsg("data directory \"%s\" has group or world access",
1320 errdetail("Permissions should be u=rwx (0700).")));
1323 /* Look for PG_VERSION before looking for pg_control */
1324 ValidatePgVersion(DataDir);
1326 snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1328 fp = AllocateFile(path, PG_BINARY_R);
1331 write_stderr("%s: could not find the database system\n"
1332 "Expected to find it in the directory \"%s\",\n"
1333 "but could not open file \"%s\": %s\n",
1334 progname, DataDir, path, strerror(errno));
1341 * Main idle loop of postmaster
1351 last_touch_time = time(NULL);
1353 nSockets = initMasks(&readmask);
1361 * Wait for a connection request to arrive.
1363 * We wait at most one minute, to ensure that the other background
1364 * tasks handled below get done even when no requests are arriving.
1366 * If we are in PM_WAIT_DEAD_END state, then we don't want to accept
1367 * any new connections, so we don't call select() at all; just sleep
1368 * for a little bit with signals unblocked.
1370 memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
1372 PG_SETMASK(&UnBlockSig);
1374 if (pmState == PM_WAIT_DEAD_END)
1376 pg_usleep(100000L); /* 100 msec seems reasonable */
1381 /* must set timeout each time; some OSes change it! */
1382 struct timeval timeout;
1384 timeout.tv_sec = 60;
1385 timeout.tv_usec = 0;
1387 selres = select(nSockets, &rmask, NULL, NULL, &timeout);
1391 * Block all signals until we wait again. (This makes it safe for our
1392 * signal handlers to do nontrivial work.)
1394 PG_SETMASK(&BlockSig);
1396 /* Now check the select() result */
1399 if (errno != EINTR && errno != EWOULDBLOCK)
1402 (errcode_for_socket_access(),
1403 errmsg("select() failed in postmaster: %m")));
1404 return STATUS_ERROR;
1409 * New connection pending on any of our sockets? If so, fork a child
1410 * process to deal with it.
1416 for (i = 0; i < MAXLISTEN; i++)
1418 if (ListenSocket[i] == PGINVALID_SOCKET)
1420 if (FD_ISSET(ListenSocket[i], &rmask))
1424 port = ConnCreate(ListenSocket[i]);
1427 BackendStartup(port);
1430 * We no longer need the open socket or port structure
1433 StreamClose(port->sock);
1440 /* If we have lost the log collector, try to start a new one */
1441 if (SysLoggerPID == 0 && Logging_collector)
1442 SysLoggerPID = SysLogger_Start();
1445 * If no background writer process is running, and we are not in a
1446 * state that prevents it, start one. It doesn't matter if this
1447 * fails, we'll just try again later. Likewise for the checkpointer.
1449 if (pmState == PM_RUN || pmState == PM_RECOVERY ||
1450 pmState == PM_HOT_STANDBY)
1452 if (CheckpointerPID == 0)
1453 CheckpointerPID = StartCheckpointer();
1454 if (BgWriterPID == 0)
1455 BgWriterPID = StartBackgroundWriter();
1459 * Likewise, if we have lost the walwriter process, try to start a new
1460 * one. But this is needed only in normal operation (else we cannot
1461 * be writing any new WAL).
1463 if (WalWriterPID == 0 && pmState == PM_RUN)
1464 WalWriterPID = StartWalWriter();
1467 * If we have lost the autovacuum launcher, try to start a new one. We
1468 * don't want autovacuum to run in binary upgrade mode because
1469 * autovacuum might update relfrozenxid for empty tables before the
1470 * physical files are put in place.
1472 if (!IsBinaryUpgrade && AutoVacPID == 0 &&
1473 (AutoVacuumingActive() || start_autovac_launcher) &&
1476 AutoVacPID = StartAutoVacLauncher();
1477 if (AutoVacPID != 0)
1478 start_autovac_launcher = false; /* signal processed */
1481 /* If we have lost the archiver, try to start a new one */
1482 if (XLogArchivingActive() && PgArchPID == 0 && pmState == PM_RUN)
1483 PgArchPID = pgarch_start();
1485 /* If we have lost the stats collector, try to start a new one */
1486 if (PgStatPID == 0 && pmState == PM_RUN)
1487 PgStatPID = pgstat_start();
1489 /* If we need to signal the autovacuum launcher, do so now */
1490 if (avlauncher_needs_signal)
1492 avlauncher_needs_signal = false;
1493 if (AutoVacPID != 0)
1494 kill(AutoVacPID, SIGUSR2);
1498 * Touch Unix socket and lock files every 58 minutes, to ensure that
1499 * they are not removed by overzealous /tmp-cleaning tasks. We assume
1500 * no one runs cleaners with cutoff times of less than an hour ...
1503 if (now - last_touch_time >= 58 * SECS_PER_MINUTE)
1506 TouchSocketLockFiles();
1507 last_touch_time = now;
1514 * Initialise the masks for select() for the ports we are listening on.
1515 * Return the number of sockets to listen on.
1518 initMasks(fd_set *rmask)
1525 for (i = 0; i < MAXLISTEN; i++)
1527 int fd = ListenSocket[i];
1529 if (fd == PGINVALID_SOCKET)
1542 * Read a client's startup packet and do something according to it.
1544 * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
1545 * not return at all.
1547 * (Note that ereport(FATAL) stuff is sent to the client, so only use it
1548 * if that's what you want. Return STATUS_ERROR if you don't want to
1549 * send anything to the client, which would typically be appropriate
1550 * if we detect a communications failure.)
1553 ProcessStartupPacket(Port *port, bool SSLdone)
1557 ProtocolVersion proto;
1558 MemoryContext oldcontext;
1560 if (pq_getbytes((char *) &len, 4) == EOF)
1563 * EOF after SSLdone probably means the client didn't like our
1564 * response to NEGOTIATE_SSL_CODE. That's not an error condition, so
1565 * don't clutter the log with a complaint.
1569 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1570 errmsg("incomplete startup packet")));
1571 return STATUS_ERROR;
1577 if (len < (int32) sizeof(ProtocolVersion) ||
1578 len > MAX_STARTUP_PACKET_LENGTH)
1581 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1582 errmsg("invalid length of startup packet")));
1583 return STATUS_ERROR;
1587 * Allocate at least the size of an old-style startup packet, plus one
1588 * extra byte, and make sure all are zeroes. This ensures we will have
1589 * null termination of all strings, in both fixed- and variable-length
1592 if (len <= (int32) sizeof(StartupPacket))
1593 buf = palloc0(sizeof(StartupPacket) + 1);
1595 buf = palloc0(len + 1);
1597 if (pq_getbytes(buf, len) == EOF)
1600 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1601 errmsg("incomplete startup packet")));
1602 return STATUS_ERROR;
1606 * The first field is either a protocol version number or a special
1609 port->proto = proto = ntohl(*((ProtocolVersion *) buf));
1611 if (proto == CANCEL_REQUEST_CODE)
1613 processCancelRequest(port, buf);
1614 /* Not really an error, but we don't want to proceed further */
1615 return STATUS_ERROR;
1618 if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
1623 /* No SSL when disabled or on Unix sockets */
1624 if (!EnableSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
1627 SSLok = 'S'; /* Support for SSL */
1629 SSLok = 'N'; /* No support for SSL */
1633 if (send(port->sock, &SSLok, 1, 0) != 1)
1636 goto retry1; /* if interrupted, just retry */
1638 (errcode_for_socket_access(),
1639 errmsg("failed to send SSL negotiation response: %m")));
1640 return STATUS_ERROR; /* close the connection */
1644 if (SSLok == 'S' && secure_open_server(port) == -1)
1645 return STATUS_ERROR;
1647 /* regular startup packet, cancel, etc packet should follow... */
1648 /* but not another SSL negotiation request */
1649 return ProcessStartupPacket(port, true);
1652 /* Could add additional special packet types here */
1655 * Set FrontendProtocol now so that ereport() knows what format to send if
1656 * we fail during startup.
1658 FrontendProtocol = proto;
1660 /* Check we can handle the protocol the frontend is using. */
1662 if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
1663 PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
1664 (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
1665 PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
1667 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1668 errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
1669 PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
1670 PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST),
1671 PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST),
1672 PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))));
1675 * Now fetch parameters out of startup packet and save them into the Port
1676 * structure. All data structures attached to the Port struct must be
1677 * allocated in TopMemoryContext so that they will remain available in a
1678 * running backend (even after PostmasterContext is destroyed). We need
1679 * not worry about leaking this storage on failure, since we aren't in the
1680 * postmaster process anymore.
1682 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1684 if (PG_PROTOCOL_MAJOR(proto) >= 3)
1686 int32 offset = sizeof(ProtocolVersion);
1689 * Scan packet body for name/option pairs. We can assume any string
1690 * beginning within the packet body is null-terminated, thanks to
1691 * zeroing extra byte above.
1693 port->guc_options = NIL;
1695 while (offset < len)
1697 char *nameptr = ((char *) buf) + offset;
1701 if (*nameptr == '\0')
1702 break; /* found packet terminator */
1703 valoffset = offset + strlen(nameptr) + 1;
1704 if (valoffset >= len)
1705 break; /* missing value, will complain below */
1706 valptr = ((char *) buf) + valoffset;
1708 if (strcmp(nameptr, "database") == 0)
1709 port->database_name = pstrdup(valptr);
1710 else if (strcmp(nameptr, "user") == 0)
1711 port->user_name = pstrdup(valptr);
1712 else if (strcmp(nameptr, "options") == 0)
1713 port->cmdline_options = pstrdup(valptr);
1714 else if (strcmp(nameptr, "replication") == 0)
1716 if (!parse_bool(valptr, &am_walsender))
1718 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1719 errmsg("invalid value for boolean option \"replication\"")));
1723 /* Assume it's a generic GUC option */
1724 port->guc_options = lappend(port->guc_options,
1726 port->guc_options = lappend(port->guc_options,
1729 offset = valoffset + strlen(valptr) + 1;
1733 * If we didn't find a packet terminator exactly at the end of the
1734 * given packet length, complain.
1736 if (offset != len - 1)
1738 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1739 errmsg("invalid startup packet layout: expected terminator as last byte")));
1744 * Get the parameters from the old-style, fixed-width-fields startup
1745 * packet as C strings. The packet destination was cleared first so a
1746 * short packet has zeros silently added. We have to be prepared to
1747 * truncate the pstrdup result for oversize fields, though.
1749 StartupPacket *packet = (StartupPacket *) buf;
1751 port->database_name = pstrdup(packet->database);
1752 if (strlen(port->database_name) > sizeof(packet->database))
1753 port->database_name[sizeof(packet->database)] = '\0';
1754 port->user_name = pstrdup(packet->user);
1755 if (strlen(port->user_name) > sizeof(packet->user))
1756 port->user_name[sizeof(packet->user)] = '\0';
1757 port->cmdline_options = pstrdup(packet->options);
1758 if (strlen(port->cmdline_options) > sizeof(packet->options))
1759 port->cmdline_options[sizeof(packet->options)] = '\0';
1760 port->guc_options = NIL;
1763 /* Check a user name was given. */
1764 if (port->user_name == NULL || port->user_name[0] == '\0')
1766 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1767 errmsg("no PostgreSQL user name specified in startup packet")));
1769 /* The database defaults to the user name. */
1770 if (port->database_name == NULL || port->database_name[0] == '\0')
1771 port->database_name = pstrdup(port->user_name);
1773 if (Db_user_namespace)
1776 * If user@, it is a global user, remove '@'. We only want to do this
1777 * if there is an '@' at the end and no earlier in the user string or
1778 * they may fake as a local user of another database attaching to this
1781 if (strchr(port->user_name, '@') ==
1782 port->user_name + strlen(port->user_name) - 1)
1783 *strchr(port->user_name, '@') = '\0';
1786 /* Append '@' and dbname */
1789 db_user = palloc(strlen(port->user_name) +
1790 strlen(port->database_name) + 2);
1791 sprintf(db_user, "%s@%s", port->user_name, port->database_name);
1792 port->user_name = db_user;
1797 * Truncate given database and user names to length of a Postgres name.
1798 * This avoids lookup failures when overlength names are given.
1800 if (strlen(port->database_name) >= NAMEDATALEN)
1801 port->database_name[NAMEDATALEN - 1] = '\0';
1802 if (strlen(port->user_name) >= NAMEDATALEN)
1803 port->user_name[NAMEDATALEN - 1] = '\0';
1805 /* Walsender is not related to a particular database */
1807 port->database_name[0] = '\0';
1810 * Done putting stuff in TopMemoryContext.
1812 MemoryContextSwitchTo(oldcontext);
1815 * If we're going to reject the connection due to database state, say so
1816 * now instead of wasting cycles on an authentication exchange. (This also
1817 * allows a pg_ping utility to be written.)
1819 switch (port->canAcceptConnections)
1823 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1824 errmsg("the database system is starting up")));
1828 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1829 errmsg("the database system is shutting down")));
1833 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1834 errmsg("the database system is in recovery mode")));
1838 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
1839 errmsg("sorry, too many clients already")));
1841 case CAC_WAITBACKUP:
1842 /* OK for now, will check in InitPostgres */
1853 * The client has sent a cancel request packet, not a normal
1854 * start-a-new-connection packet. Perform the necessary processing.
1855 * Nothing is sent back to the client.
1858 processCancelRequest(Port *port, void *pkt)
1860 CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
1862 long cancelAuthCode;
1865 #ifndef EXEC_BACKEND
1871 backendPID = (int) ntohl(canc->backendPID);
1872 cancelAuthCode = (long) ntohl(canc->cancelAuthCode);
1875 * See if we have a matching backend. In the EXEC_BACKEND case, we can no
1876 * longer access the postmaster's own backend list, and must rely on the
1877 * duplicate array in shared memory.
1879 #ifndef EXEC_BACKEND
1880 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
1882 bp = (Backend *) DLE_VAL(curr);
1884 for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
1886 bp = (Backend *) &ShmemBackendArray[i];
1888 if (bp->pid == backendPID)
1890 if (bp->cancel_key == cancelAuthCode)
1892 /* Found a match; signal that backend to cancel current op */
1894 (errmsg_internal("processing cancel request: sending SIGINT to process %d",
1896 signal_child(bp->pid, SIGINT);
1899 /* Right PID, wrong key: no way, Jose */
1901 (errmsg("wrong key in cancel request for process %d",
1907 /* No matching backend */
1909 (errmsg("PID %d in cancel request did not match any process",
1914 * canAcceptConnections --- check to see if database state allows connections.
1917 canAcceptConnections(void)
1919 CAC_state result = CAC_OK;
1922 * Can't start backends when in startup/shutdown/inconsistent recovery
1925 * In state PM_WAIT_BACKUP only superusers can connect (this must be
1926 * allowed so that a superuser can end online backup mode); we return
1927 * CAC_WAITBACKUP code to indicate that this must be checked later. Note
1928 * that neither CAC_OK nor CAC_WAITBACKUP can safely be returned until we
1929 * have checked for too many children.
1931 if (pmState != PM_RUN)
1933 if (pmState == PM_WAIT_BACKUP)
1934 result = CAC_WAITBACKUP; /* allow superusers only */
1935 else if (Shutdown > NoShutdown)
1936 return CAC_SHUTDOWN; /* shutdown is pending */
1937 else if (!FatalError &&
1938 (pmState == PM_STARTUP ||
1939 pmState == PM_RECOVERY))
1940 return CAC_STARTUP; /* normal startup */
1941 else if (!FatalError &&
1942 pmState == PM_HOT_STANDBY)
1943 result = CAC_OK; /* connection OK during hot standby */
1945 return CAC_RECOVERY; /* else must be crash recovery */
1949 * Don't start too many children.
1951 * We allow more connections than we can have backends here because some
1952 * might still be authenticating; they might fail auth, or some existing
1953 * backend might exit before the auth cycle is completed. The exact
1954 * MaxBackends limit is enforced when a new backend tries to join the
1955 * shared-inval backend array.
1957 * The limit here must match the sizes of the per-child-process arrays;
1958 * see comments for MaxLivePostmasterChildren().
1960 if (CountChildren(BACKEND_TYPE_ALL) >= MaxLivePostmasterChildren())
1961 result = CAC_TOOMANY;
1968 * ConnCreate -- create a local connection data structure
1970 * Returns NULL on failure, other than out-of-memory which is fatal.
1973 ConnCreate(int serverFd)
1977 if (!(port = (Port *) calloc(1, sizeof(Port))))
1980 (errcode(ERRCODE_OUT_OF_MEMORY),
1981 errmsg("out of memory")));
1985 if (StreamConnection(serverFd, port) != STATUS_OK)
1987 if (port->sock >= 0)
1988 StreamClose(port->sock);
1994 * Precompute password salt values to use for this connection. It's
1995 * slightly annoying to do this long in advance of knowing whether we'll
1996 * need 'em or not, but we must do the random() calls before we fork, not
1997 * after. Else the postmaster's random sequence won't get advanced, and
1998 * all backends would end up using the same salt...
2000 RandomSalt(port->md5Salt);
2003 * Allocate GSSAPI specific state struct
2005 #ifndef EXEC_BACKEND
2006 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2007 port->gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
2011 (errcode(ERRCODE_OUT_OF_MEMORY),
2012 errmsg("out of memory")));
2023 * ConnFree -- free a local connection data structure
2026 ConnFree(Port *conn)
2038 * ClosePostmasterPorts -- close all the postmaster's open sockets
2040 * This is called during child process startup to release file descriptors
2041 * that are not needed by that child process. The postmaster still has
2042 * them open, of course.
2044 * Note: we pass am_syslogger as a boolean because we don't want to set
2045 * the global variable yet when this is called.
2048 ClosePostmasterPorts(bool am_syslogger)
2055 * Close the write end of postmaster death watch pipe. It's important to
2056 * do this as early as possible, so that if postmaster dies, others won't
2057 * think that it's still running because we're holding the pipe open.
2059 if (close(postmaster_alive_fds[POSTMASTER_FD_OWN]))
2061 (errcode_for_file_access(),
2062 errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
2063 postmaster_alive_fds[POSTMASTER_FD_OWN] = -1;
2066 /* Close the listen sockets */
2067 for (i = 0; i < MAXLISTEN; i++)
2069 if (ListenSocket[i] != PGINVALID_SOCKET)
2071 StreamClose(ListenSocket[i]);
2072 ListenSocket[i] = PGINVALID_SOCKET;
2076 /* If using syslogger, close the read side of the pipe */
2080 if (syslogPipe[0] >= 0)
2081 close(syslogPipe[0]);
2085 CloseHandle(syslogPipe[0]);
2091 /* If using Bonjour, close the connection to the mDNS daemon */
2093 close(DNSServiceRefSockFD(bonjour_sdref));
2099 * reset_shared -- reset shared memory and semaphores
2102 reset_shared(int port)
2105 * Create or re-create shared memory and semaphores.
2107 * Note: in each "cycle of life" we will normally assign the same IPC keys
2108 * (if using SysV shmem and/or semas), since the port number is used to
2109 * determine IPC keys. This helps ensure that we will clean up dead IPC
2110 * objects if the postmaster crashes and is restarted.
2112 CreateSharedMemoryAndSemaphores(false, port);
2117 * SIGHUP -- reread config files, and tell children to do same
2120 SIGHUP_handler(SIGNAL_ARGS)
2122 int save_errno = errno;
2124 PG_SETMASK(&BlockSig);
2126 if (Shutdown <= SmartShutdown)
2129 (errmsg("received SIGHUP, reloading configuration files")));
2130 ProcessConfigFile(PGC_SIGHUP);
2131 SignalChildren(SIGHUP);
2132 if (StartupPID != 0)
2133 signal_child(StartupPID, SIGHUP);
2134 if (BgWriterPID != 0)
2135 signal_child(BgWriterPID, SIGHUP);
2136 if (CheckpointerPID != 0)
2137 signal_child(CheckpointerPID, SIGHUP);
2138 if (WalWriterPID != 0)
2139 signal_child(WalWriterPID, SIGHUP);
2140 if (WalReceiverPID != 0)
2141 signal_child(WalReceiverPID, SIGHUP);
2142 if (AutoVacPID != 0)
2143 signal_child(AutoVacPID, SIGHUP);
2145 signal_child(PgArchPID, SIGHUP);
2146 if (SysLoggerPID != 0)
2147 signal_child(SysLoggerPID, SIGHUP);
2149 signal_child(PgStatPID, SIGHUP);
2151 /* Reload authentication config files too */
2154 (errmsg("pg_hba.conf not reloaded")));
2159 /* Update the starting-point file for future children */
2160 write_nondefault_variables(PGC_SIGHUP);
2164 PG_SETMASK(&UnBlockSig);
2171 * pmdie -- signal handler for processing various postmaster signals.
2176 int save_errno = errno;
2178 PG_SETMASK(&BlockSig);
2181 (errmsg_internal("postmaster received signal %d",
2182 postgres_signal_arg)));
2184 switch (postgres_signal_arg)
2191 * Wait for children to end their work, then shut down.
2193 if (Shutdown >= SmartShutdown)
2195 Shutdown = SmartShutdown;
2197 (errmsg("received smart shutdown request")));
2199 if (pmState == PM_RUN || pmState == PM_RECOVERY ||
2200 pmState == PM_HOT_STANDBY || pmState == PM_STARTUP)
2202 /* autovacuum workers are told to shut down immediately */
2203 SignalSomeChildren(SIGTERM, BACKEND_TYPE_AUTOVAC);
2204 /* and the autovac launcher too */
2205 if (AutoVacPID != 0)
2206 signal_child(AutoVacPID, SIGTERM);
2207 /* and the bgwriter too */
2208 if (BgWriterPID != 0)
2209 signal_child(BgWriterPID, SIGTERM);
2210 /* and the walwriter too */
2211 if (WalWriterPID != 0)
2212 signal_child(WalWriterPID, SIGTERM);
2215 * If we're in recovery, we can't kill the startup process
2216 * right away, because at present doing so does not release
2217 * its locks. We might want to change this in a future
2218 * release. For the time being, the PM_WAIT_READONLY state
2219 * indicates that we're waiting for the regular (read only)
2220 * backends to die off; once they do, we'll kill the startup
2221 * and walreceiver processes.
2223 pmState = (pmState == PM_RUN) ?
2224 PM_WAIT_BACKUP : PM_WAIT_READONLY;
2228 * Now wait for online backup mode to end and backends to exit. If
2229 * that is already the case, PostmasterStateMachine will take the
2232 PostmasterStateMachine();
2240 * Abort all children with SIGTERM (rollback active transactions
2241 * and exit) and shut down when they are gone.
2243 if (Shutdown >= FastShutdown)
2245 Shutdown = FastShutdown;
2247 (errmsg("received fast shutdown request")));
2249 if (StartupPID != 0)
2250 signal_child(StartupPID, SIGTERM);
2251 if (BgWriterPID != 0)
2252 signal_child(BgWriterPID, SIGTERM);
2253 if (WalReceiverPID != 0)
2254 signal_child(WalReceiverPID, SIGTERM);
2255 if (pmState == PM_RECOVERY)
2258 * Only startup, bgwriter, and checkpointer should be active
2259 * in this state; we just signaled the first two, and we don't
2260 * want to kill checkpointer yet.
2262 pmState = PM_WAIT_BACKENDS;
2264 else if (pmState == PM_RUN ||
2265 pmState == PM_WAIT_BACKUP ||
2266 pmState == PM_WAIT_READONLY ||
2267 pmState == PM_WAIT_BACKENDS ||
2268 pmState == PM_HOT_STANDBY)
2271 (errmsg("aborting any active transactions")));
2272 /* shut down all backends and autovac workers */
2273 SignalSomeChildren(SIGTERM,
2274 BACKEND_TYPE_NORMAL | BACKEND_TYPE_AUTOVAC);
2275 /* and the autovac launcher too */
2276 if (AutoVacPID != 0)
2277 signal_child(AutoVacPID, SIGTERM);
2278 /* and the walwriter too */
2279 if (WalWriterPID != 0)
2280 signal_child(WalWriterPID, SIGTERM);
2281 pmState = PM_WAIT_BACKENDS;
2285 * Now wait for backends to exit. If there are none,
2286 * PostmasterStateMachine will take the next step.
2288 PostmasterStateMachine();
2294 * Immediate Shutdown:
2296 * abort all children with SIGQUIT and exit without attempt to
2297 * properly shut down data base system.
2300 (errmsg("received immediate shutdown request")));
2301 SignalChildren(SIGQUIT);
2302 if (StartupPID != 0)
2303 signal_child(StartupPID, SIGQUIT);
2304 if (BgWriterPID != 0)
2305 signal_child(BgWriterPID, SIGQUIT);
2306 if (CheckpointerPID != 0)
2307 signal_child(CheckpointerPID, SIGQUIT);
2308 if (WalWriterPID != 0)
2309 signal_child(WalWriterPID, SIGQUIT);
2310 if (WalReceiverPID != 0)
2311 signal_child(WalReceiverPID, SIGQUIT);
2312 if (AutoVacPID != 0)
2313 signal_child(AutoVacPID, SIGQUIT);
2315 signal_child(PgArchPID, SIGQUIT);
2317 signal_child(PgStatPID, SIGQUIT);
2322 PG_SETMASK(&UnBlockSig);
2328 * Reaper -- signal handler to cleanup after a child process dies.
2333 int save_errno = errno;
2334 int pid; /* process id of dead child process */
2335 int exitstatus; /* its exit status */
2337 PG_SETMASK(&BlockSig);
2340 (errmsg_internal("reaping dead processes")));
2342 while ((pid = waitpid(-1, &exitstatus, WNOHANG)) > 0)
2345 * Check if this child was a startup process.
2347 if (pid == StartupPID)
2352 * Unexpected exit of startup process (including FATAL exit)
2353 * during PM_STARTUP is treated as catastrophic. There are no
2354 * other processes running yet, so we can just exit.
2356 if (pmState == PM_STARTUP && !EXIT_STATUS_0(exitstatus))
2358 LogChildExit(LOG, _("startup process"),
2361 (errmsg("aborting startup due to startup process failure")));
2366 * Startup process exited in response to a shutdown request (or it
2367 * completed normally regardless of the shutdown request).
2369 if (Shutdown > NoShutdown &&
2370 (EXIT_STATUS_0(exitstatus) || EXIT_STATUS_1(exitstatus)))
2372 pmState = PM_WAIT_BACKENDS;
2373 /* PostmasterStateMachine logic does the rest */
2378 * After PM_STARTUP, any unexpected exit (including FATAL exit) of
2379 * the startup process is catastrophic, so kill other children,
2380 * and set RecoveryError so we don't try to reinitialize after
2381 * they're gone. Exception: if FatalError is already set, that
2382 * implies we previously sent the startup process a SIGQUIT, so
2383 * that's probably the reason it died, and we do want to try to
2384 * restart in that case.
2386 if (!EXIT_STATUS_0(exitstatus))
2389 RecoveryError = true;
2390 HandleChildCrash(pid, exitstatus,
2391 _("startup process"));
2396 * Startup succeeded, commence normal operations
2399 ReachedNormalRunning = true;
2403 * Kill any walsenders to force the downstream standby(s) to
2404 * reread the timeline history file, adjust their timelines and
2405 * establish replication connections again. This is required
2406 * because the timeline of cascading standby is not consistent
2407 * with that of cascaded one just after failover. We LOG this
2408 * message since we need to leave a record to explain this
2411 * XXX should avoid the need for disconnection. When we do,
2412 * am_cascading_walsender should be replaced with
2413 * RecoveryInProgress()
2415 if (max_wal_senders > 0 && CountChildren(BACKEND_TYPE_WALSND) > 0)
2418 (errmsg("terminating all walsender processes to force cascaded "
2419 "standby(s) to update timeline and reconnect")));
2420 SignalSomeChildren(SIGUSR2, BACKEND_TYPE_WALSND);
2424 * Crank up the background tasks, if we didn't do that already
2425 * when we entered consistent recovery state. It doesn't matter
2426 * if this fails, we'll just try again later.
2428 if (CheckpointerPID == 0)
2429 CheckpointerPID = StartCheckpointer();
2430 if (BgWriterPID == 0)
2431 BgWriterPID = StartBackgroundWriter();
2432 if (WalWriterPID == 0)
2433 WalWriterPID = StartWalWriter();
2436 * Likewise, start other special children as needed. In a restart
2437 * situation, some of them may be alive already.
2439 if (!IsBinaryUpgrade && AutoVacuumingActive() && AutoVacPID == 0)
2440 AutoVacPID = StartAutoVacLauncher();
2441 if (XLogArchivingActive() && PgArchPID == 0)
2442 PgArchPID = pgarch_start();
2444 PgStatPID = pgstat_start();
2446 /* at this point we are really open for business */
2448 (errmsg("database system is ready to accept connections")));
2454 * Was it the bgwriter? Normal exit can be ignored; we'll start a new
2455 * one at the next iteration of the postmaster's main loop, if
2456 * necessary. Any other exit condition is treated as a crash.
2458 if (pid == BgWriterPID)
2461 if (!EXIT_STATUS_0(exitstatus))
2462 HandleChildCrash(pid, exitstatus,
2463 _("background writer process"));
2468 * Was it the checkpointer?
2470 if (pid == CheckpointerPID)
2472 CheckpointerPID = 0;
2473 if (EXIT_STATUS_0(exitstatus) && pmState == PM_SHUTDOWN)
2476 * OK, we saw normal exit of the checkpointer after it's been
2477 * told to shut down. We expect that it wrote a shutdown
2478 * checkpoint. (If for some reason it didn't, recovery will
2479 * occur on next postmaster start.)
2481 * At this point we should have no normal backend children
2482 * left (else we'd not be in PM_SHUTDOWN state) but we might
2483 * have dead_end children to wait for.
2485 * If we have an archiver subprocess, tell it to do a last
2486 * archive cycle and quit. Likewise, if we have walsender
2487 * processes, tell them to send any remaining WAL and quit.
2489 Assert(Shutdown > NoShutdown);
2491 /* Waken archiver for the last time */
2493 signal_child(PgArchPID, SIGUSR2);
2496 * Waken walsenders for the last time. No regular backends
2497 * should be around anymore.
2499 SignalChildren(SIGUSR2);
2501 pmState = PM_SHUTDOWN_2;
2504 * We can also shut down the stats collector now; there's
2505 * nothing left for it to do.
2508 signal_child(PgStatPID, SIGQUIT);
2513 * Any unexpected exit of the checkpointer (including FATAL
2514 * exit) is treated as a crash.
2516 HandleChildCrash(pid, exitstatus,
2517 _("checkpointer process"));
2524 * Was it the wal writer? Normal exit can be ignored; we'll start a
2525 * new one at the next iteration of the postmaster's main loop, if
2526 * necessary. Any other exit condition is treated as a crash.
2528 if (pid == WalWriterPID)
2531 if (!EXIT_STATUS_0(exitstatus))
2532 HandleChildCrash(pid, exitstatus,
2533 _("WAL writer process"));
2538 * Was it the wal receiver? If exit status is zero (normal) or one
2539 * (FATAL exit), we assume everything is all right just like normal
2542 if (pid == WalReceiverPID)
2545 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2546 HandleChildCrash(pid, exitstatus,
2547 _("WAL receiver process"));
2552 * Was it the autovacuum launcher? Normal exit can be ignored; we'll
2553 * start a new one at the next iteration of the postmaster's main
2554 * loop, if necessary. Any other exit condition is treated as a
2557 if (pid == AutoVacPID)
2560 if (!EXIT_STATUS_0(exitstatus))
2561 HandleChildCrash(pid, exitstatus,
2562 _("autovacuum launcher process"));
2567 * Was it the archiver? If so, just try to start a new one; no need
2568 * to force reset of the rest of the system. (If fail, we'll try
2569 * again in future cycles of the main loop.). Unless we were waiting
2570 * for it to shut down; don't restart it in that case, and
2571 * PostmasterStateMachine() will advance to the next shutdown step.
2573 if (pid == PgArchPID)
2576 if (!EXIT_STATUS_0(exitstatus))
2577 LogChildExit(LOG, _("archiver process"),
2579 if (XLogArchivingActive() && pmState == PM_RUN)
2580 PgArchPID = pgarch_start();
2585 * Was it the statistics collector? If so, just try to start a new
2586 * one; no need to force reset of the rest of the system. (If fail,
2587 * we'll try again in future cycles of the main loop.)
2589 if (pid == PgStatPID)
2592 if (!EXIT_STATUS_0(exitstatus))
2593 LogChildExit(LOG, _("statistics collector process"),
2595 if (pmState == PM_RUN)
2596 PgStatPID = pgstat_start();
2600 /* Was it the system logger? If so, try to start a new one */
2601 if (pid == SysLoggerPID)
2604 /* for safety's sake, launch new logger *first* */
2605 SysLoggerPID = SysLogger_Start();
2606 if (!EXIT_STATUS_0(exitstatus))
2607 LogChildExit(LOG, _("system logger process"),
2613 * Else do standard backend child cleanup.
2615 CleanupBackend(pid, exitstatus);
2616 } /* loop over pending child-death reports */
2619 * After cleaning out the SIGCHLD queue, see if we have any state changes
2620 * or actions to make.
2622 PostmasterStateMachine();
2624 /* Done with signal handler */
2625 PG_SETMASK(&UnBlockSig);
2632 * CleanupBackend -- cleanup after terminated backend.
2634 * Remove all local state associated with backend.
2637 CleanupBackend(int pid,
2638 int exitstatus) /* child's exit status. */
2642 LogChildExit(DEBUG2, _("server process"), pid, exitstatus);
2645 * If a backend dies in an ugly way then we must signal all other backends
2646 * to quickdie. If exit status is zero (normal) or one (FATAL exit), we
2647 * assume everything is all right and proceed to remove the backend from
2648 * the active backend list.
2653 * On win32, also treat ERROR_WAIT_NO_CHILDREN (128) as nonfatal case,
2654 * since that sometimes happens under load when the process fails to start
2655 * properly (long before it starts using shared memory). Microsoft reports
2656 * it is related to mutex failure:
2657 * http://archives.postgresql.org/pgsql-hackers/2010-09/msg00790.php
2659 if (exitstatus == ERROR_WAIT_NO_CHILDREN)
2661 LogChildExit(LOG, _("server process"), pid, exitstatus);
2666 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2668 HandleChildCrash(pid, exitstatus, _("server process"));
2672 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2674 Backend *bp = (Backend *) DLE_VAL(curr);
2680 if (!ReleasePostmasterChildSlot(bp->child_slot))
2683 * Uh-oh, the child failed to clean itself up. Treat as a
2686 HandleChildCrash(pid, exitstatus, _("server process"));
2690 ShmemBackendArrayRemove(bp);
2701 * HandleChildCrash -- cleanup after failed backend, bgwriter, checkpointer,
2702 * walwriter or autovacuum.
2704 * The objectives here are to clean up our local state about the child
2705 * process, and to signal all other remaining children to quickdie.
2708 HandleChildCrash(int pid, int exitstatus, const char *procname)
2715 * Make log entry unless there was a previous crash (if so, nonzero exit
2716 * status is to be expected in SIGQUIT response; don't clutter log)
2720 LogChildExit(LOG, procname, pid, exitstatus);
2722 (errmsg("terminating any other active server processes")));
2725 /* Process regular backends */
2726 for (curr = DLGetHead(BackendList); curr; curr = next)
2728 next = DLGetSucc(curr);
2729 bp = (Backend *) DLE_VAL(curr);
2733 * Found entry for freshly-dead backend, so remove it.
2737 (void) ReleasePostmasterChildSlot(bp->child_slot);
2739 ShmemBackendArrayRemove(bp);
2744 /* Keep looping so we can signal remaining backends */
2749 * This backend is still alive. Unless we did so already, tell it
2750 * to commit hara-kiri.
2752 * SIGQUIT is the special signal that says exit without proc_exit
2753 * and let the user know what's going on. But if SendStop is set
2754 * (-s on command line), then we send SIGSTOP instead, so that we
2755 * can get core dumps from all backends by hand.
2757 * We could exclude dead_end children here, but at least in the
2758 * SIGSTOP case it seems better to include them.
2763 (errmsg_internal("sending %s to process %d",
2764 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2766 signal_child(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
2771 /* Take care of the startup process too */
2772 if (pid == StartupPID)
2774 else if (StartupPID != 0 && !FatalError)
2777 (errmsg_internal("sending %s to process %d",
2778 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2779 (int) StartupPID)));
2780 signal_child(StartupPID, (SendStop ? SIGSTOP : SIGQUIT));
2783 /* Take care of the bgwriter too */
2784 if (pid == BgWriterPID)
2786 else if (BgWriterPID != 0 && !FatalError)
2789 (errmsg_internal("sending %s to process %d",
2790 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2791 (int) BgWriterPID)));
2792 signal_child(BgWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
2795 /* Take care of the checkpointer too */
2796 if (pid == CheckpointerPID)
2797 CheckpointerPID = 0;
2798 else if (CheckpointerPID != 0 && !FatalError)
2801 (errmsg_internal("sending %s to process %d",
2802 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2803 (int) CheckpointerPID)));
2804 signal_child(CheckpointerPID, (SendStop ? SIGSTOP : SIGQUIT));
2807 /* Take care of the walwriter too */
2808 if (pid == WalWriterPID)
2810 else if (WalWriterPID != 0 && !FatalError)
2813 (errmsg_internal("sending %s to process %d",
2814 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2815 (int) WalWriterPID)));
2816 signal_child(WalWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
2819 /* Take care of the walreceiver too */
2820 if (pid == WalReceiverPID)
2822 else if (WalReceiverPID != 0 && !FatalError)
2825 (errmsg_internal("sending %s to process %d",
2826 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2827 (int) WalReceiverPID)));
2828 signal_child(WalReceiverPID, (SendStop ? SIGSTOP : SIGQUIT));
2831 /* Take care of the autovacuum launcher too */
2832 if (pid == AutoVacPID)
2834 else if (AutoVacPID != 0 && !FatalError)
2837 (errmsg_internal("sending %s to process %d",
2838 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2839 (int) AutoVacPID)));
2840 signal_child(AutoVacPID, (SendStop ? SIGSTOP : SIGQUIT));
2844 * Force a power-cycle of the pgarch process too. (This isn't absolutely
2845 * necessary, but it seems like a good idea for robustness, and it
2846 * simplifies the state-machine logic in the case where a shutdown request
2847 * arrives during crash processing.)
2849 if (PgArchPID != 0 && !FatalError)
2852 (errmsg_internal("sending %s to process %d",
2855 signal_child(PgArchPID, SIGQUIT);
2859 * Force a power-cycle of the pgstat process too. (This isn't absolutely
2860 * necessary, but it seems like a good idea for robustness, and it
2861 * simplifies the state-machine logic in the case where a shutdown request
2862 * arrives during crash processing.)
2864 if (PgStatPID != 0 && !FatalError)
2867 (errmsg_internal("sending %s to process %d",
2870 signal_child(PgStatPID, SIGQUIT);
2871 allow_immediate_pgstat_restart();
2874 /* We do NOT restart the syslogger */
2877 /* We now transit into a state of waiting for children to die */
2878 if (pmState == PM_RECOVERY ||
2879 pmState == PM_HOT_STANDBY ||
2880 pmState == PM_RUN ||
2881 pmState == PM_WAIT_BACKUP ||
2882 pmState == PM_WAIT_READONLY ||
2883 pmState == PM_SHUTDOWN)
2884 pmState = PM_WAIT_BACKENDS;
2888 * Log the death of a child process.
2891 LogChildExit(int lev, const char *procname, int pid, int exitstatus)
2894 * size of activity_buffer is arbitrary, but set equal to default
2895 * track_activity_query_size
2897 char activity_buffer[1024];
2898 const char *activity = NULL;
2900 if (!EXIT_STATUS_0(exitstatus))
2901 activity = pgstat_get_crashed_backend_activity(pid,
2903 sizeof(activity_buffer));
2905 if (WIFEXITED(exitstatus))
2909 translator: %s is a noun phrase describing a child process, such as
2911 (errmsg("%s (PID %d) exited with exit code %d",
2912 procname, pid, WEXITSTATUS(exitstatus)),
2913 activity ? errdetail("Failed process was running: %s", activity) : 0));
2914 else if (WIFSIGNALED(exitstatus))
2919 translator: %s is a noun phrase describing a child process, such as
2921 (errmsg("%s (PID %d) was terminated by exception 0x%X",
2922 procname, pid, WTERMSIG(exitstatus)),
2923 errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
2924 activity ? errdetail("Failed process was running: %s", activity) : 0));
2925 #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST
2929 translator: %s is a noun phrase describing a child process, such as
2931 (errmsg("%s (PID %d) was terminated by signal %d: %s",
2932 procname, pid, WTERMSIG(exitstatus),
2933 WTERMSIG(exitstatus) < NSIG ?
2934 sys_siglist[WTERMSIG(exitstatus)] : "(unknown)"),
2935 activity ? errdetail("Failed process was running: %s", activity) : 0));
2940 translator: %s is a noun phrase describing a child process, such as
2942 (errmsg("%s (PID %d) was terminated by signal %d",
2943 procname, pid, WTERMSIG(exitstatus)),
2944 activity ? errdetail("Failed process was running: %s", activity) : 0));
2950 translator: %s is a noun phrase describing a child process, such as
2952 (errmsg("%s (PID %d) exited with unrecognized status %d",
2953 procname, pid, exitstatus),
2954 activity ? errdetail("Failed process was running: %s", activity) : 0));
2958 * Advance the postmaster's state machine and take actions as appropriate
2960 * This is common code for pmdie(), reaper() and sigusr1_handler(), which
2961 * receive the signals that might mean we need to change state.
2964 PostmasterStateMachine(void)
2966 if (pmState == PM_WAIT_BACKUP)
2969 * PM_WAIT_BACKUP state ends when online backup mode is not active.
2971 if (!BackupInProgress())
2972 pmState = PM_WAIT_BACKENDS;
2975 if (pmState == PM_WAIT_READONLY)
2978 * PM_WAIT_READONLY state ends when we have no regular backends that
2979 * have been started during recovery. We kill the startup and
2980 * walreceiver processes and transition to PM_WAIT_BACKENDS. Ideally,
2981 * we might like to kill these processes first and then wait for
2982 * backends to die off, but that doesn't work at present because
2983 * killing the startup process doesn't release its locks.
2985 if (CountChildren(BACKEND_TYPE_NORMAL) == 0)
2987 if (StartupPID != 0)
2988 signal_child(StartupPID, SIGTERM);
2989 if (WalReceiverPID != 0)
2990 signal_child(WalReceiverPID, SIGTERM);
2991 pmState = PM_WAIT_BACKENDS;
2996 * If we are in a state-machine state that implies waiting for backends to
2997 * exit, see if they're all gone, and change state if so.
2999 if (pmState == PM_WAIT_BACKENDS)
3002 * PM_WAIT_BACKENDS state ends when we have no regular backends
3003 * (including autovac workers) and no walwriter, autovac launcher or
3004 * bgwriter. If we are doing crash recovery then we expect the
3005 * checkpointer to exit as well, otherwise not. The archiver, stats,
3006 * and syslogger processes are disregarded since they are not
3007 * connected to shared memory; we also disregard dead_end children
3008 * here. Walsenders are also disregarded, they will be terminated
3009 * later after writing the checkpoint record, like the archiver
3012 if (CountChildren(BACKEND_TYPE_NORMAL | BACKEND_TYPE_AUTOVAC) == 0 &&
3014 WalReceiverPID == 0 &&
3016 (CheckpointerPID == 0 || !FatalError) &&
3017 WalWriterPID == 0 &&
3023 * Start waiting for dead_end children to die. This state
3024 * change causes ServerLoop to stop creating new ones.
3026 pmState = PM_WAIT_DEAD_END;
3029 * We already SIGQUIT'd the archiver and stats processes, if
3030 * any, when we entered FatalError state.
3036 * If we get here, we are proceeding with normal shutdown. All
3037 * the regular children are gone, and it's time to tell the
3038 * checkpointer to do a shutdown checkpoint.
3040 Assert(Shutdown > NoShutdown);
3041 /* Start the checkpointer if not running */
3042 if (CheckpointerPID == 0)
3043 CheckpointerPID = StartCheckpointer();
3044 /* And tell it to shut down */
3045 if (CheckpointerPID != 0)
3047 signal_child(CheckpointerPID, SIGUSR2);
3048 pmState = PM_SHUTDOWN;
3053 * If we failed to fork a checkpointer, just shut down.
3054 * Any required cleanup will happen at next restart. We
3055 * set FatalError so that an "abnormal shutdown" message
3056 * gets logged when we exit.
3059 pmState = PM_WAIT_DEAD_END;
3061 /* Kill the walsenders, archiver and stats collector too */
3062 SignalChildren(SIGQUIT);
3064 signal_child(PgArchPID, SIGQUIT);
3066 signal_child(PgStatPID, SIGQUIT);
3072 if (pmState == PM_SHUTDOWN_2)
3075 * PM_SHUTDOWN_2 state ends when there's no other children than
3076 * dead_end children left. There shouldn't be any regular backends
3077 * left by now anyway; what we're really waiting for is walsenders and
3080 * Walreceiver should normally be dead by now, but not when a fast
3081 * shutdown is performed during recovery.
3083 if (PgArchPID == 0 && CountChildren(BACKEND_TYPE_ALL) == 0 &&
3084 WalReceiverPID == 0)
3086 pmState = PM_WAIT_DEAD_END;
3090 if (pmState == PM_WAIT_DEAD_END)
3093 * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
3094 * (ie, no dead_end children remain), and the archiver and stats
3095 * collector are gone too.
3097 * The reason we wait for those two is to protect them against a new
3098 * postmaster starting conflicting subprocesses; this isn't an
3099 * ironclad protection, but it at least helps in the
3100 * shutdown-and-immediately-restart scenario. Note that they have
3101 * already been sent appropriate shutdown signals, either during a
3102 * normal state transition leading up to PM_WAIT_DEAD_END, or during
3103 * FatalError processing.
3105 if (DLGetHead(BackendList) == NULL &&
3106 PgArchPID == 0 && PgStatPID == 0)
3108 /* These other guys should be dead already */
3109 Assert(StartupPID == 0);
3110 Assert(WalReceiverPID == 0);
3111 Assert(BgWriterPID == 0);
3112 Assert(CheckpointerPID == 0);
3113 Assert(WalWriterPID == 0);
3114 Assert(AutoVacPID == 0);
3115 /* syslogger is not considered here */
3116 pmState = PM_NO_CHILDREN;
3121 * If we've been told to shut down, we exit as soon as there are no
3122 * remaining children. If there was a crash, cleanup will occur at the
3123 * next startup. (Before PostgreSQL 8.3, we tried to recover from the
3124 * crash before exiting, but that seems unwise if we are quitting because
3125 * we got SIGTERM from init --- there may well not be time for recovery
3126 * before init decides to SIGKILL us.)
3128 * Note that the syslogger continues to run. It will exit when it sees
3129 * EOF on its input pipe, which happens when there are no more upstream
3132 if (Shutdown > NoShutdown && pmState == PM_NO_CHILDREN)
3136 ereport(LOG, (errmsg("abnormal database system shutdown")));
3142 * Terminate exclusive backup mode to avoid recovery after a clean
3143 * fast shutdown. Since an exclusive backup can only be taken
3144 * during normal running (and not, for example, while running
3145 * under Hot Standby) it only makes sense to do this if we reached
3146 * normal running. If we're still in recovery, the backup file is
3147 * one we're recovering *from*, and we must keep it around so that
3148 * recovery restarts from the right place.
3150 if (ReachedNormalRunning)
3153 /* Normal exit from the postmaster is here */
3159 * If recovery failed, or the user does not want an automatic restart
3160 * after backend crashes, wait for all non-syslogger children to exit, and
3161 * then exit postmaster. We don't try to reinitialize when recovery fails,
3162 * because more than likely it will just fail again and we will keep
3165 if (pmState == PM_NO_CHILDREN && (RecoveryError || !restart_after_crash))
3169 * If we need to recover from a crash, wait for all non-syslogger children
3170 * to exit, then reset shmem and StartupDataBase.
3172 if (FatalError && pmState == PM_NO_CHILDREN)
3175 (errmsg("all server processes terminated; reinitializing")));
3178 reset_shared(PostPortNumber);
3180 StartupPID = StartupDataBase();
3181 Assert(StartupPID != 0);
3182 pmState = PM_STARTUP;
3188 * Send a signal to a postmaster child process
3190 * On systems that have setsid(), each child process sets itself up as a
3191 * process group leader. For signals that are generally interpreted in the
3192 * appropriate fashion, we signal the entire process group not just the
3193 * direct child process. This allows us to, for example, SIGQUIT a blocked
3194 * archive_recovery script, or SIGINT a script being run by a backend via
3197 * There is a race condition for recently-forked children: they might not
3198 * have executed setsid() yet. So we signal the child directly as well as
3199 * the group. We assume such a child will handle the signal before trying
3200 * to spawn any grandchild processes. We also assume that signaling the
3201 * child twice will not cause any problems.
3204 signal_child(pid_t pid, int signal)
3206 if (kill(pid, signal) < 0)
3207 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
3215 if (kill(-pid, signal) < 0)
3216 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) (-pid), signal);
3225 * Send a signal to the targeted children (but NOT special children;
3226 * dead_end children are never signaled, either).
3229 SignalSomeChildren(int signal, int target)
3232 bool signaled = false;
3234 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
3236 Backend *bp = (Backend *) DLE_VAL(curr);
3242 * Since target == BACKEND_TYPE_ALL is the most common case, we test
3243 * it first and avoid touching shared memory for every child.
3245 if (target != BACKEND_TYPE_ALL)
3249 if (bp->is_autovacuum)
3250 child = BACKEND_TYPE_AUTOVAC;
3251 else if (IsPostmasterChildWalSender(bp->child_slot))
3252 child = BACKEND_TYPE_WALSND;
3254 child = BACKEND_TYPE_NORMAL;
3255 if (!(target & child))
3260 (errmsg_internal("sending signal %d to process %d",
3261 signal, (int) bp->pid)));
3262 signal_child(bp->pid, signal);
3269 * BackendStartup -- start backend process
3271 * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
3273 * Note: if you change this code, also consider StartAutovacuumWorker.
3276 BackendStartup(Port *port)
3278 Backend *bn; /* for backend cleanup */
3282 * Create backend data structure. Better before the fork() so we can
3283 * handle failure cleanly.
3285 bn = (Backend *) malloc(sizeof(Backend));
3289 (errcode(ERRCODE_OUT_OF_MEMORY),
3290 errmsg("out of memory")));
3291 return STATUS_ERROR;
3295 * Compute the cancel key that will be assigned to this backend. The
3296 * backend will have its own copy in the forked-off process' value of
3297 * MyCancelKey, so that it can transmit the key to the frontend.
3299 MyCancelKey = PostmasterRandom();
3300 bn->cancel_key = MyCancelKey;
3302 /* Pass down canAcceptConnections state */
3303 port->canAcceptConnections = canAcceptConnections();
3304 bn->dead_end = (port->canAcceptConnections != CAC_OK &&
3305 port->canAcceptConnections != CAC_WAITBACKUP);
3308 * Unless it's a dead_end child, assign it a child slot number
3311 bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
3316 pid = backend_forkexec(port);
3317 #else /* !EXEC_BACKEND */
3318 pid = fork_process();
3319 if (pid == 0) /* child */
3324 * Let's clean up ourselves as the postmaster child, and close the
3325 * postmaster's listen sockets. (In EXEC_BACKEND case this is all
3326 * done in SubPostmasterMain.)
3328 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
3330 MyProcPid = getpid(); /* reset MyProcPid */
3332 MyStartTime = time(NULL);
3334 /* We don't want the postmaster's proc_exit() handlers */
3337 /* Close the postmaster's sockets */
3338 ClosePostmasterPorts(false);
3340 /* Perform additional initialization and collect startup packet */
3341 BackendInitialize(port);
3343 /* And run the backend */
3346 #endif /* EXEC_BACKEND */
3350 /* in parent, fork failed */
3351 int save_errno = errno;
3354 (void) ReleasePostmasterChildSlot(bn->child_slot);
3358 (errmsg("could not fork new process for connection: %m")));
3359 report_fork_failure_to_client(port, save_errno);
3360 return STATUS_ERROR;
3363 /* in parent, successful fork */
3365 (errmsg_internal("forked new backend, pid=%d socket=%d",
3366 (int) pid, (int) port->sock)));
3369 * Everything's been successful, it's safe to add this backend to our list
3373 bn->is_autovacuum = false;
3374 DLInitElem(&bn->elem, bn);
3375 DLAddHead(BackendList, &bn->elem);
3378 ShmemBackendArrayAdd(bn);
3385 * Try to report backend fork() failure to client before we close the
3386 * connection. Since we do not care to risk blocking the postmaster on
3387 * this connection, we set the connection to non-blocking and try only once.
3389 * This is grungy special-purpose code; we cannot use backend libpq since
3390 * it's not up and running.
3393 report_fork_failure_to_client(Port *port, int errnum)
3398 /* Format the error message packet (always V2 protocol) */
3399 snprintf(buffer, sizeof(buffer), "E%s%s\n",
3400 _("could not fork new process for connection: "),
3403 /* Set port to non-blocking. Don't do send() if this fails */
3404 if (!pg_set_noblock(port->sock))
3407 /* We'll retry after EINTR, but ignore all other failures */
3410 rc = send(port->sock, buffer, strlen(buffer) + 1, 0);
3411 } while (rc < 0 && errno == EINTR);
3416 * BackendInitialize -- initialize an interactive (postmaster-child)
3417 * backend process, and collect the client's startup packet.
3419 * returns: nothing. Will not return at all if there's any failure.
3421 * Note: this code does not depend on having any access to shared memory.
3422 * In the EXEC_BACKEND case, we are physically attached to shared memory
3423 * but have not yet set up most of our local pointers to shmem structures.
3426 BackendInitialize(Port *port)
3429 char remote_host[NI_MAXHOST];
3430 char remote_port[NI_MAXSERV];
3431 char remote_ps_data[NI_MAXHOST];
3433 /* Save port etc. for ps status */
3437 * PreAuthDelay is a debugging aid for investigating problems in the
3438 * authentication cycle: it can be set in postgresql.conf to allow time to
3439 * attach to the newly-forked backend with a debugger. (See also
3440 * PostAuthDelay, which we allow clients to pass through PGOPTIONS, but it
3441 * is not honored until after authentication.)
3443 if (PreAuthDelay > 0)
3444 pg_usleep(PreAuthDelay * 1000000L);
3446 /* This flag will remain set until InitPostgres finishes authentication */
3447 ClientAuthInProgress = true; /* limit visibility of log messages */
3449 /* save process start time */
3450 port->SessionStartTime = GetCurrentTimestamp();
3451 MyStartTime = timestamptz_to_time_t(port->SessionStartTime);
3453 /* set these to empty in case they are needed before we set them up */
3454 port->remote_host = "";
3455 port->remote_port = "";
3458 * Initialize libpq and enable reporting of ereport errors to the client.
3459 * Must do this now because authentication uses libpq to send messages.
3461 pq_init(); /* initialize libpq to talk to client */
3462 whereToSendOutput = DestRemote; /* now safe to ereport to client */
3465 * If possible, make this process a group leader, so that the postmaster
3466 * can signal any child processes too. (We do this now on the off chance
3467 * that something might spawn a child process during authentication.)
3471 elog(FATAL, "setsid() failed: %m");
3475 * We arrange for a simple exit(1) if we receive SIGTERM or SIGQUIT or
3476 * timeout while trying to collect the startup packet. Otherwise the
3477 * postmaster cannot shutdown the database FAST or IMMED cleanly if a
3478 * buggy client fails to send the packet promptly.
3480 pqsignal(SIGTERM, startup_die);
3481 pqsignal(SIGQUIT, startup_die);
3482 InitializeTimeouts(); /* establishes SIGALRM handler */
3483 PG_SETMASK(&StartupBlockSig);
3486 * Get the remote host name and port for logging and status display.
3488 remote_host[0] = '\0';
3489 remote_port[0] = '\0';
3490 if (pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
3491 remote_host, sizeof(remote_host),
3492 remote_port, sizeof(remote_port),
3493 (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV) != 0)
3495 int ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
3496 remote_host, sizeof(remote_host),
3497 remote_port, sizeof(remote_port),
3498 NI_NUMERICHOST | NI_NUMERICSERV);
3502 (errmsg_internal("pg_getnameinfo_all() failed: %s",
3503 gai_strerror(ret))));
3505 if (remote_port[0] == '\0')
3506 snprintf(remote_ps_data, sizeof(remote_ps_data), "%s", remote_host);
3508 snprintf(remote_ps_data, sizeof(remote_ps_data), "%s(%s)", remote_host, remote_port);
3510 if (Log_connections)
3514 (errmsg("connection received: host=%s port=%s",
3519 (errmsg("connection received: host=%s",
3524 * save remote_host and remote_port in port structure
3526 port->remote_host = strdup(remote_host);
3527 port->remote_port = strdup(remote_port);
3529 port->remote_hostname = port->remote_host;
3532 * Ready to begin client interaction. We will give up and exit(1) after a
3533 * time delay, so that a broken client can't hog a connection
3534 * indefinitely. PreAuthDelay and any DNS interactions above don't count
3535 * against the time limit.
3537 * Note: AuthenticationTimeout is applied here while waiting for the
3538 * startup packet, and then again in InitPostgres for the duration of any
3539 * authentication operations. So a hostile client could tie up the
3540 * process for nearly twice AuthenticationTimeout before we kick him off.
3542 * Note: because PostgresMain will call InitializeTimeouts again, the
3543 * registration of STARTUP_PACKET_TIMEOUT will be lost. This is okay
3544 * since we never use it again after this function.
3546 RegisterTimeout(STARTUP_PACKET_TIMEOUT, StartupPacketTimeoutHandler);
3547 enable_timeout_after(STARTUP_PACKET_TIMEOUT, AuthenticationTimeout * 1000);
3550 * Receive the startup packet (which might turn out to be a cancel request
3553 status = ProcessStartupPacket(port, false);
3556 * Stop here if it was bad or a cancel packet. ProcessStartupPacket
3557 * already did any appropriate error reporting.
3559 if (status != STATUS_OK)
3563 * Now that we have the user and database name, we can set the process
3564 * title for ps. It's good to do this as early as possible in startup.
3566 * For a walsender, the ps display is set in the following form:
3568 * postgres: wal sender process <user> <host> <activity>
3570 * To achieve that, we pass "wal sender process" as username and username
3571 * as dbname to init_ps_display(). XXX: should add a new variant of
3572 * init_ps_display() to avoid abusing the parameters like this.
3575 init_ps_display("wal sender process", port->user_name, remote_ps_data,
3576 update_process_title ? "authentication" : "");
3578 init_ps_display(port->user_name, port->database_name, remote_ps_data,
3579 update_process_title ? "authentication" : "");
3582 * Disable the timeout, and prevent SIGTERM/SIGQUIT again.
3584 disable_timeout(STARTUP_PACKET_TIMEOUT, false);
3585 PG_SETMASK(&BlockSig);
3590 * BackendRun -- set up the backend's argument list and invoke PostgresMain()
3593 * Shouldn't return at all.
3594 * If PostgresMain() fails, return status.
3597 BackendRun(Port *port)
3607 * Don't want backend to be able to see the postmaster random number
3608 * generator state. We have to clobber the static random_seed *and* start
3609 * a new random sequence in the random() library function.
3612 random_start_time.tv_usec = 0;
3613 /* slightly hacky way to get integer microseconds part of timestamptz */
3614 TimestampDifference(0, port->SessionStartTime, &secs, &usecs);
3615 srandom((unsigned int) (MyProcPid ^ usecs));
3618 * Now, build the argv vector that will be given to PostgresMain.
3620 * The maximum possible number of commandline arguments that could come
3621 * from ExtraOptions is (strlen(ExtraOptions) + 1) / 2; see
3624 maxac = 5; /* for fixed args supplied below */
3625 maxac += (strlen(ExtraOptions) + 1) / 2;
3627 av = (char **) MemoryContextAlloc(TopMemoryContext,
3628 maxac * sizeof(char *));
3631 av[ac++] = "postgres";
3634 * Pass any backend switches specified with -o on the postmaster's own
3635 * command line. We assume these are secure. (It's OK to mangle
3636 * ExtraOptions now, since we're safely inside a subprocess.)
3638 pg_split_opts(av, &ac, ExtraOptions);
3641 * Tell the backend which database to use.
3643 av[ac++] = port->database_name;
3650 * Debug: print arguments being passed to backend
3653 (errmsg_internal("%s child[%d]: starting with (",
3654 progname, (int) getpid())));
3655 for (i = 0; i < ac; ++i)
3657 (errmsg_internal("\t%s", av[i])));
3659 (errmsg_internal(")")));
3662 * Make sure we aren't in PostmasterContext anymore. (We can't delete it
3663 * just yet, though, because InitPostgres will need the HBA data.)
3665 MemoryContextSwitchTo(TopMemoryContext);
3667 PostgresMain(ac, av, port->user_name);
3674 * postmaster_forkexec -- fork and exec a postmaster subprocess
3676 * The caller must have set up the argv array already, except for argv[2]
3677 * which will be filled with the name of the temp variable file.
3679 * Returns the child process PID, or -1 on fork failure (a suitable error
3680 * message has been logged on failure).
3682 * All uses of this routine will dispatch to SubPostmasterMain in the
3686 postmaster_forkexec(int argc, char *argv[])
3690 /* This entry point passes dummy values for the Port variables */
3691 memset(&port, 0, sizeof(port));
3692 return internal_forkexec(argc, argv, &port);
3696 * backend_forkexec -- fork/exec off a backend process
3698 * Some operating systems (WIN32) don't have fork() so we have to simulate
3699 * it by storing parameters that need to be passed to the child and
3700 * then create a new child process.
3702 * returns the pid of the fork/exec'd process, or -1 on failure
3705 backend_forkexec(Port *port)
3710 av[ac++] = "postgres";
3711 av[ac++] = "--forkbackend";
3712 av[ac++] = NULL; /* filled in by internal_forkexec */
3715 Assert(ac < lengthof(av));
3717 return internal_forkexec(ac, av, port);
3723 * internal_forkexec non-win32 implementation
3725 * - writes out backend variables to the parameter file
3726 * - fork():s, and then exec():s the child process
3729 internal_forkexec(int argc, char *argv[], Port *port)
3731 static unsigned long tmpBackendFileNum = 0;
3733 char tmpfilename[MAXPGPATH];
3734 BackendParameters param;
3737 if (!save_backend_variables(¶m, port))
3738 return -1; /* log made by save_backend_variables */
3740 /* Calculate name for temp file */
3741 snprintf(tmpfilename, MAXPGPATH, "%s/%s.backend_var.%d.%lu",
3742 PG_TEMP_FILES_DIR, PG_TEMP_FILE_PREFIX,
3743 MyProcPid, ++tmpBackendFileNum);
3746 fp = AllocateFile(tmpfilename, PG_BINARY_W);
3749 /* As in OpenTemporaryFile, try to make the temp-file directory */
3750 mkdir(PG_TEMP_FILES_DIR, S_IRWXU);
3752 fp = AllocateFile(tmpfilename, PG_BINARY_W);
3756 (errcode_for_file_access(),
3757 errmsg("could not create file \"%s\": %m",
3763 if (fwrite(¶m, sizeof(param), 1, fp) != 1)
3766 (errcode_for_file_access(),
3767 errmsg("could not write to file \"%s\": %m", tmpfilename)));
3776 (errcode_for_file_access(),
3777 errmsg("could not write to file \"%s\": %m", tmpfilename)));
3781 /* Make sure caller set up argv properly */
3783 Assert(argv[argc] == NULL);
3784 Assert(strncmp(argv[1], "--fork", 6) == 0);
3785 Assert(argv[2] == NULL);
3787 /* Insert temp file name after --fork argument */
3788 argv[2] = tmpfilename;
3790 /* Fire off execv in child */
3791 if ((pid = fork_process()) == 0)
3793 if (execv(postgres_exec_path, argv) < 0)
3796 (errmsg("could not execute server process \"%s\": %m",
3797 postgres_exec_path)));
3798 /* We're already in the child process here, can't return */
3803 return pid; /* Parent returns pid, or -1 on fork failure */
3808 * internal_forkexec win32 implementation
3810 * - starts backend using CreateProcess(), in suspended state
3811 * - writes out backend variables to the parameter file
3812 * - during this, duplicates handles and sockets required for
3813 * inheritance into the new process
3814 * - resumes execution of the new process once the backend parameter
3818 internal_forkexec(int argc, char *argv[], Port *port)
3821 PROCESS_INFORMATION pi;
3824 char cmdLine[MAXPGPATH * 2];
3826 BackendParameters *param;
3827 SECURITY_ATTRIBUTES sa;
3828 char paramHandleStr[32];
3829 win32_deadchild_waitinfo *childinfo;
3831 /* Make sure caller set up argv properly */
3833 Assert(argv[argc] == NULL);
3834 Assert(strncmp(argv[1], "--fork", 6) == 0);
3835 Assert(argv[2] == NULL);
3837 /* Set up shared memory for parameter passing */
3838 ZeroMemory(&sa, sizeof(sa));
3839 sa.nLength = sizeof(sa);
3840 sa.bInheritHandle = TRUE;
3841 paramHandle = CreateFileMapping(INVALID_HANDLE_VALUE,
3845 sizeof(BackendParameters),
3847 if (paramHandle == INVALID_HANDLE_VALUE)
3849 elog(LOG, "could not create backend parameter file mapping: error code %lu",
3854 param = MapViewOfFile(paramHandle, FILE_MAP_WRITE, 0, 0, sizeof(BackendParameters));
3857 elog(LOG, "could not map backend parameter memory: error code %lu",
3859 CloseHandle(paramHandle);
3863 /* Insert temp file name after --fork argument */
3865 sprintf(paramHandleStr, "%llu", (LONG_PTR) paramHandle);
3867 sprintf(paramHandleStr, "%lu", (DWORD) paramHandle);
3869 argv[2] = paramHandleStr;
3871 /* Format the cmd line */
3872 cmdLine[sizeof(cmdLine) - 1] = '\0';
3873 cmdLine[sizeof(cmdLine) - 2] = '\0';
3874 snprintf(cmdLine, sizeof(cmdLine) - 1, "\"%s\"", postgres_exec_path);
3876 while (argv[++i] != NULL)
3878 j = strlen(cmdLine);
3879 snprintf(cmdLine + j, sizeof(cmdLine) - 1 - j, " \"%s\"", argv[i]);
3881 if (cmdLine[sizeof(cmdLine) - 2] != '\0')
3883 elog(LOG, "subprocess command line too long");
3887 memset(&pi, 0, sizeof(pi));
3888 memset(&si, 0, sizeof(si));
3892 * Create the subprocess in a suspended state. This will be resumed later,
3893 * once we have written out the parameter file.
3895 if (!CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, CREATE_SUSPENDED,
3896 NULL, NULL, &si, &pi))
3898 elog(LOG, "CreateProcess call failed: %m (error code %lu)",
3903 if (!save_backend_variables(param, port, pi.hProcess, pi.dwProcessId))
3906 * log made by save_backend_variables, but we have to clean up the
3907 * mess with the half-started process
3909 if (!TerminateProcess(pi.hProcess, 255))
3911 (errmsg_internal("could not terminate unstarted process: error code %lu",
3913 CloseHandle(pi.hProcess);
3914 CloseHandle(pi.hThread);
3915 return -1; /* log made by save_backend_variables */
3918 /* Drop the parameter shared memory that is now inherited to the backend */
3919 if (!UnmapViewOfFile(param))
3920 elog(LOG, "could not unmap view of backend parameter file: error code %lu",
3922 if (!CloseHandle(paramHandle))
3923 elog(LOG, "could not close handle to backend parameter file: error code %lu",
3927 * Reserve the memory region used by our main shared memory segment before
3928 * we resume the child process.
3930 if (!pgwin32_ReserveSharedMemoryRegion(pi.hProcess))
3933 * Failed to reserve the memory, so terminate the newly created
3934 * process and give up.
3936 if (!TerminateProcess(pi.hProcess, 255))
3938 (errmsg_internal("could not terminate process that failed to reserve memory: error code %lu",
3940 CloseHandle(pi.hProcess);
3941 CloseHandle(pi.hThread);
3942 return -1; /* logging done made by
3943 * pgwin32_ReserveSharedMemoryRegion() */
3947 * Now that the backend variables are written out, we start the child
3948 * thread so it can start initializing while we set up the rest of the
3951 if (ResumeThread(pi.hThread) == -1)
3953 if (!TerminateProcess(pi.hProcess, 255))
3956 (errmsg_internal("could not terminate unstartable process: error code %lu",
3958 CloseHandle(pi.hProcess);
3959 CloseHandle(pi.hThread);
3962 CloseHandle(pi.hProcess);
3963 CloseHandle(pi.hThread);
3965 (errmsg_internal("could not resume thread of unstarted process: error code %lu",
3971 * Queue a waiter for to signal when this child dies. The wait will be
3972 * handled automatically by an operating system thread pool.
3974 * Note: use malloc instead of palloc, since it needs to be thread-safe.
3975 * Struct will be free():d from the callback function that runs on a
3978 childinfo = malloc(sizeof(win32_deadchild_waitinfo));
3981 (errcode(ERRCODE_OUT_OF_MEMORY),
3982 errmsg("out of memory")));
3984 childinfo->procHandle = pi.hProcess;
3985 childinfo->procId = pi.dwProcessId;
3987 if (!RegisterWaitForSingleObject(&childinfo->waitHandle,
3989 pgwin32_deadchild_callback,
3992 WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD))
3994 (errmsg_internal("could not register process for wait: error code %lu",
3997 /* Don't close pi.hProcess here - the wait thread needs access to it */
3999 CloseHandle(pi.hThread);
4001 return pi.dwProcessId;
4007 * SubPostmasterMain -- Get the fork/exec'd process into a state equivalent
4008 * to what it would be if we'd simply forked on Unix, and then
4009 * dispatch to the appropriate place.
4011 * The first two command line arguments are expected to be "--forkFOO"
4012 * (where FOO indicates which postmaster child we are to become), and
4013 * the name of a variables file that we can read to load data that would
4014 * have been inherited by fork() on Unix. Remaining arguments go to the
4015 * subprocess FooMain() routine.
4018 SubPostmasterMain(int argc, char *argv[])
4022 /* Do this sooner rather than later... */
4023 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
4025 MyProcPid = getpid(); /* reset MyProcPid */
4027 MyStartTime = time(NULL);
4030 * make sure stderr is in binary mode before anything can possibly be
4031 * written to it, in case it's actually the syslogger pipe, so the pipe
4032 * chunking protocol isn't disturbed. Non-logpipe data gets translated on
4033 * redirection (e.g. via pg_ctl -l) anyway.
4036 _setmode(fileno(stderr), _O_BINARY);
4039 /* Lose the postmaster's on-exit routines (really a no-op) */
4042 /* In EXEC_BACKEND case we will not have inherited these settings */
4043 IsPostmasterEnvironment = true;
4044 whereToSendOutput = DestNone;
4046 /* Setup essential subsystems (to ensure elog() behaves sanely) */
4047 MemoryContextInit();
4048 InitializeGUCOptions();
4050 /* Read in the variables file */
4051 memset(&port, 0, sizeof(Port));
4052 read_backend_variables(argv[2], &port);
4055 * Set reference point for stack-depth checking
4060 * Set up memory area for GSS information. Mirrors the code in ConnCreate
4061 * for the non-exec case.
4063 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
4064 port.gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
4067 (errcode(ERRCODE_OUT_OF_MEMORY),
4068 errmsg("out of memory")));
4071 /* Check we got appropriate args */
4073 elog(FATAL, "invalid subpostmaster invocation");
4076 * If appropriate, physically re-attach to shared memory segment. We want
4077 * to do this before going any further to ensure that we can attach at the
4078 * same address the postmaster used.
4080 if (strcmp(argv[1], "--forkbackend") == 0 ||
4081 strcmp(argv[1], "--forkavlauncher") == 0 ||
4082 strcmp(argv[1], "--forkavworker") == 0 ||
4083 strcmp(argv[1], "--forkboot") == 0)
4084 PGSharedMemoryReAttach();
4086 /* autovacuum needs this set before calling InitProcess */
4087 if (strcmp(argv[1], "--forkavlauncher") == 0)
4088 AutovacuumLauncherIAm();
4089 if (strcmp(argv[1], "--forkavworker") == 0)
4090 AutovacuumWorkerIAm();
4093 * Start our win32 signal implementation. This has to be done after we
4094 * read the backend variables, because we need to pick up the signal pipe
4095 * from the parent process.
4098 pgwin32_signal_initialize();
4101 /* In EXEC_BACKEND case we will not have inherited these settings */
4103 PG_SETMASK(&BlockSig);
4105 /* Read in remaining GUC variables */
4106 read_nondefault_variables();
4109 * Reload any libraries that were preloaded by the postmaster. Since we
4110 * exec'd this process, those libraries didn't come along with us; but we
4111 * should load them into all child processes to be consistent with the
4112 * non-EXEC_BACKEND behavior.
4114 process_shared_preload_libraries();
4116 /* Run backend or appropriate child */
4117 if (strcmp(argv[1], "--forkbackend") == 0)
4119 Assert(argc == 3); /* shouldn't be any more args */
4121 /* Close the postmaster's sockets */
4122 ClosePostmasterPorts(false);
4125 * Need to reinitialize the SSL library in the backend, since the
4126 * context structures contain function pointers and cannot be passed
4127 * through the parameter file.
4129 * XXX should we do this in all child processes? For the moment it's
4130 * enough to do it in backend children.
4134 secure_initialize();
4138 * Perform additional initialization and collect startup packet.
4140 * We want to do this before InitProcess() for a couple of reasons: 1.
4141 * so that we aren't eating up a PGPROC slot while waiting on the
4142 * client. 2. so that if InitProcess() fails due to being out of
4143 * PGPROC slots, we have already initialized libpq and are able to
4144 * report the error to the client.
4146 BackendInitialize(&port);
4148 /* Restore basic shared memory pointers */
4149 InitShmemAccess(UsedShmemSegAddr);
4151 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
4155 * Attach process to shared data structures. If testing EXEC_BACKEND
4156 * on Linux, you must run this as root before starting the postmaster:
4158 * echo 0 >/proc/sys/kernel/randomize_va_space
4160 * This prevents a randomized stack base address that causes child
4161 * shared memory to be at a different address than the parent, making
4162 * it impossible to attached to shared memory. Return the value to
4163 * '1' when finished.
4165 CreateSharedMemoryAndSemaphores(false, 0);
4167 /* And run the backend */
4168 BackendRun(&port); /* does not return */
4170 if (strcmp(argv[1], "--forkboot") == 0)
4172 /* Close the postmaster's sockets */
4173 ClosePostmasterPorts(false);
4175 /* Restore basic shared memory pointers */
4176 InitShmemAccess(UsedShmemSegAddr);
4178 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
4179 InitAuxiliaryProcess();
4181 /* Attach process to shared data structures */
4182 CreateSharedMemoryAndSemaphores(false, 0);
4184 AuxiliaryProcessMain(argc - 2, argv + 2); /* does not return */
4186 if (strcmp(argv[1], "--forkavlauncher") == 0)
4188 /* Close the postmaster's sockets */
4189 ClosePostmasterPorts(false);
4191 /* Restore basic shared memory pointers */
4192 InitShmemAccess(UsedShmemSegAddr);
4194 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
4197 /* Attach process to shared data structures */
4198 CreateSharedMemoryAndSemaphores(false, 0);
4200 AutoVacLauncherMain(argc - 2, argv + 2); /* does not return */
4202 if (strcmp(argv[1], "--forkavworker") == 0)
4204 /* Close the postmaster's sockets */
4205 ClosePostmasterPorts(false);
4207 /* Restore basic shared memory pointers */
4208 InitShmemAccess(UsedShmemSegAddr);
4210 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
4213 /* Attach process to shared data structures */
4214 CreateSharedMemoryAndSemaphores(false, 0);
4216 AutoVacWorkerMain(argc - 2, argv + 2); /* does not return */
4218 if (strcmp(argv[1], "--forkarch") == 0)
4220 /* Close the postmaster's sockets */
4221 ClosePostmasterPorts(false);
4223 /* Do not want to attach to shared memory */
4225 PgArchiverMain(argc, argv); /* does not return */
4227 if (strcmp(argv[1], "--forkcol") == 0)
4229 /* Close the postmaster's sockets */
4230 ClosePostmasterPorts(false);
4232 /* Do not want to attach to shared memory */
4234 PgstatCollectorMain(argc, argv); /* does not return */
4236 if (strcmp(argv[1], "--forklog") == 0)
4238 /* Close the postmaster's sockets */
4239 ClosePostmasterPorts(true);
4241 /* Do not want to attach to shared memory */
4243 SysLoggerMain(argc, argv); /* does not return */
4246 abort(); /* shouldn't get here */
4248 #endif /* EXEC_BACKEND */
4252 * ExitPostmaster -- cleanup
4254 * Do NOT call exit() directly --- always go through here!
4257 ExitPostmaster(int status)
4259 /* should cleanup shared memory and kill all backends */
4262 * Not sure of the semantics here. When the Postmaster dies, should the
4263 * backends all be killed? probably not.
4265 * MUST -- vadim 05-10-1999
4272 * sigusr1_handler - handle signal conditions from child processes
4275 sigusr1_handler(SIGNAL_ARGS)
4277 int save_errno = errno;
4279 PG_SETMASK(&BlockSig);
4282 * RECOVERY_STARTED and BEGIN_HOT_STANDBY signals are ignored in
4283 * unexpected states. If the startup process quickly starts up, completes
4284 * recovery, exits, we might process the death of the startup process
4285 * first. We don't want to go back to recovery in that case.
4287 if (CheckPostmasterSignal(PMSIGNAL_RECOVERY_STARTED) &&
4288 pmState == PM_STARTUP)
4290 /* WAL redo has started. We're out of reinitialization. */
4294 * Crank up the background tasks. It doesn't matter if this fails,
4295 * we'll just try again later.
4297 Assert(CheckpointerPID == 0);
4298 CheckpointerPID = StartCheckpointer();
4299 Assert(BgWriterPID == 0);
4300 BgWriterPID = StartBackgroundWriter();
4302 pmState = PM_RECOVERY;
4304 if (CheckPostmasterSignal(PMSIGNAL_BEGIN_HOT_STANDBY) &&
4305 pmState == PM_RECOVERY)
4308 * Likewise, start other special children as needed.
4310 Assert(PgStatPID == 0);
4311 PgStatPID = pgstat_start();
4314 (errmsg("database system is ready to accept read only connections")));
4316 pmState = PM_HOT_STANDBY;
4319 if (CheckPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER) &&
4323 * Send SIGUSR1 to archiver process, to wake it up and begin archiving
4324 * next transaction log file.
4326 signal_child(PgArchPID, SIGUSR1);
4329 if (CheckPostmasterSignal(PMSIGNAL_ROTATE_LOGFILE) &&
4332 /* Tell syslogger to rotate logfile */
4333 signal_child(SysLoggerPID, SIGUSR1);
4336 if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER))
4339 * Start one iteration of the autovacuum daemon, even if autovacuuming
4340 * is nominally not enabled. This is so we can have an active defense
4341 * against transaction ID wraparound. We set a flag for the main loop
4342 * to do it rather than trying to do it here --- this is because the
4343 * autovac process itself may send the signal, and we want to handle
4344 * that by launching another iteration as soon as the current one
4347 start_autovac_launcher = true;
4350 if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER))
4352 /* The autovacuum launcher wants us to start a worker process. */
4353 StartAutovacuumWorker();
4356 if (CheckPostmasterSignal(PMSIGNAL_START_WALRECEIVER) &&
4357 WalReceiverPID == 0 &&
4358 (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
4359 pmState == PM_HOT_STANDBY || pmState == PM_WAIT_READONLY))
4361 /* Startup Process wants us to start the walreceiver process. */
4362 WalReceiverPID = StartWalReceiver();
4365 if (CheckPostmasterSignal(PMSIGNAL_ADVANCE_STATE_MACHINE) &&
4366 (pmState == PM_WAIT_BACKUP || pmState == PM_WAIT_BACKENDS))
4368 /* Advance postmaster's state machine */
4369 PostmasterStateMachine();
4372 if (CheckPromoteSignal() && StartupPID != 0 &&
4373 (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
4374 pmState == PM_HOT_STANDBY || pmState == PM_WAIT_READONLY))
4376 /* Tell startup process to finish recovery */
4377 signal_child(StartupPID, SIGUSR2);
4380 PG_SETMASK(&UnBlockSig);
4386 * SIGTERM or SIGQUIT while processing startup packet.
4387 * Clean up and exit(1).
4389 * XXX: possible future improvement: try to send a message indicating
4390 * why we are disconnecting. Problem is to be sure we don't block while
4391 * doing so, nor mess up SSL initialization. In practice, if the client
4392 * has wedged here, it probably couldn't do anything with the message anyway.
4395 startup_die(SIGNAL_ARGS)
4401 * Dummy signal handler
4403 * We use this for signals that we don't actually use in the postmaster,
4404 * but we do use in backends. If we were to SIG_IGN such signals in the
4405 * postmaster, then a newly started backend might drop a signal that arrives
4406 * before it's able to reconfigure its signal processing. (See notes in
4410 dummy_handler(SIGNAL_ARGS)
4415 * Timeout while processing startup packet.
4416 * As for startup_die(), we clean up and exit(1).
4419 StartupPacketTimeoutHandler(void)
4429 RandomSalt(char *md5Salt)
4434 * We use % 255, sacrificing one possible byte value, so as to ensure that
4435 * all bits of the random() value participate in the result. While at it,
4436 * add one to avoid generating any null bytes.
4438 rand = PostmasterRandom();
4439 md5Salt[0] = (rand % 255) + 1;
4440 rand = PostmasterRandom();
4441 md5Salt[1] = (rand % 255) + 1;
4442 rand = PostmasterRandom();
4443 md5Salt[2] = (rand % 255) + 1;
4444 rand = PostmasterRandom();
4445 md5Salt[3] = (rand % 255) + 1;
4452 PostmasterRandom(void)
4455 * Select a random seed at the time of first receiving a request.
4457 if (random_seed == 0)
4461 struct timeval random_stop_time;
4463 gettimeofday(&random_stop_time, NULL);
4466 * We are not sure how much precision is in tv_usec, so we swap
4467 * the high and low 16 bits of 'random_stop_time' and XOR them
4468 * with 'random_start_time'. On the off chance that the result is
4469 * 0, we loop until it isn't.
4471 random_seed = random_start_time.tv_usec ^
4472 ((random_stop_time.tv_usec << 16) |
4473 ((random_stop_time.tv_usec >> 16) & 0xffff));
4475 while (random_seed == 0);
4477 srandom(random_seed);
4484 * Count up number of child processes of specified types (dead_end chidren
4485 * are always excluded).
4488 CountChildren(int target)
4493 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
4495 Backend *bp = (Backend *) DLE_VAL(curr);
4501 * Since target == BACKEND_TYPE_ALL is the most common case, we test
4502 * it first and avoid touching shared memory for every child.
4504 if (target != BACKEND_TYPE_ALL)
4508 if (bp->is_autovacuum)
4509 child = BACKEND_TYPE_AUTOVAC;
4510 else if (IsPostmasterChildWalSender(bp->child_slot))
4511 child = BACKEND_TYPE_WALSND;
4513 child = BACKEND_TYPE_NORMAL;
4514 if (!(target & child))
4525 * StartChildProcess -- start an auxiliary process for the postmaster
4527 * xlop determines what kind of child will be started. All child types
4528 * initially go to AuxiliaryProcessMain, which will handle common setup.
4530 * Return value of StartChildProcess is subprocess' PID, or 0 if failed
4531 * to start subprocess.
4534 StartChildProcess(AuxProcType type)
4542 * Set up command-line arguments for subprocess
4544 av[ac++] = "postgres";
4547 av[ac++] = "--forkboot";
4548 av[ac++] = NULL; /* filled in by postmaster_forkexec */
4551 snprintf(typebuf, sizeof(typebuf), "-x%d", type);
4555 Assert(ac < lengthof(av));
4558 pid = postmaster_forkexec(ac, av);
4559 #else /* !EXEC_BACKEND */
4560 pid = fork_process();
4562 if (pid == 0) /* child */
4564 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
4566 /* Close the postmaster's sockets */
4567 ClosePostmasterPorts(false);
4569 /* Lose the postmaster's on-exit routines and port connections */
4572 /* Release postmaster's working memory context */
4573 MemoryContextSwitchTo(TopMemoryContext);
4574 MemoryContextDelete(PostmasterContext);
4575 PostmasterContext = NULL;
4577 AuxiliaryProcessMain(ac, av);
4580 #endif /* EXEC_BACKEND */
4584 /* in parent, fork failed */
4585 int save_errno = errno;
4590 case StartupProcess:
4592 (errmsg("could not fork startup process: %m")));
4594 case BgWriterProcess:
4596 (errmsg("could not fork background writer process: %m")));
4598 case CheckpointerProcess:
4600 (errmsg("could not fork checkpointer process: %m")));
4602 case WalWriterProcess:
4604 (errmsg("could not fork WAL writer process: %m")));
4606 case WalReceiverProcess:
4608 (errmsg("could not fork WAL receiver process: %m")));
4612 (errmsg("could not fork process: %m")));
4617 * fork failure is fatal during startup, but there's no need to choke
4618 * immediately if starting other child types fails.
4620 if (type == StartupProcess)
4626 * in parent, successful fork
4632 * StartAutovacuumWorker
4633 * Start an autovac worker process.
4635 * This function is here because it enters the resulting PID into the
4636 * postmaster's private backends list.
4638 * NB -- this code very roughly matches BackendStartup.
4641 StartAutovacuumWorker(void)
4646 * If not in condition to run a process, don't try, but handle it like a
4647 * fork failure. This does not normally happen, since the signal is only
4648 * supposed to be sent by autovacuum launcher when it's OK to do it, but
4649 * we have to check to avoid race-condition problems during DB state
4652 if (canAcceptConnections() == CAC_OK)
4654 bn = (Backend *) malloc(sizeof(Backend));
4658 * Compute the cancel key that will be assigned to this session.
4659 * We probably don't need cancel keys for autovac workers, but
4660 * we'd better have something random in the field to prevent
4661 * unfriendly people from sending cancels to them.
4663 MyCancelKey = PostmasterRandom();
4664 bn->cancel_key = MyCancelKey;
4666 /* Autovac workers are not dead_end and need a child slot */
4667 bn->dead_end = false;
4668 bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
4670 bn->pid = StartAutoVacWorker();
4673 bn->is_autovacuum = true;
4674 DLInitElem(&bn->elem, bn);
4675 DLAddHead(BackendList, &bn->elem);
4677 ShmemBackendArrayAdd(bn);
4684 * fork failed, fall through to report -- actual error message was
4685 * logged by StartAutoVacWorker
4687 (void) ReleasePostmasterChildSlot(bn->child_slot);
4692 (errcode(ERRCODE_OUT_OF_MEMORY),
4693 errmsg("out of memory")));
4697 * Report the failure to the launcher, if it's running. (If it's not, we
4698 * might not even be connected to shared memory, so don't try to call
4699 * AutoVacWorkerFailed.) Note that we also need to signal it so that it
4700 * responds to the condition, but we don't do that here, instead waiting
4701 * for ServerLoop to do it. This way we avoid a ping-pong signalling in
4702 * quick succession between the autovac launcher and postmaster in case
4705 if (AutoVacPID != 0)
4707 AutoVacWorkerFailed();
4708 avlauncher_needs_signal = true;
4713 * Create the opts file
4716 CreateOptsFile(int argc, char *argv[], char *fullprogname)
4721 #define OPTS_FILE "postmaster.opts"
4723 if ((fp = fopen(OPTS_FILE, "w")) == NULL)
4725 elog(LOG, "could not create file \"%s\": %m", OPTS_FILE);
4729 fprintf(fp, "%s", fullprogname);
4730 for (i = 1; i < argc; i++)
4731 fprintf(fp, " \"%s\"", argv[i]);
4736 elog(LOG, "could not write file \"%s\": %m", OPTS_FILE);
4745 * MaxLivePostmasterChildren
4747 * This reports the number of entries needed in per-child-process arrays
4748 * (the PMChildFlags array, and if EXEC_BACKEND the ShmemBackendArray).
4749 * These arrays include regular backends, autovac workers and walsenders,
4750 * but not special children nor dead_end children. This allows the arrays
4751 * to have a fixed maximum size, to wit the same too-many-children limit
4752 * enforced by canAcceptConnections(). The exact value isn't too critical
4753 * as long as it's more than MaxBackends.
4756 MaxLivePostmasterChildren(void)
4758 return 2 * MaxBackends;
4765 * The following need to be available to the save/restore_backend_variables
4766 * functions. They are marked NON_EXEC_STATIC in their home modules.
4768 extern slock_t *ShmemLock;
4769 extern LWLock *LWLockArray;
4770 extern slock_t *ProcStructLock;
4771 extern PGPROC *AuxiliaryProcs;
4772 extern PMSignalData *PMSignalState;
4773 extern pgsocket pgStatSock;
4774 extern pg_time_t first_syslogger_file_time;
4777 #define write_inheritable_socket(dest, src, childpid) ((*(dest) = (src)), true)
4778 #define read_inheritable_socket(dest, src) (*(dest) = *(src))
4780 static bool write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE child);
4781 static bool write_inheritable_socket(InheritableSocket *dest, SOCKET src,
4783 static void read_inheritable_socket(SOCKET *dest, InheritableSocket *src);
4787 /* Save critical backend variables into the BackendParameters struct */
4790 save_backend_variables(BackendParameters *param, Port *port)
4793 save_backend_variables(BackendParameters *param, Port *port,
4794 HANDLE childProcess, pid_t childPid)
4797 memcpy(¶m->port, port, sizeof(Port));
4798 if (!write_inheritable_socket(¶m->portsocket, port->sock, childPid))
4801 strlcpy(param->DataDir, DataDir, MAXPGPATH);
4803 memcpy(¶m->ListenSocket, &ListenSocket, sizeof(ListenSocket));
4805 param->MyCancelKey = MyCancelKey;
4806 param->MyPMChildSlot = MyPMChildSlot;
4808 param->UsedShmemSegID = UsedShmemSegID;
4809 param->UsedShmemSegAddr = UsedShmemSegAddr;
4811 param->ShmemLock = ShmemLock;
4812 param->ShmemVariableCache = ShmemVariableCache;
4813 param->ShmemBackendArray = ShmemBackendArray;
4815 param->LWLockArray = LWLockArray;
4816 param->ProcStructLock = ProcStructLock;
4817 param->ProcGlobal = ProcGlobal;
4818 param->AuxiliaryProcs = AuxiliaryProcs;
4819 param->PreparedXactProcs = PreparedXactProcs;
4820 param->PMSignalState = PMSignalState;
4821 if (!write_inheritable_socket(¶m->pgStatSock, pgStatSock, childPid))
4824 param->PostmasterPid = PostmasterPid;
4825 param->PgStartTime = PgStartTime;
4826 param->PgReloadTime = PgReloadTime;
4827 param->first_syslogger_file_time = first_syslogger_file_time;
4829 param->redirection_done = redirection_done;
4830 param->IsBinaryUpgrade = IsBinaryUpgrade;
4831 param->max_safe_fds = max_safe_fds;
4834 param->PostmasterHandle = PostmasterHandle;
4835 if (!write_duplicated_handle(¶m->initial_signal_pipe,
4836 pgwin32_create_signal_listener(childPid),
4840 memcpy(¶m->postmaster_alive_fds, &postmaster_alive_fds,
4841 sizeof(postmaster_alive_fds));
4844 memcpy(¶m->syslogPipe, &syslogPipe, sizeof(syslogPipe));
4846 strlcpy(param->my_exec_path, my_exec_path, MAXPGPATH);
4848 strlcpy(param->pkglib_path, pkglib_path, MAXPGPATH);
4850 strlcpy(param->ExtraOptions, ExtraOptions, MAXPGPATH);
4858 * Duplicate a handle for usage in a child process, and write the child
4859 * process instance of the handle to the parameter file.
4862 write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE childProcess)
4864 HANDLE hChild = INVALID_HANDLE_VALUE;
4866 if (!DuplicateHandle(GetCurrentProcess(),
4872 DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS))
4875 (errmsg_internal("could not duplicate handle to be written to backend parameter file: error code %lu",
4885 * Duplicate a socket for usage in a child process, and write the resulting
4886 * structure to the parameter file.
4887 * This is required because a number of LSPs (Layered Service Providers) very
4888 * common on Windows (antivirus, firewalls, download managers etc) break
4889 * straight socket inheritance.
4892 write_inheritable_socket(InheritableSocket *dest, SOCKET src, pid_t childpid)
4894 dest->origsocket = src;
4895 if (src != 0 && src != PGINVALID_SOCKET)
4898 if (WSADuplicateSocket(src, childpid, &dest->wsainfo) != 0)
4901 (errmsg("could not duplicate socket %d for use in backend: error code %d",
4902 (int) src, WSAGetLastError())));
4910 * Read a duplicate socket structure back, and get the socket descriptor.
4913 read_inheritable_socket(SOCKET *dest, InheritableSocket *src)
4917 if (src->origsocket == PGINVALID_SOCKET || src->origsocket == 0)
4919 /* Not a real socket! */
4920 *dest = src->origsocket;
4924 /* Actual socket, so create from structure */
4925 s = WSASocket(FROM_PROTOCOL_INFO,
4931 if (s == INVALID_SOCKET)
4933 write_stderr("could not create inherited socket: error code %d\n",
4940 * To make sure we don't get two references to the same socket, close
4941 * the original one. (This would happen when inheritance actually
4944 closesocket(src->origsocket);
4950 read_backend_variables(char *id, Port *port)
4952 BackendParameters param;
4955 /* Non-win32 implementation reads from file */
4959 fp = AllocateFile(id, PG_BINARY_R);
4962 write_stderr("could not read from backend variables file \"%s\": %s\n",
4963 id, strerror(errno));
4967 if (fread(¶m, sizeof(param), 1, fp) != 1)
4969 write_stderr("could not read from backend variables file \"%s\": %s\n",
4970 id, strerror(errno));
4976 if (unlink(id) != 0)
4978 write_stderr("could not remove file \"%s\": %s\n",
4979 id, strerror(errno));
4983 /* Win32 version uses mapped file */
4985 BackendParameters *paramp;
4988 paramHandle = (HANDLE) _atoi64(id);
4990 paramHandle = (HANDLE) atol(id);
4992 paramp = MapViewOfFile(paramHandle, FILE_MAP_READ, 0, 0, 0);
4995 write_stderr("could not map view of backend variables: error code %lu\n",
5000 memcpy(¶m, paramp, sizeof(BackendParameters));
5002 if (!UnmapViewOfFile(paramp))
5004 write_stderr("could not unmap view of backend variables: error code %lu\n",
5009 if (!CloseHandle(paramHandle))
5011 write_stderr("could not close handle to backend parameter variables: error code %lu\n",
5017 restore_backend_variables(¶m, port);
5020 /* Restore critical backend variables from the BackendParameters struct */
5022 restore_backend_variables(BackendParameters *param, Port *port)
5024 memcpy(port, ¶m->port, sizeof(Port));
5025 read_inheritable_socket(&port->sock, ¶m->portsocket);
5027 SetDataDir(param->DataDir);
5029 memcpy(&ListenSocket, ¶m->ListenSocket, sizeof(ListenSocket));
5031 MyCancelKey = param->MyCancelKey;
5032 MyPMChildSlot = param->MyPMChildSlot;
5034 UsedShmemSegID = param->UsedShmemSegID;
5035 UsedShmemSegAddr = param->UsedShmemSegAddr;
5037 ShmemLock = param->ShmemLock;
5038 ShmemVariableCache = param->ShmemVariableCache;
5039 ShmemBackendArray = param->ShmemBackendArray;
5041 LWLockArray = param->LWLockArray;
5042 ProcStructLock = param->ProcStructLock;
5043 ProcGlobal = param->ProcGlobal;
5044 AuxiliaryProcs = param->AuxiliaryProcs;
5045 PreparedXactProcs = param->PreparedXactProcs;
5046 PMSignalState = param->PMSignalState;
5047 read_inheritable_socket(&pgStatSock, ¶m->pgStatSock);
5049 PostmasterPid = param->PostmasterPid;
5050 PgStartTime = param->PgStartTime;
5051 PgReloadTime = param->PgReloadTime;
5052 first_syslogger_file_time = param->first_syslogger_file_time;
5054 redirection_done = param->redirection_done;
5055 IsBinaryUpgrade = param->IsBinaryUpgrade;
5056 max_safe_fds = param->max_safe_fds;
5059 PostmasterHandle = param->PostmasterHandle;
5060 pgwin32_initial_signal_pipe = param->initial_signal_pipe;
5062 memcpy(&postmaster_alive_fds, ¶m->postmaster_alive_fds,
5063 sizeof(postmaster_alive_fds));
5066 memcpy(&syslogPipe, ¶m->syslogPipe, sizeof(syslogPipe));
5068 strlcpy(my_exec_path, param->my_exec_path, MAXPGPATH);
5070 strlcpy(pkglib_path, param->pkglib_path, MAXPGPATH);
5072 strlcpy(ExtraOptions, param->ExtraOptions, MAXPGPATH);
5077 ShmemBackendArraySize(void)
5079 return mul_size(MaxLivePostmasterChildren(), sizeof(Backend));
5083 ShmemBackendArrayAllocation(void)
5085 Size size = ShmemBackendArraySize();
5087 ShmemBackendArray = (Backend *) ShmemAlloc(size);
5088 /* Mark all slots as empty */
5089 memset(ShmemBackendArray, 0, size);
5093 ShmemBackendArrayAdd(Backend *bn)
5095 /* The array slot corresponding to my PMChildSlot should be free */
5096 int i = bn->child_slot - 1;
5098 Assert(ShmemBackendArray[i].pid == 0);
5099 ShmemBackendArray[i] = *bn;
5103 ShmemBackendArrayRemove(Backend *bn)
5105 int i = bn->child_slot - 1;
5107 Assert(ShmemBackendArray[i].pid == bn->pid);
5108 /* Mark the slot as empty */
5109 ShmemBackendArray[i].pid = 0;
5111 #endif /* EXEC_BACKEND */
5117 * Subset implementation of waitpid() for Windows. We assume pid is -1
5118 * (that is, check all child processes) and options is WNOHANG (don't wait).
5121 waitpid(pid_t pid, int *exitstatus, int options)
5128 * Check if there are any dead children. If there are, return the pid of
5129 * the first one that died.
5131 if (GetQueuedCompletionStatus(win32ChildQueue, &dwd, &key, &ovl, 0))
5133 *exitstatus = (int) key;
5141 * Note! Code below executes on a thread pool! All operations must
5142 * be thread safe! Note that elog() and friends must *not* be used.
5145 pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
5147 win32_deadchild_waitinfo *childinfo = (win32_deadchild_waitinfo *) lpParameter;
5150 if (TimerOrWaitFired)
5151 return; /* timeout. Should never happen, since we use
5152 * INFINITE as timeout value. */
5155 * Remove handle from wait - required even though it's set to wait only
5158 UnregisterWaitEx(childinfo->waitHandle, NULL);
5160 if (!GetExitCodeProcess(childinfo->procHandle, &exitcode))
5163 * Should never happen. Inform user and set a fixed exitcode.
5165 write_stderr("could not read exit code for process\n");
5169 if (!PostQueuedCompletionStatus(win32ChildQueue, childinfo->procId, (ULONG_PTR) exitcode, NULL))
5170 write_stderr("could not post child completion status\n");
5173 * Handle is per-process, so we close it here instead of in the
5174 * originating thread
5176 CloseHandle(childinfo->procHandle);
5179 * Free struct that was allocated before the call to
5180 * RegisterWaitForSingleObject()
5184 /* Queue SIGCHLD signal */
5185 pg_queue_signal(SIGCHLD);
5190 * Initialize one and only handle for monitoring postmaster death.
5192 * Called once in the postmaster, so that child processes can subsequently
5193 * monitor if their parent is dead.
5196 InitPostmasterDeathWatchHandle(void)
5201 * Create a pipe. Postmaster holds the write end of the pipe open
5202 * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
5203 * the read file descriptor to select() to wake up in case postmaster
5204 * dies, or check for postmaster death with a (read() == 0). Children must
5205 * close the write end as soon as possible after forking, because EOF
5206 * won't be signaled in the read end until all processes have closed the
5207 * write fd. That is taken care of in ClosePostmasterPorts().
5209 Assert(MyProcPid == PostmasterPid);
5210 if (pipe(postmaster_alive_fds))
5212 (errcode_for_file_access(),
5213 errmsg_internal("could not create pipe to monitor postmaster death: %m")));
5216 * Set O_NONBLOCK to allow testing for the fd's presence with a read()
5219 if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK))
5221 (errcode_for_socket_access(),
5222 errmsg_internal("could not set postmaster death monitoring pipe to non-blocking mode: %m")));
5226 * On Windows, we use a process handle for the same purpose.
5228 if (DuplicateHandle(GetCurrentProcess(),
5229 GetCurrentProcess(),
5230 GetCurrentProcess(),
5234 DUPLICATE_SAME_ACCESS) == 0)
5236 (errmsg_internal("could not duplicate postmaster handle: error code %lu",