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 */
161 char *ListenAddresses;
164 * ReservedBackends is the number of backends reserved for superuser use.
165 * This number is taken out of the pool size given by MaxBackends so
166 * number of backend slots available to non-superusers is
167 * (MaxBackends - ReservedBackends). Note what this really means is
168 * "if there are <= ReservedBackends connections available, only superusers
169 * can make new connections" --- pre-existing superuser connections don't
170 * count against the limit.
172 int ReservedBackends;
174 /* The socket(s) we're listening to. */
176 static pgsocket ListenSocket[MAXLISTEN];
179 * Set by the -o option
181 static char ExtraOptions[MAXPGPATH];
184 * These globals control the behavior of the postmaster in case some
185 * backend dumps core. Normally, it kills all peers of the dead backend
186 * and reinitializes shared memory. By specifying -s or -n, we can have
187 * the postmaster stop (rather than kill) peers and not reinitialize
188 * shared data structures. (Reinit is currently dead code, though.)
190 static bool Reinit = true;
191 static int SendStop = false;
193 /* still more option variables */
194 bool EnableSSL = false;
196 int PreAuthDelay = 0;
197 int AuthenticationTimeout = 60;
199 bool log_hostname; /* for ps display and logging */
200 bool Log_connections = false;
201 bool Db_user_namespace = false;
203 bool enable_bonjour = false;
205 bool restart_after_crash = true;
207 char *output_config_variable = NULL;
209 /* PIDs of special child processes; 0 when not running */
210 static pid_t StartupPID = 0,
220 /* Startup/shutdown state */
222 #define SmartShutdown 1
223 #define FastShutdown 2
225 static int Shutdown = NoShutdown;
227 static bool FatalError = false; /* T if recovering from backend crash */
228 static bool RecoveryError = false; /* T if WAL recovery failed */
231 * We use a simple state machine to control startup, shutdown, and
232 * crash recovery (which is rather like shutdown followed by startup).
234 * After doing all the postmaster initialization work, we enter PM_STARTUP
235 * state and the startup process is launched. The startup process begins by
236 * reading the control file and other preliminary initialization steps.
237 * In a normal startup, or after crash recovery, the startup process exits
238 * with exit code 0 and we switch to PM_RUN state. However, archive recovery
239 * is handled specially since it takes much longer and we would like to support
240 * hot standby during archive recovery.
242 * When the startup process is ready to start archive recovery, it signals the
243 * postmaster, and we switch to PM_RECOVERY state. The background writer and
244 * checkpointer are launched, while the startup process continues applying WAL.
245 * If Hot Standby is enabled, then, after reaching a consistent point in WAL
246 * redo, startup process signals us again, and we switch to PM_HOT_STANDBY
247 * state and begin accepting connections to perform read-only queries. When
248 * archive recovery is finished, the startup process exits with exit code 0
249 * and we switch to PM_RUN state.
251 * Normal child backends can only be launched when we are in PM_RUN or
252 * PM_HOT_STANDBY state. (We also allow launch of normal
253 * child backends in PM_WAIT_BACKUP state, but only for superusers.)
254 * In other states we handle connection requests by launching "dead_end"
255 * child processes, which will simply send the client an error message and
256 * quit. (We track these in the BackendList so that we can know when they
257 * are all gone; this is important because they're still connected to shared
258 * memory, and would interfere with an attempt to destroy the shmem segment,
259 * possibly leading to SHMALL failure when we try to make a new one.)
260 * In PM_WAIT_DEAD_END state we are waiting for all the dead_end children
261 * to drain out of the system, and therefore stop accepting connection
262 * requests at all until the last existing child has quit (which hopefully
263 * will not be very long).
265 * Notice that this state variable does not distinguish *why* we entered
266 * states later than PM_RUN --- Shutdown and FatalError must be consulted
267 * to find that out. FatalError is never true in PM_RECOVERY_* or PM_RUN
268 * states, nor in PM_SHUTDOWN states (because we don't enter those states
269 * when trying to recover from a crash). It can be true in PM_STARTUP state,
270 * because we don't clear it until we've successfully started WAL redo.
271 * Similarly, RecoveryError means that we have crashed during recovery, and
272 * should not try to restart.
276 PM_INIT, /* postmaster starting */
277 PM_STARTUP, /* waiting for startup subprocess */
278 PM_RECOVERY, /* in archive recovery mode */
279 PM_HOT_STANDBY, /* in hot standby mode */
280 PM_RUN, /* normal "database is alive" state */
281 PM_WAIT_BACKUP, /* waiting for online backup mode to end */
282 PM_WAIT_READONLY, /* waiting for read only backends to exit */
283 PM_WAIT_BACKENDS, /* waiting for live backends to exit */
284 PM_SHUTDOWN, /* waiting for checkpointer to do shutdown
286 PM_SHUTDOWN_2, /* waiting for archiver and walsenders to
288 PM_WAIT_DEAD_END, /* waiting for dead_end children to exit */
289 PM_NO_CHILDREN /* all important children have exited */
292 static PMState pmState = PM_INIT;
294 static bool ReachedNormalRunning = false; /* T if we've reached PM_RUN */
296 bool ClientAuthInProgress = false; /* T during new-client
299 bool redirection_done = false; /* stderr redirected for syslogger? */
301 /* received START_AUTOVAC_LAUNCHER signal */
302 static volatile sig_atomic_t start_autovac_launcher = false;
304 /* the launcher needs to be signalled to communicate some condition */
305 static volatile bool avlauncher_needs_signal = false;
308 * State for assigning random salts and cancel keys.
309 * Also, the global MyCancelKey passes the cancel key assigned to a given
310 * backend from the postmaster to that backend (via fork).
312 static unsigned int random_seed = 0;
313 static struct timeval random_start_time;
319 #ifdef HAVE_INT_OPTRESET
320 extern int optreset; /* might not be declared by system headers */
324 static DNSServiceRef bonjour_sdref = NULL;
328 * postmaster.c - function prototypes
330 static void getInstallationPaths(const char *argv0);
331 static void checkDataDir(void);
332 static Port *ConnCreate(int serverFd);
333 static void ConnFree(Port *port);
334 static void reset_shared(int port);
335 static void SIGHUP_handler(SIGNAL_ARGS);
336 static void pmdie(SIGNAL_ARGS);
337 static void reaper(SIGNAL_ARGS);
338 static void sigusr1_handler(SIGNAL_ARGS);
339 static void startup_die(SIGNAL_ARGS);
340 static void dummy_handler(SIGNAL_ARGS);
341 static void StartupPacketTimeoutHandler(void);
342 static void CleanupBackend(int pid, int exitstatus);
343 static void HandleChildCrash(int pid, int exitstatus, const char *procname);
344 static void LogChildExit(int lev, const char *procname,
345 int pid, int exitstatus);
346 static void PostmasterStateMachine(void);
347 static void BackendInitialize(Port *port);
348 static void BackendRun(Port *port) __attribute__((noreturn));
349 static void ExitPostmaster(int status) __attribute__((noreturn));
350 static int ServerLoop(void);
351 static int BackendStartup(Port *port);
352 static int ProcessStartupPacket(Port *port, bool SSLdone);
353 static void processCancelRequest(Port *port, void *pkt);
354 static int initMasks(fd_set *rmask);
355 static void report_fork_failure_to_client(Port *port, int errnum);
356 static CAC_state canAcceptConnections(void);
357 static long PostmasterRandom(void);
358 static void RandomSalt(char *md5Salt);
359 static void signal_child(pid_t pid, int signal);
360 static bool SignalSomeChildren(int signal, int targets);
362 #define SignalChildren(sig) SignalSomeChildren(sig, BACKEND_TYPE_ALL)
365 * Possible types of a backend. These are OR-able request flag bits
366 * for SignalSomeChildren() and CountChildren().
368 #define BACKEND_TYPE_NORMAL 0x0001 /* normal backend */
369 #define BACKEND_TYPE_AUTOVAC 0x0002 /* autovacuum worker process */
370 #define BACKEND_TYPE_WALSND 0x0004 /* walsender process */
371 #define BACKEND_TYPE_ALL 0x0007 /* OR of all the above */
373 static int CountChildren(int target);
374 static bool CreateOptsFile(int argc, char *argv[], char *fullprogname);
375 static pid_t StartChildProcess(AuxProcType type);
376 static void StartAutovacuumWorker(void);
377 static void InitPostmasterDeathWatchHandle(void);
382 #define WNOHANG 0 /* ignored, so any integer value will do */
384 static pid_t waitpid(pid_t pid, int *exitstatus, int options);
385 static void WINAPI pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired);
387 static HANDLE win32ChildQueue;
394 } win32_deadchild_waitinfo;
397 static pid_t backend_forkexec(Port *port);
398 static pid_t internal_forkexec(int argc, char *argv[], Port *port);
400 /* Type for a socket that can be inherited to a client process */
404 SOCKET origsocket; /* Original socket value, or PGINVALID_SOCKET
406 WSAPROTOCOL_INFO wsainfo;
409 typedef int InheritableSocket;
412 typedef struct LWLock LWLock; /* ugly kluge */
415 * Structure contains all variables passed to exec:ed backends
420 InheritableSocket portsocket;
421 char DataDir[MAXPGPATH];
422 pgsocket ListenSocket[MAXLISTEN];
426 unsigned long UsedShmemSegID;
428 HANDLE UsedShmemSegID;
430 void *UsedShmemSegAddr;
432 VariableCache ShmemVariableCache;
433 Backend *ShmemBackendArray;
435 slock_t *ProcStructLock;
436 PROC_HDR *ProcGlobal;
437 PGPROC *AuxiliaryProcs;
438 PGPROC *PreparedXactProcs;
439 PMSignalData *PMSignalState;
440 InheritableSocket pgStatSock;
442 TimestampTz PgStartTime;
443 TimestampTz PgReloadTime;
444 bool redirection_done;
445 bool IsBinaryUpgrade;
448 HANDLE PostmasterHandle;
449 HANDLE initial_signal_pipe;
450 HANDLE syslogPipe[2];
452 int postmaster_alive_fds[2];
455 char my_exec_path[MAXPGPATH];
456 char pkglib_path[MAXPGPATH];
457 char ExtraOptions[MAXPGPATH];
460 static void read_backend_variables(char *id, Port *port);
461 static void restore_backend_variables(BackendParameters *param, Port *port);
464 static bool save_backend_variables(BackendParameters *param, Port *port);
466 static bool save_backend_variables(BackendParameters *param, Port *port,
467 HANDLE childProcess, pid_t childPid);
470 static void ShmemBackendArrayAdd(Backend *bn);
471 static void ShmemBackendArrayRemove(Backend *bn);
472 #endif /* EXEC_BACKEND */
474 #define StartupDataBase() StartChildProcess(StartupProcess)
475 #define StartBackgroundWriter() StartChildProcess(BgWriterProcess)
476 #define StartCheckpointer() StartChildProcess(CheckpointerProcess)
477 #define StartWalWriter() StartChildProcess(WalWriterProcess)
478 #define StartWalReceiver() StartChildProcess(WalReceiverProcess)
480 /* Macros to check exit status of a child process */
481 #define EXIT_STATUS_0(st) ((st) == 0)
482 #define EXIT_STATUS_1(st) (WIFEXITED(st) && WEXITSTATUS(st) == 1)
486 * File descriptors for pipe used to monitor if postmaster is alive.
487 * First is POSTMASTER_FD_WATCH, second is POSTMASTER_FD_OWN.
489 int postmaster_alive_fds[2] = {-1, -1};
491 /* Process handle of postmaster used for the same purpose on Windows */
492 HANDLE PostmasterHandle;
496 * Postmaster main entry point
499 PostmasterMain(int argc, char *argv[])
503 char *userDoption = NULL;
504 bool listen_addr_saved = false;
507 MyProcPid = PostmasterPid = getpid();
509 MyStartTime = time(NULL);
511 IsPostmasterEnvironment = true;
514 * for security, no dir or file created can be group or other accessible
516 umask(S_IRWXG | S_IRWXO);
519 * Fire up essential subsystems: memory management
524 * By default, palloc() requests in the postmaster will be allocated in
525 * the PostmasterContext, which is space that can be recycled by backends.
526 * Allocated data that needs to be available to backends should be
527 * allocated in TopMemoryContext.
529 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
531 ALLOCSET_DEFAULT_MINSIZE,
532 ALLOCSET_DEFAULT_INITSIZE,
533 ALLOCSET_DEFAULT_MAXSIZE);
534 MemoryContextSwitchTo(PostmasterContext);
536 /* Initialize paths to installation files */
537 getInstallationPaths(argv[0]);
542 InitializeGUCOptions();
547 * Parse command-line options. CAUTION: keep this in sync with
548 * tcop/postgres.c (the option sets should not conflict) and with the
549 * common help() function in main/main.c.
551 while ((opt = getopt(argc, argv, "A:B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:W:-:")) != -1)
556 SetConfigOption("debug_assertions", optarg, PGC_POSTMASTER, PGC_S_ARGV);
560 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
564 /* Undocumented flag used for binary upgrades */
565 IsBinaryUpgrade = true;
569 output_config_variable = optarg;
573 userDoption = optarg;
577 set_debug_options(atoi(optarg), PGC_POSTMASTER, PGC_S_ARGV);
581 SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
585 SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
589 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
593 if (!set_plan_disabling_options(optarg, PGC_POSTMASTER, PGC_S_ARGV))
595 write_stderr("%s: invalid argument for option -f: \"%s\"\n",
602 SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
606 SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
610 /* only used by interactive backend */
614 SetConfigOption("unix_socket_directory", optarg, PGC_POSTMASTER, PGC_S_ARGV);
618 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
622 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
626 /* Don't reinit shared mem after abnormal exit */
631 SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
635 /* Other options to pass to the backend on the command line */
636 snprintf(ExtraOptions + strlen(ExtraOptions),
637 sizeof(ExtraOptions) - strlen(ExtraOptions),
642 SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
646 SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
650 /* only used by single-user backend */
654 SetConfigOption("work_mem", optarg, PGC_POSTMASTER, PGC_S_ARGV);
658 SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
664 * In the event that some backend dumps core, send SIGSTOP,
665 * rather than SIGQUIT, to all its peers. This lets the wily
666 * post_hacker collect core dumps from everyone.
673 const char *tmp = get_stats_option_name(optarg);
677 SetConfigOption(tmp, "true", PGC_POSTMASTER, PGC_S_ARGV);
681 write_stderr("%s: invalid argument for option -t: \"%s\"\n",
689 SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
698 ParseLongOption(optarg, &name, &value);
703 (errcode(ERRCODE_SYNTAX_ERROR),
704 errmsg("--%s requires a value",
708 (errcode(ERRCODE_SYNTAX_ERROR),
709 errmsg("-c %s requires a value",
713 SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
721 write_stderr("Try \"%s --help\" for more information.\n",
728 * Postmaster accepts no non-option switch arguments.
732 write_stderr("%s: invalid argument: \"%s\"\n",
733 progname, argv[optind]);
734 write_stderr("Try \"%s --help\" for more information.\n",
740 * Locate the proper configuration files and data directory, and read
741 * postgresql.conf for the first time.
743 if (!SelectConfigFiles(userDoption, progname))
746 if (output_config_variable != NULL)
749 * permission is handled because the user is reading inside the data
752 puts(GetConfigOption(output_config_variable, false, false));
756 /* Verify that DataDir looks reasonable */
759 /* And switch working directory into it */
763 * Check for invalid combinations of GUC settings.
765 if (ReservedBackends >= MaxBackends)
767 write_stderr("%s: superuser_reserved_connections must be less than max_connections\n", progname);
770 if (XLogArchiveMode && wal_level == WAL_LEVEL_MINIMAL)
772 (errmsg("WAL archival (archive_mode=on) requires wal_level \"archive\" or \"hot_standby\"")));
773 if (max_wal_senders > 0 && wal_level == WAL_LEVEL_MINIMAL)
775 (errmsg("WAL streaming (max_wal_senders > 0) requires wal_level \"archive\" or \"hot_standby\"")));
778 * Other one-time internal sanity checks can go here, if they are fast.
779 * (Put any slow processing further down, after postmaster.pid creation.)
781 if (!CheckDateTokenTables())
783 write_stderr("%s: invalid datetoken tables, please fix\n", progname);
788 * Now that we are done processing the postmaster arguments, reset
789 * getopt(3) library so that it will work correctly in subprocesses.
792 #ifdef HAVE_INT_OPTRESET
793 optreset = 1; /* some systems need this too */
796 /* For debugging: display postmaster environment */
798 extern char **environ;
802 (errmsg_internal("%s: PostmasterMain: initial environment dump:",
805 (errmsg_internal("-----------------------------------------")));
806 for (p = environ; *p; ++p)
808 (errmsg_internal("\t%s", *p)));
810 (errmsg_internal("-----------------------------------------")));
814 * Create lockfile for data directory.
816 * We want to do this before we try to grab the input sockets, because the
817 * data directory interlock is more reliable than the socket-file
818 * interlock (thanks to whoever decided to put socket files in /tmp :-().
819 * For the same reason, it's best to grab the TCP socket(s) before the
822 CreateDataDirLockFile(true);
825 * Initialize SSL library, if specified.
833 * process any libraries that should be preloaded at postmaster start
835 process_shared_preload_libraries();
838 * Establish input sockets.
840 for (i = 0; i < MAXLISTEN; i++)
841 ListenSocket[i] = PGINVALID_SOCKET;
850 /* Need a modifiable copy of ListenAddresses */
851 rawstring = pstrdup(ListenAddresses);
853 /* Parse string into list of identifiers */
854 if (!SplitIdentifierString(rawstring, ',', &elemlist))
856 /* syntax error in list */
858 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
859 errmsg("invalid list syntax for \"listen_addresses\"")));
864 char *curhost = (char *) lfirst(l);
866 if (strcmp(curhost, "*") == 0)
867 status = StreamServerPort(AF_UNSPEC, NULL,
868 (unsigned short) PostPortNumber,
870 ListenSocket, MAXLISTEN);
872 status = StreamServerPort(AF_UNSPEC, curhost,
873 (unsigned short) PostPortNumber,
875 ListenSocket, MAXLISTEN);
877 if (status == STATUS_OK)
880 /* record the first successful host addr in lockfile */
881 if (!listen_addr_saved)
883 AddToDataDirLockFile(LOCK_FILE_LINE_LISTEN_ADDR, curhost);
884 listen_addr_saved = true;
889 (errmsg("could not create listen socket for \"%s\"",
893 if (!success && list_length(elemlist))
895 (errmsg("could not create any TCP/IP sockets")));
902 /* Register for Bonjour only if we opened TCP socket(s) */
903 if (enable_bonjour && ListenSocket[0] != PGINVALID_SOCKET)
905 DNSServiceErrorType err;
908 * We pass 0 for interface_index, which will result in registering on
909 * all "applicable" interfaces. It's not entirely clear from the
910 * DNS-SD docs whether this would be appropriate if we have bound to
911 * just a subset of the available network interfaces.
913 err = DNSServiceRegister(&bonjour_sdref,
920 htons(PostPortNumber),
925 if (err != kDNSServiceErr_NoError)
926 elog(LOG, "DNSServiceRegister() failed: error code %ld",
930 * We don't bother to read the mDNS daemon's reply, and we expect that
931 * it will automatically terminate our registration when the socket is
932 * closed at postmaster termination. So there's nothing more to be
933 * done here. However, the bonjour_sdref is kept around so that
934 * forked children can close their copies of the socket.
939 #ifdef HAVE_UNIX_SOCKETS
940 status = StreamServerPort(AF_UNIX, NULL,
941 (unsigned short) PostPortNumber,
943 ListenSocket, MAXLISTEN);
944 if (status != STATUS_OK)
946 (errmsg("could not create Unix-domain socket")));
950 * check that we have some socket to listen on
952 if (ListenSocket[0] == PGINVALID_SOCKET)
954 (errmsg("no socket created for listening")));
957 * If no valid TCP ports, write an empty line for listen address,
958 * indicating the Unix socket must be used. Note that this line is not
959 * added to the lock file until there is a socket backing it.
961 if (!listen_addr_saved)
962 AddToDataDirLockFile(LOCK_FILE_LINE_LISTEN_ADDR, "");
965 * Set up shared memory and semaphores.
967 reset_shared(PostPortNumber);
970 * Estimate number of openable files. This must happen after setting up
971 * semaphores, because on some platforms semaphores count as open files.
976 * Set reference point for stack-depth checking.
981 * Initialize the list of active backends.
983 BackendList = DLNewList();
986 * Initialize pipe (or process handle on Windows) that allows children to
987 * wake up from sleep on postmaster death.
989 InitPostmasterDeathWatchHandle();
994 * Initialize I/O completion port used to deliver list of dead children.
996 win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
997 if (win32ChildQueue == NULL)
999 (errmsg("could not create I/O completion port for child queue")));
1003 * Record postmaster options. We delay this till now to avoid recording
1004 * bogus options (eg, NBuffers too high for available memory).
1006 if (!CreateOptsFile(argc, argv, my_exec_path))
1010 /* Write out nondefault GUC settings for child processes to use */
1011 write_nondefault_variables(PGC_POSTMASTER);
1015 * Write the external PID file if requested
1017 if (external_pid_file)
1019 FILE *fpidfile = fopen(external_pid_file, "w");
1023 fprintf(fpidfile, "%d\n", MyProcPid);
1025 /* Should we remove the pid file on postmaster exit? */
1027 /* Make PID file world readable */
1028 if (chmod(external_pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) != 0)
1029 write_stderr("%s: could not change permissions of external PID file \"%s\": %s\n",
1030 progname, external_pid_file, strerror(errno));
1033 write_stderr("%s: could not write external PID file \"%s\": %s\n",
1034 progname, external_pid_file, strerror(errno));
1038 * Set up signal handlers for the postmaster process.
1040 * CAUTION: when changing this list, check for side-effects on the signal
1041 * handling setup of child processes. See tcop/postgres.c,
1042 * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/walwriter.c,
1043 * postmaster/autovacuum.c, postmaster/pgarch.c, postmaster/pgstat.c,
1044 * postmaster/syslogger.c and postmaster/checkpointer.c.
1047 PG_SETMASK(&BlockSig);
1049 pqsignal(SIGHUP, SIGHUP_handler); /* reread config file and have
1050 * children do same */
1051 pqsignal(SIGINT, pmdie); /* send SIGTERM and shut down */
1052 pqsignal(SIGQUIT, pmdie); /* send SIGQUIT and die */
1053 pqsignal(SIGTERM, pmdie); /* wait for children and shut down */
1054 pqsignal(SIGALRM, SIG_IGN); /* ignored */
1055 pqsignal(SIGPIPE, SIG_IGN); /* ignored */
1056 pqsignal(SIGUSR1, sigusr1_handler); /* message from child process */
1057 pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
1058 pqsignal(SIGCHLD, reaper); /* handle child termination */
1059 pqsignal(SIGTTIN, SIG_IGN); /* ignored */
1060 pqsignal(SIGTTOU, SIG_IGN); /* ignored */
1061 /* ignore SIGXFSZ, so that ulimit violations work like disk full */
1063 pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
1067 * If enabled, start up syslogger collection subprocess
1069 SysLoggerPID = SysLogger_Start();
1072 * Reset whereToSendOutput from DestDebug (its starting state) to
1073 * DestNone. This stops ereport from sending log messages to stderr unless
1074 * Log_destination permits. We don't do this until the postmaster is
1075 * fully launched, since startup failures may as well be reported to
1078 whereToSendOutput = DestNone;
1081 * Initialize stats collection subsystem (this does NOT start the
1082 * collector process!)
1087 * Initialize the autovacuum subsystem (again, no process start yet)
1092 * Load configuration files for client authentication.
1097 * It makes no sense to continue if we fail to load the HBA file,
1098 * since there is no way to connect to the database in this case.
1101 (errmsg("could not load pg_hba.conf")));
1106 * Remove old temporary files. At this point there can be no other
1107 * Postgres processes running in this directory, so this should be safe.
1109 RemovePgTempFiles();
1112 * Remember postmaster startup time
1114 PgStartTime = GetCurrentTimestamp();
1115 /* PostmasterRandom wants its own copy */
1116 gettimeofday(&random_start_time, NULL);
1119 * We're ready to rock and roll...
1121 StartupPID = StartupDataBase();
1122 Assert(StartupPID != 0);
1123 pmState = PM_STARTUP;
1125 status = ServerLoop();
1128 * ServerLoop probably shouldn't ever return, but if it does, close down.
1130 ExitPostmaster(status != STATUS_OK);
1132 abort(); /* not reached */
1137 * Compute and check the directory paths to files that are part of the
1138 * installation (as deduced from the postgres executable's own location)
1141 getInstallationPaths(const char *argv0)
1145 /* Locate the postgres executable itself */
1146 if (find_my_exec(argv0, my_exec_path) < 0)
1147 elog(FATAL, "%s: could not locate my own executable path", argv0);
1150 /* Locate executable backend before we change working directory */
1151 if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1152 postgres_exec_path) < 0)
1154 (errmsg("%s: could not locate matching postgres executable",
1159 * Locate the pkglib directory --- this has to be set early in case we try
1160 * to load any modules from it in response to postgresql.conf entries.
1162 get_pkglib_path(my_exec_path, pkglib_path);
1165 * Verify that there's a readable directory there; otherwise the Postgres
1166 * installation is incomplete or corrupt. (A typical cause of this
1167 * failure is that the postgres executable has been moved or hardlinked to
1168 * some directory that's not a sibling of the installation lib/
1171 pdir = AllocateDir(pkglib_path);
1174 (errcode_for_file_access(),
1175 errmsg("could not open directory \"%s\": %m",
1177 errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1182 * XXX is it worth similarly checking the share/ directory? If the lib/
1183 * directory is there, then share/ probably is too.
1189 * Validate the proposed data directory
1194 char path[MAXPGPATH];
1196 struct stat stat_buf;
1200 if (stat(DataDir, &stat_buf) != 0)
1202 if (errno == ENOENT)
1204 (errcode_for_file_access(),
1205 errmsg("data directory \"%s\" does not exist",
1209 (errcode_for_file_access(),
1210 errmsg("could not read permissions of directory \"%s\": %m",
1214 /* eventual chdir would fail anyway, but let's test ... */
1215 if (!S_ISDIR(stat_buf.st_mode))
1217 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1218 errmsg("specified data directory \"%s\" is not a directory",
1222 * Check that the directory belongs to my userid; if not, reject.
1224 * This check is an essential part of the interlock that prevents two
1225 * postmasters from starting in the same directory (see CreateLockFile()).
1226 * Do not remove or weaken it.
1228 * XXX can we safely enable this check on Windows?
1230 #if !defined(WIN32) && !defined(__CYGWIN__)
1231 if (stat_buf.st_uid != geteuid())
1233 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1234 errmsg("data directory \"%s\" has wrong ownership",
1236 errhint("The server must be started by the user that owns the data directory.")));
1240 * Check if the directory has group or world access. If so, reject.
1242 * It would be possible to allow weaker constraints (for example, allow
1243 * group access) but we cannot make a general assumption that that is
1244 * okay; for example there are platforms where nearly all users
1245 * customarily belong to the same group. Perhaps this test should be
1248 * XXX temporarily suppress check when on Windows, because there may not
1249 * be proper support for Unix-y file permissions. Need to think of a
1250 * reasonable check to apply on Windows.
1252 #if !defined(WIN32) && !defined(__CYGWIN__)
1253 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
1255 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1256 errmsg("data directory \"%s\" has group or world access",
1258 errdetail("Permissions should be u=rwx (0700).")));
1261 /* Look for PG_VERSION before looking for pg_control */
1262 ValidatePgVersion(DataDir);
1264 snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1266 fp = AllocateFile(path, PG_BINARY_R);
1269 write_stderr("%s: could not find the database system\n"
1270 "Expected to find it in the directory \"%s\",\n"
1271 "but could not open file \"%s\": %s\n",
1272 progname, DataDir, path, strerror(errno));
1279 * Main idle loop of postmaster
1289 last_touch_time = time(NULL);
1291 nSockets = initMasks(&readmask);
1299 * Wait for a connection request to arrive.
1301 * We wait at most one minute, to ensure that the other background
1302 * tasks handled below get done even when no requests are arriving.
1304 * If we are in PM_WAIT_DEAD_END state, then we don't want to accept
1305 * any new connections, so we don't call select() at all; just sleep
1306 * for a little bit with signals unblocked.
1308 memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
1310 PG_SETMASK(&UnBlockSig);
1312 if (pmState == PM_WAIT_DEAD_END)
1314 pg_usleep(100000L); /* 100 msec seems reasonable */
1319 /* must set timeout each time; some OSes change it! */
1320 struct timeval timeout;
1322 timeout.tv_sec = 60;
1323 timeout.tv_usec = 0;
1325 selres = select(nSockets, &rmask, NULL, NULL, &timeout);
1329 * Block all signals until we wait again. (This makes it safe for our
1330 * signal handlers to do nontrivial work.)
1332 PG_SETMASK(&BlockSig);
1334 /* Now check the select() result */
1337 if (errno != EINTR && errno != EWOULDBLOCK)
1340 (errcode_for_socket_access(),
1341 errmsg("select() failed in postmaster: %m")));
1342 return STATUS_ERROR;
1347 * New connection pending on any of our sockets? If so, fork a child
1348 * process to deal with it.
1354 for (i = 0; i < MAXLISTEN; i++)
1356 if (ListenSocket[i] == PGINVALID_SOCKET)
1358 if (FD_ISSET(ListenSocket[i], &rmask))
1362 port = ConnCreate(ListenSocket[i]);
1365 BackendStartup(port);
1368 * We no longer need the open socket or port structure
1371 StreamClose(port->sock);
1378 /* If we have lost the log collector, try to start a new one */
1379 if (SysLoggerPID == 0 && Logging_collector)
1380 SysLoggerPID = SysLogger_Start();
1383 * If no background writer process is running, and we are not in a
1384 * state that prevents it, start one. It doesn't matter if this
1385 * fails, we'll just try again later. Likewise for the checkpointer.
1387 if (pmState == PM_RUN || pmState == PM_RECOVERY ||
1388 pmState == PM_HOT_STANDBY)
1390 if (CheckpointerPID == 0)
1391 CheckpointerPID = StartCheckpointer();
1392 if (BgWriterPID == 0)
1393 BgWriterPID = StartBackgroundWriter();
1397 * Likewise, if we have lost the walwriter process, try to start a new
1398 * one. But this is needed only in normal operation (else we cannot
1399 * be writing any new WAL).
1401 if (WalWriterPID == 0 && pmState == PM_RUN)
1402 WalWriterPID = StartWalWriter();
1405 * If we have lost the autovacuum launcher, try to start a new one. We
1406 * don't want autovacuum to run in binary upgrade mode because
1407 * autovacuum might update relfrozenxid for empty tables before the
1408 * physical files are put in place.
1410 if (!IsBinaryUpgrade && AutoVacPID == 0 &&
1411 (AutoVacuumingActive() || start_autovac_launcher) &&
1414 AutoVacPID = StartAutoVacLauncher();
1415 if (AutoVacPID != 0)
1416 start_autovac_launcher = false; /* signal processed */
1419 /* If we have lost the archiver, try to start a new one */
1420 if (XLogArchivingActive() && PgArchPID == 0 && pmState == PM_RUN)
1421 PgArchPID = pgarch_start();
1423 /* If we have lost the stats collector, try to start a new one */
1424 if (PgStatPID == 0 && pmState == PM_RUN)
1425 PgStatPID = pgstat_start();
1427 /* If we need to signal the autovacuum launcher, do so now */
1428 if (avlauncher_needs_signal)
1430 avlauncher_needs_signal = false;
1431 if (AutoVacPID != 0)
1432 kill(AutoVacPID, SIGUSR2);
1436 * Touch the socket and lock file every 58 minutes, to ensure that
1437 * they are not removed by overzealous /tmp-cleaning tasks. We assume
1438 * no one runs cleaners with cutoff times of less than an hour ...
1441 if (now - last_touch_time >= 58 * SECS_PER_MINUTE)
1444 TouchSocketLockFile();
1445 last_touch_time = now;
1452 * Initialise the masks for select() for the ports we are listening on.
1453 * Return the number of sockets to listen on.
1456 initMasks(fd_set *rmask)
1463 for (i = 0; i < MAXLISTEN; i++)
1465 int fd = ListenSocket[i];
1467 if (fd == PGINVALID_SOCKET)
1480 * Read a client's startup packet and do something according to it.
1482 * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
1483 * not return at all.
1485 * (Note that ereport(FATAL) stuff is sent to the client, so only use it
1486 * if that's what you want. Return STATUS_ERROR if you don't want to
1487 * send anything to the client, which would typically be appropriate
1488 * if we detect a communications failure.)
1491 ProcessStartupPacket(Port *port, bool SSLdone)
1495 ProtocolVersion proto;
1496 MemoryContext oldcontext;
1498 if (pq_getbytes((char *) &len, 4) == EOF)
1501 * EOF after SSLdone probably means the client didn't like our
1502 * response to NEGOTIATE_SSL_CODE. That's not an error condition, so
1503 * don't clutter the log with a complaint.
1507 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1508 errmsg("incomplete startup packet")));
1509 return STATUS_ERROR;
1515 if (len < (int32) sizeof(ProtocolVersion) ||
1516 len > MAX_STARTUP_PACKET_LENGTH)
1519 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1520 errmsg("invalid length of startup packet")));
1521 return STATUS_ERROR;
1525 * Allocate at least the size of an old-style startup packet, plus one
1526 * extra byte, and make sure all are zeroes. This ensures we will have
1527 * null termination of all strings, in both fixed- and variable-length
1530 if (len <= (int32) sizeof(StartupPacket))
1531 buf = palloc0(sizeof(StartupPacket) + 1);
1533 buf = palloc0(len + 1);
1535 if (pq_getbytes(buf, len) == EOF)
1538 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1539 errmsg("incomplete startup packet")));
1540 return STATUS_ERROR;
1544 * The first field is either a protocol version number or a special
1547 port->proto = proto = ntohl(*((ProtocolVersion *) buf));
1549 if (proto == CANCEL_REQUEST_CODE)
1551 processCancelRequest(port, buf);
1552 /* Not really an error, but we don't want to proceed further */
1553 return STATUS_ERROR;
1556 if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
1561 /* No SSL when disabled or on Unix sockets */
1562 if (!EnableSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
1565 SSLok = 'S'; /* Support for SSL */
1567 SSLok = 'N'; /* No support for SSL */
1571 if (send(port->sock, &SSLok, 1, 0) != 1)
1574 goto retry1; /* if interrupted, just retry */
1576 (errcode_for_socket_access(),
1577 errmsg("failed to send SSL negotiation response: %m")));
1578 return STATUS_ERROR; /* close the connection */
1582 if (SSLok == 'S' && secure_open_server(port) == -1)
1583 return STATUS_ERROR;
1585 /* regular startup packet, cancel, etc packet should follow... */
1586 /* but not another SSL negotiation request */
1587 return ProcessStartupPacket(port, true);
1590 /* Could add additional special packet types here */
1593 * Set FrontendProtocol now so that ereport() knows what format to send if
1594 * we fail during startup.
1596 FrontendProtocol = proto;
1598 /* Check we can handle the protocol the frontend is using. */
1600 if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
1601 PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
1602 (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
1603 PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
1605 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1606 errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
1607 PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
1608 PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST),
1609 PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST),
1610 PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))));
1613 * Now fetch parameters out of startup packet and save them into the Port
1614 * structure. All data structures attached to the Port struct must be
1615 * allocated in TopMemoryContext so that they will remain available in a
1616 * running backend (even after PostmasterContext is destroyed). We need
1617 * not worry about leaking this storage on failure, since we aren't in the
1618 * postmaster process anymore.
1620 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1622 if (PG_PROTOCOL_MAJOR(proto) >= 3)
1624 int32 offset = sizeof(ProtocolVersion);
1627 * Scan packet body for name/option pairs. We can assume any string
1628 * beginning within the packet body is null-terminated, thanks to
1629 * zeroing extra byte above.
1631 port->guc_options = NIL;
1633 while (offset < len)
1635 char *nameptr = ((char *) buf) + offset;
1639 if (*nameptr == '\0')
1640 break; /* found packet terminator */
1641 valoffset = offset + strlen(nameptr) + 1;
1642 if (valoffset >= len)
1643 break; /* missing value, will complain below */
1644 valptr = ((char *) buf) + valoffset;
1646 if (strcmp(nameptr, "database") == 0)
1647 port->database_name = pstrdup(valptr);
1648 else if (strcmp(nameptr, "user") == 0)
1649 port->user_name = pstrdup(valptr);
1650 else if (strcmp(nameptr, "options") == 0)
1651 port->cmdline_options = pstrdup(valptr);
1652 else if (strcmp(nameptr, "replication") == 0)
1654 if (!parse_bool(valptr, &am_walsender))
1656 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1657 errmsg("invalid value for boolean option \"replication\"")));
1661 /* Assume it's a generic GUC option */
1662 port->guc_options = lappend(port->guc_options,
1664 port->guc_options = lappend(port->guc_options,
1667 offset = valoffset + strlen(valptr) + 1;
1671 * If we didn't find a packet terminator exactly at the end of the
1672 * given packet length, complain.
1674 if (offset != len - 1)
1676 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1677 errmsg("invalid startup packet layout: expected terminator as last byte")));
1682 * Get the parameters from the old-style, fixed-width-fields startup
1683 * packet as C strings. The packet destination was cleared first so a
1684 * short packet has zeros silently added. We have to be prepared to
1685 * truncate the pstrdup result for oversize fields, though.
1687 StartupPacket *packet = (StartupPacket *) buf;
1689 port->database_name = pstrdup(packet->database);
1690 if (strlen(port->database_name) > sizeof(packet->database))
1691 port->database_name[sizeof(packet->database)] = '\0';
1692 port->user_name = pstrdup(packet->user);
1693 if (strlen(port->user_name) > sizeof(packet->user))
1694 port->user_name[sizeof(packet->user)] = '\0';
1695 port->cmdline_options = pstrdup(packet->options);
1696 if (strlen(port->cmdline_options) > sizeof(packet->options))
1697 port->cmdline_options[sizeof(packet->options)] = '\0';
1698 port->guc_options = NIL;
1701 /* Check a user name was given. */
1702 if (port->user_name == NULL || port->user_name[0] == '\0')
1704 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1705 errmsg("no PostgreSQL user name specified in startup packet")));
1707 /* The database defaults to the user name. */
1708 if (port->database_name == NULL || port->database_name[0] == '\0')
1709 port->database_name = pstrdup(port->user_name);
1711 if (Db_user_namespace)
1714 * If user@, it is a global user, remove '@'. We only want to do this
1715 * if there is an '@' at the end and no earlier in the user string or
1716 * they may fake as a local user of another database attaching to this
1719 if (strchr(port->user_name, '@') ==
1720 port->user_name + strlen(port->user_name) - 1)
1721 *strchr(port->user_name, '@') = '\0';
1724 /* Append '@' and dbname */
1727 db_user = palloc(strlen(port->user_name) +
1728 strlen(port->database_name) + 2);
1729 sprintf(db_user, "%s@%s", port->user_name, port->database_name);
1730 port->user_name = db_user;
1735 * Truncate given database and user names to length of a Postgres name.
1736 * This avoids lookup failures when overlength names are given.
1738 if (strlen(port->database_name) >= NAMEDATALEN)
1739 port->database_name[NAMEDATALEN - 1] = '\0';
1740 if (strlen(port->user_name) >= NAMEDATALEN)
1741 port->user_name[NAMEDATALEN - 1] = '\0';
1743 /* Walsender is not related to a particular database */
1745 port->database_name[0] = '\0';
1748 * Done putting stuff in TopMemoryContext.
1750 MemoryContextSwitchTo(oldcontext);
1753 * If we're going to reject the connection due to database state, say so
1754 * now instead of wasting cycles on an authentication exchange. (This also
1755 * allows a pg_ping utility to be written.)
1757 switch (port->canAcceptConnections)
1761 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1762 errmsg("the database system is starting up")));
1766 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1767 errmsg("the database system is shutting down")));
1771 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1772 errmsg("the database system is in recovery mode")));
1776 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
1777 errmsg("sorry, too many clients already")));
1779 case CAC_WAITBACKUP:
1780 /* OK for now, will check in InitPostgres */
1791 * The client has sent a cancel request packet, not a normal
1792 * start-a-new-connection packet. Perform the necessary processing.
1793 * Nothing is sent back to the client.
1796 processCancelRequest(Port *port, void *pkt)
1798 CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
1800 long cancelAuthCode;
1803 #ifndef EXEC_BACKEND
1809 backendPID = (int) ntohl(canc->backendPID);
1810 cancelAuthCode = (long) ntohl(canc->cancelAuthCode);
1813 * See if we have a matching backend. In the EXEC_BACKEND case, we can no
1814 * longer access the postmaster's own backend list, and must rely on the
1815 * duplicate array in shared memory.
1817 #ifndef EXEC_BACKEND
1818 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
1820 bp = (Backend *) DLE_VAL(curr);
1822 for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
1824 bp = (Backend *) &ShmemBackendArray[i];
1826 if (bp->pid == backendPID)
1828 if (bp->cancel_key == cancelAuthCode)
1830 /* Found a match; signal that backend to cancel current op */
1832 (errmsg_internal("processing cancel request: sending SIGINT to process %d",
1834 signal_child(bp->pid, SIGINT);
1837 /* Right PID, wrong key: no way, Jose */
1839 (errmsg("wrong key in cancel request for process %d",
1845 /* No matching backend */
1847 (errmsg("PID %d in cancel request did not match any process",
1852 * canAcceptConnections --- check to see if database state allows connections.
1855 canAcceptConnections(void)
1857 CAC_state result = CAC_OK;
1860 * Can't start backends when in startup/shutdown/inconsistent recovery
1863 * In state PM_WAIT_BACKUP only superusers can connect (this must be
1864 * allowed so that a superuser can end online backup mode); we return
1865 * CAC_WAITBACKUP code to indicate that this must be checked later. Note
1866 * that neither CAC_OK nor CAC_WAITBACKUP can safely be returned until we
1867 * have checked for too many children.
1869 if (pmState != PM_RUN)
1871 if (pmState == PM_WAIT_BACKUP)
1872 result = CAC_WAITBACKUP; /* allow superusers only */
1873 else if (Shutdown > NoShutdown)
1874 return CAC_SHUTDOWN; /* shutdown is pending */
1875 else if (!FatalError &&
1876 (pmState == PM_STARTUP ||
1877 pmState == PM_RECOVERY))
1878 return CAC_STARTUP; /* normal startup */
1879 else if (!FatalError &&
1880 pmState == PM_HOT_STANDBY)
1881 result = CAC_OK; /* connection OK during hot standby */
1883 return CAC_RECOVERY; /* else must be crash recovery */
1887 * Don't start too many children.
1889 * We allow more connections than we can have backends here because some
1890 * might still be authenticating; they might fail auth, or some existing
1891 * backend might exit before the auth cycle is completed. The exact
1892 * MaxBackends limit is enforced when a new backend tries to join the
1893 * shared-inval backend array.
1895 * The limit here must match the sizes of the per-child-process arrays;
1896 * see comments for MaxLivePostmasterChildren().
1898 if (CountChildren(BACKEND_TYPE_ALL) >= MaxLivePostmasterChildren())
1899 result = CAC_TOOMANY;
1906 * ConnCreate -- create a local connection data structure
1908 * Returns NULL on failure, other than out-of-memory which is fatal.
1911 ConnCreate(int serverFd)
1915 if (!(port = (Port *) calloc(1, sizeof(Port))))
1918 (errcode(ERRCODE_OUT_OF_MEMORY),
1919 errmsg("out of memory")));
1923 if (StreamConnection(serverFd, port) != STATUS_OK)
1925 if (port->sock >= 0)
1926 StreamClose(port->sock);
1932 * Precompute password salt values to use for this connection. It's
1933 * slightly annoying to do this long in advance of knowing whether we'll
1934 * need 'em or not, but we must do the random() calls before we fork, not
1935 * after. Else the postmaster's random sequence won't get advanced, and
1936 * all backends would end up using the same salt...
1938 RandomSalt(port->md5Salt);
1941 * Allocate GSSAPI specific state struct
1943 #ifndef EXEC_BACKEND
1944 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
1945 port->gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
1949 (errcode(ERRCODE_OUT_OF_MEMORY),
1950 errmsg("out of memory")));
1961 * ConnFree -- free a local connection data structure
1964 ConnFree(Port *conn)
1976 * ClosePostmasterPorts -- close all the postmaster's open sockets
1978 * This is called during child process startup to release file descriptors
1979 * that are not needed by that child process. The postmaster still has
1980 * them open, of course.
1982 * Note: we pass am_syslogger as a boolean because we don't want to set
1983 * the global variable yet when this is called.
1986 ClosePostmasterPorts(bool am_syslogger)
1993 * Close the write end of postmaster death watch pipe. It's important to
1994 * do this as early as possible, so that if postmaster dies, others won't
1995 * think that it's still running because we're holding the pipe open.
1997 if (close(postmaster_alive_fds[POSTMASTER_FD_OWN]))
1999 (errcode_for_file_access(),
2000 errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
2001 postmaster_alive_fds[POSTMASTER_FD_OWN] = -1;
2004 /* Close the listen sockets */
2005 for (i = 0; i < MAXLISTEN; i++)
2007 if (ListenSocket[i] != PGINVALID_SOCKET)
2009 StreamClose(ListenSocket[i]);
2010 ListenSocket[i] = PGINVALID_SOCKET;
2014 /* If using syslogger, close the read side of the pipe */
2018 if (syslogPipe[0] >= 0)
2019 close(syslogPipe[0]);
2023 CloseHandle(syslogPipe[0]);
2029 /* If using Bonjour, close the connection to the mDNS daemon */
2031 close(DNSServiceRefSockFD(bonjour_sdref));
2037 * reset_shared -- reset shared memory and semaphores
2040 reset_shared(int port)
2043 * Create or re-create shared memory and semaphores.
2045 * Note: in each "cycle of life" we will normally assign the same IPC keys
2046 * (if using SysV shmem and/or semas), since the port number is used to
2047 * determine IPC keys. This helps ensure that we will clean up dead IPC
2048 * objects if the postmaster crashes and is restarted.
2050 CreateSharedMemoryAndSemaphores(false, port);
2055 * SIGHUP -- reread config files, and tell children to do same
2058 SIGHUP_handler(SIGNAL_ARGS)
2060 int save_errno = errno;
2062 PG_SETMASK(&BlockSig);
2064 if (Shutdown <= SmartShutdown)
2067 (errmsg("received SIGHUP, reloading configuration files")));
2068 ProcessConfigFile(PGC_SIGHUP);
2069 SignalChildren(SIGHUP);
2070 if (StartupPID != 0)
2071 signal_child(StartupPID, SIGHUP);
2072 if (BgWriterPID != 0)
2073 signal_child(BgWriterPID, SIGHUP);
2074 if (CheckpointerPID != 0)
2075 signal_child(CheckpointerPID, SIGHUP);
2076 if (WalWriterPID != 0)
2077 signal_child(WalWriterPID, SIGHUP);
2078 if (WalReceiverPID != 0)
2079 signal_child(WalReceiverPID, SIGHUP);
2080 if (AutoVacPID != 0)
2081 signal_child(AutoVacPID, SIGHUP);
2083 signal_child(PgArchPID, SIGHUP);
2084 if (SysLoggerPID != 0)
2085 signal_child(SysLoggerPID, SIGHUP);
2087 signal_child(PgStatPID, SIGHUP);
2089 /* Reload authentication config files too */
2092 (errmsg("pg_hba.conf not reloaded")));
2097 /* Update the starting-point file for future children */
2098 write_nondefault_variables(PGC_SIGHUP);
2102 PG_SETMASK(&UnBlockSig);
2109 * pmdie -- signal handler for processing various postmaster signals.
2114 int save_errno = errno;
2116 PG_SETMASK(&BlockSig);
2119 (errmsg_internal("postmaster received signal %d",
2120 postgres_signal_arg)));
2122 switch (postgres_signal_arg)
2129 * Wait for children to end their work, then shut down.
2131 if (Shutdown >= SmartShutdown)
2133 Shutdown = SmartShutdown;
2135 (errmsg("received smart shutdown request")));
2137 if (pmState == PM_RUN || pmState == PM_RECOVERY ||
2138 pmState == PM_HOT_STANDBY || pmState == PM_STARTUP)
2140 /* autovacuum workers are told to shut down immediately */
2141 SignalSomeChildren(SIGTERM, BACKEND_TYPE_AUTOVAC);
2142 /* and the autovac launcher too */
2143 if (AutoVacPID != 0)
2144 signal_child(AutoVacPID, SIGTERM);
2145 /* and the bgwriter too */
2146 if (BgWriterPID != 0)
2147 signal_child(BgWriterPID, SIGTERM);
2148 /* and the walwriter too */
2149 if (WalWriterPID != 0)
2150 signal_child(WalWriterPID, SIGTERM);
2153 * If we're in recovery, we can't kill the startup process
2154 * right away, because at present doing so does not release
2155 * its locks. We might want to change this in a future
2156 * release. For the time being, the PM_WAIT_READONLY state
2157 * indicates that we're waiting for the regular (read only)
2158 * backends to die off; once they do, we'll kill the startup
2159 * and walreceiver processes.
2161 pmState = (pmState == PM_RUN) ?
2162 PM_WAIT_BACKUP : PM_WAIT_READONLY;
2166 * Now wait for online backup mode to end and backends to exit. If
2167 * that is already the case, PostmasterStateMachine will take the
2170 PostmasterStateMachine();
2178 * Abort all children with SIGTERM (rollback active transactions
2179 * and exit) and shut down when they are gone.
2181 if (Shutdown >= FastShutdown)
2183 Shutdown = FastShutdown;
2185 (errmsg("received fast shutdown request")));
2187 if (StartupPID != 0)
2188 signal_child(StartupPID, SIGTERM);
2189 if (BgWriterPID != 0)
2190 signal_child(BgWriterPID, SIGTERM);
2191 if (WalReceiverPID != 0)
2192 signal_child(WalReceiverPID, SIGTERM);
2193 if (pmState == PM_RECOVERY)
2196 * Only startup, bgwriter, and checkpointer should be active
2197 * in this state; we just signaled the first two, and we don't
2198 * want to kill checkpointer yet.
2200 pmState = PM_WAIT_BACKENDS;
2202 else if (pmState == PM_RUN ||
2203 pmState == PM_WAIT_BACKUP ||
2204 pmState == PM_WAIT_READONLY ||
2205 pmState == PM_WAIT_BACKENDS ||
2206 pmState == PM_HOT_STANDBY)
2209 (errmsg("aborting any active transactions")));
2210 /* shut down all backends and autovac workers */
2211 SignalSomeChildren(SIGTERM,
2212 BACKEND_TYPE_NORMAL | BACKEND_TYPE_AUTOVAC);
2213 /* and the autovac launcher too */
2214 if (AutoVacPID != 0)
2215 signal_child(AutoVacPID, SIGTERM);
2216 /* and the walwriter too */
2217 if (WalWriterPID != 0)
2218 signal_child(WalWriterPID, SIGTERM);
2219 pmState = PM_WAIT_BACKENDS;
2223 * Now wait for backends to exit. If there are none,
2224 * PostmasterStateMachine will take the next step.
2226 PostmasterStateMachine();
2232 * Immediate Shutdown:
2234 * abort all children with SIGQUIT and exit without attempt to
2235 * properly shut down data base system.
2238 (errmsg("received immediate shutdown request")));
2239 SignalChildren(SIGQUIT);
2240 if (StartupPID != 0)
2241 signal_child(StartupPID, SIGQUIT);
2242 if (BgWriterPID != 0)
2243 signal_child(BgWriterPID, SIGQUIT);
2244 if (CheckpointerPID != 0)
2245 signal_child(CheckpointerPID, SIGQUIT);
2246 if (WalWriterPID != 0)
2247 signal_child(WalWriterPID, SIGQUIT);
2248 if (WalReceiverPID != 0)
2249 signal_child(WalReceiverPID, SIGQUIT);
2250 if (AutoVacPID != 0)
2251 signal_child(AutoVacPID, SIGQUIT);
2253 signal_child(PgArchPID, SIGQUIT);
2255 signal_child(PgStatPID, SIGQUIT);
2260 PG_SETMASK(&UnBlockSig);
2266 * Reaper -- signal handler to cleanup after a child process dies.
2271 int save_errno = errno;
2272 int pid; /* process id of dead child process */
2273 int exitstatus; /* its exit status */
2275 PG_SETMASK(&BlockSig);
2278 (errmsg_internal("reaping dead processes")));
2280 while ((pid = waitpid(-1, &exitstatus, WNOHANG)) > 0)
2283 * Check if this child was a startup process.
2285 if (pid == StartupPID)
2290 * Unexpected exit of startup process (including FATAL exit)
2291 * during PM_STARTUP is treated as catastrophic. There are no
2292 * other processes running yet, so we can just exit.
2294 if (pmState == PM_STARTUP && !EXIT_STATUS_0(exitstatus))
2296 LogChildExit(LOG, _("startup process"),
2299 (errmsg("aborting startup due to startup process failure")));
2304 * Startup process exited in response to a shutdown request (or it
2305 * completed normally regardless of the shutdown request).
2307 if (Shutdown > NoShutdown &&
2308 (EXIT_STATUS_0(exitstatus) || EXIT_STATUS_1(exitstatus)))
2310 pmState = PM_WAIT_BACKENDS;
2311 /* PostmasterStateMachine logic does the rest */
2316 * After PM_STARTUP, any unexpected exit (including FATAL exit) of
2317 * the startup process is catastrophic, so kill other children,
2318 * and set RecoveryError so we don't try to reinitialize after
2319 * they're gone. Exception: if FatalError is already set, that
2320 * implies we previously sent the startup process a SIGQUIT, so
2321 * that's probably the reason it died, and we do want to try to
2322 * restart in that case.
2324 if (!EXIT_STATUS_0(exitstatus))
2327 RecoveryError = true;
2328 HandleChildCrash(pid, exitstatus,
2329 _("startup process"));
2334 * Startup succeeded, commence normal operations
2337 ReachedNormalRunning = true;
2341 * Kill any walsenders to force the downstream standby(s) to
2342 * reread the timeline history file, adjust their timelines and
2343 * establish replication connections again. This is required
2344 * because the timeline of cascading standby is not consistent
2345 * with that of cascaded one just after failover. We LOG this
2346 * message since we need to leave a record to explain this
2349 * XXX should avoid the need for disconnection. When we do,
2350 * am_cascading_walsender should be replaced with
2351 * RecoveryInProgress()
2353 if (max_wal_senders > 0 && CountChildren(BACKEND_TYPE_WALSND) > 0)
2356 (errmsg("terminating all walsender processes to force cascaded "
2357 "standby(s) to update timeline and reconnect")));
2358 SignalSomeChildren(SIGUSR2, BACKEND_TYPE_WALSND);
2362 * Crank up the background tasks, if we didn't do that already
2363 * when we entered consistent recovery state. It doesn't matter
2364 * if this fails, we'll just try again later.
2366 if (CheckpointerPID == 0)
2367 CheckpointerPID = StartCheckpointer();
2368 if (BgWriterPID == 0)
2369 BgWriterPID = StartBackgroundWriter();
2370 if (WalWriterPID == 0)
2371 WalWriterPID = StartWalWriter();
2374 * Likewise, start other special children as needed. In a restart
2375 * situation, some of them may be alive already.
2377 if (!IsBinaryUpgrade && AutoVacuumingActive() && AutoVacPID == 0)
2378 AutoVacPID = StartAutoVacLauncher();
2379 if (XLogArchivingActive() && PgArchPID == 0)
2380 PgArchPID = pgarch_start();
2382 PgStatPID = pgstat_start();
2384 /* at this point we are really open for business */
2386 (errmsg("database system is ready to accept connections")));
2392 * Was it the bgwriter? Normal exit can be ignored; we'll start a new
2393 * one at the next iteration of the postmaster's main loop, if
2394 * necessary. Any other exit condition is treated as a crash.
2396 if (pid == BgWriterPID)
2399 if (!EXIT_STATUS_0(exitstatus))
2400 HandleChildCrash(pid, exitstatus,
2401 _("background writer process"));
2406 * Was it the checkpointer?
2408 if (pid == CheckpointerPID)
2410 CheckpointerPID = 0;
2411 if (EXIT_STATUS_0(exitstatus) && pmState == PM_SHUTDOWN)
2414 * OK, we saw normal exit of the checkpointer after it's been
2415 * told to shut down. We expect that it wrote a shutdown
2416 * checkpoint. (If for some reason it didn't, recovery will
2417 * occur on next postmaster start.)
2419 * At this point we should have no normal backend children
2420 * left (else we'd not be in PM_SHUTDOWN state) but we might
2421 * have dead_end children to wait for.
2423 * If we have an archiver subprocess, tell it to do a last
2424 * archive cycle and quit. Likewise, if we have walsender
2425 * processes, tell them to send any remaining WAL and quit.
2427 Assert(Shutdown > NoShutdown);
2429 /* Waken archiver for the last time */
2431 signal_child(PgArchPID, SIGUSR2);
2434 * Waken walsenders for the last time. No regular backends
2435 * should be around anymore.
2437 SignalChildren(SIGUSR2);
2439 pmState = PM_SHUTDOWN_2;
2442 * We can also shut down the stats collector now; there's
2443 * nothing left for it to do.
2446 signal_child(PgStatPID, SIGQUIT);
2451 * Any unexpected exit of the checkpointer (including FATAL
2452 * exit) is treated as a crash.
2454 HandleChildCrash(pid, exitstatus,
2455 _("checkpointer process"));
2462 * Was it the wal writer? Normal exit can be ignored; we'll start a
2463 * new one at the next iteration of the postmaster's main loop, if
2464 * necessary. Any other exit condition is treated as a crash.
2466 if (pid == WalWriterPID)
2469 if (!EXIT_STATUS_0(exitstatus))
2470 HandleChildCrash(pid, exitstatus,
2471 _("WAL writer process"));
2476 * Was it the wal receiver? If exit status is zero (normal) or one
2477 * (FATAL exit), we assume everything is all right just like normal
2480 if (pid == WalReceiverPID)
2483 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2484 HandleChildCrash(pid, exitstatus,
2485 _("WAL receiver process"));
2490 * Was it the autovacuum launcher? Normal exit can be ignored; we'll
2491 * start a new one at the next iteration of the postmaster's main
2492 * loop, if necessary. Any other exit condition is treated as a
2495 if (pid == AutoVacPID)
2498 if (!EXIT_STATUS_0(exitstatus))
2499 HandleChildCrash(pid, exitstatus,
2500 _("autovacuum launcher process"));
2505 * Was it the archiver? If so, just try to start a new one; no need
2506 * to force reset of the rest of the system. (If fail, we'll try
2507 * again in future cycles of the main loop.). Unless we were waiting
2508 * for it to shut down; don't restart it in that case, and
2509 * PostmasterStateMachine() will advance to the next shutdown step.
2511 if (pid == PgArchPID)
2514 if (!EXIT_STATUS_0(exitstatus))
2515 LogChildExit(LOG, _("archiver process"),
2517 if (XLogArchivingActive() && pmState == PM_RUN)
2518 PgArchPID = pgarch_start();
2523 * Was it the statistics collector? If so, just try to start a new
2524 * one; no need to force reset of the rest of the system. (If fail,
2525 * we'll try again in future cycles of the main loop.)
2527 if (pid == PgStatPID)
2530 if (!EXIT_STATUS_0(exitstatus))
2531 LogChildExit(LOG, _("statistics collector process"),
2533 if (pmState == PM_RUN)
2534 PgStatPID = pgstat_start();
2538 /* Was it the system logger? If so, try to start a new one */
2539 if (pid == SysLoggerPID)
2542 /* for safety's sake, launch new logger *first* */
2543 SysLoggerPID = SysLogger_Start();
2544 if (!EXIT_STATUS_0(exitstatus))
2545 LogChildExit(LOG, _("system logger process"),
2551 * Else do standard backend child cleanup.
2553 CleanupBackend(pid, exitstatus);
2554 } /* loop over pending child-death reports */
2557 * After cleaning out the SIGCHLD queue, see if we have any state changes
2558 * or actions to make.
2560 PostmasterStateMachine();
2562 /* Done with signal handler */
2563 PG_SETMASK(&UnBlockSig);
2570 * CleanupBackend -- cleanup after terminated backend.
2572 * Remove all local state associated with backend.
2575 CleanupBackend(int pid,
2576 int exitstatus) /* child's exit status. */
2580 LogChildExit(DEBUG2, _("server process"), pid, exitstatus);
2583 * If a backend dies in an ugly way then we must signal all other backends
2584 * to quickdie. If exit status is zero (normal) or one (FATAL exit), we
2585 * assume everything is all right and proceed to remove the backend from
2586 * the active backend list.
2591 * On win32, also treat ERROR_WAIT_NO_CHILDREN (128) as nonfatal case,
2592 * since that sometimes happens under load when the process fails to start
2593 * properly (long before it starts using shared memory). Microsoft reports
2594 * it is related to mutex failure:
2595 * http://archives.postgresql.org/pgsql-hackers/2010-09/msg00790.php
2597 if (exitstatus == ERROR_WAIT_NO_CHILDREN)
2599 LogChildExit(LOG, _("server process"), pid, exitstatus);
2604 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2606 HandleChildCrash(pid, exitstatus, _("server process"));
2610 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2612 Backend *bp = (Backend *) DLE_VAL(curr);
2618 if (!ReleasePostmasterChildSlot(bp->child_slot))
2621 * Uh-oh, the child failed to clean itself up. Treat as a
2624 HandleChildCrash(pid, exitstatus, _("server process"));
2628 ShmemBackendArrayRemove(bp);
2639 * HandleChildCrash -- cleanup after failed backend, bgwriter, checkpointer,
2640 * walwriter or autovacuum.
2642 * The objectives here are to clean up our local state about the child
2643 * process, and to signal all other remaining children to quickdie.
2646 HandleChildCrash(int pid, int exitstatus, const char *procname)
2653 * Make log entry unless there was a previous crash (if so, nonzero exit
2654 * status is to be expected in SIGQUIT response; don't clutter log)
2658 LogChildExit(LOG, procname, pid, exitstatus);
2660 (errmsg("terminating any other active server processes")));
2663 /* Process regular backends */
2664 for (curr = DLGetHead(BackendList); curr; curr = next)
2666 next = DLGetSucc(curr);
2667 bp = (Backend *) DLE_VAL(curr);
2671 * Found entry for freshly-dead backend, so remove it.
2675 (void) ReleasePostmasterChildSlot(bp->child_slot);
2677 ShmemBackendArrayRemove(bp);
2682 /* Keep looping so we can signal remaining backends */
2687 * This backend is still alive. Unless we did so already, tell it
2688 * to commit hara-kiri.
2690 * SIGQUIT is the special signal that says exit without proc_exit
2691 * and let the user know what's going on. But if SendStop is set
2692 * (-s on command line), then we send SIGSTOP instead, so that we
2693 * can get core dumps from all backends by hand.
2695 * We could exclude dead_end children here, but at least in the
2696 * SIGSTOP case it seems better to include them.
2701 (errmsg_internal("sending %s to process %d",
2702 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2704 signal_child(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
2709 /* Take care of the startup process too */
2710 if (pid == StartupPID)
2712 else if (StartupPID != 0 && !FatalError)
2715 (errmsg_internal("sending %s to process %d",
2716 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2717 (int) StartupPID)));
2718 signal_child(StartupPID, (SendStop ? SIGSTOP : SIGQUIT));
2721 /* Take care of the bgwriter too */
2722 if (pid == BgWriterPID)
2724 else if (BgWriterPID != 0 && !FatalError)
2727 (errmsg_internal("sending %s to process %d",
2728 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2729 (int) BgWriterPID)));
2730 signal_child(BgWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
2733 /* Take care of the checkpointer too */
2734 if (pid == CheckpointerPID)
2735 CheckpointerPID = 0;
2736 else if (CheckpointerPID != 0 && !FatalError)
2739 (errmsg_internal("sending %s to process %d",
2740 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2741 (int) CheckpointerPID)));
2742 signal_child(CheckpointerPID, (SendStop ? SIGSTOP : SIGQUIT));
2745 /* Take care of the walwriter too */
2746 if (pid == WalWriterPID)
2748 else if (WalWriterPID != 0 && !FatalError)
2751 (errmsg_internal("sending %s to process %d",
2752 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2753 (int) WalWriterPID)));
2754 signal_child(WalWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
2757 /* Take care of the walreceiver too */
2758 if (pid == WalReceiverPID)
2760 else if (WalReceiverPID != 0 && !FatalError)
2763 (errmsg_internal("sending %s to process %d",
2764 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2765 (int) WalReceiverPID)));
2766 signal_child(WalReceiverPID, (SendStop ? SIGSTOP : SIGQUIT));
2769 /* Take care of the autovacuum launcher too */
2770 if (pid == AutoVacPID)
2772 else if (AutoVacPID != 0 && !FatalError)
2775 (errmsg_internal("sending %s to process %d",
2776 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2777 (int) AutoVacPID)));
2778 signal_child(AutoVacPID, (SendStop ? SIGSTOP : SIGQUIT));
2782 * Force a power-cycle of the pgarch process too. (This isn't absolutely
2783 * necessary, but it seems like a good idea for robustness, and it
2784 * simplifies the state-machine logic in the case where a shutdown request
2785 * arrives during crash processing.)
2787 if (PgArchPID != 0 && !FatalError)
2790 (errmsg_internal("sending %s to process %d",
2793 signal_child(PgArchPID, SIGQUIT);
2797 * Force a power-cycle of the pgstat process too. (This isn't absolutely
2798 * necessary, but it seems like a good idea for robustness, and it
2799 * simplifies the state-machine logic in the case where a shutdown request
2800 * arrives during crash processing.)
2802 if (PgStatPID != 0 && !FatalError)
2805 (errmsg_internal("sending %s to process %d",
2808 signal_child(PgStatPID, SIGQUIT);
2809 allow_immediate_pgstat_restart();
2812 /* We do NOT restart the syslogger */
2815 /* We now transit into a state of waiting for children to die */
2816 if (pmState == PM_RECOVERY ||
2817 pmState == PM_HOT_STANDBY ||
2818 pmState == PM_RUN ||
2819 pmState == PM_WAIT_BACKUP ||
2820 pmState == PM_WAIT_READONLY ||
2821 pmState == PM_SHUTDOWN)
2822 pmState = PM_WAIT_BACKENDS;
2826 * Log the death of a child process.
2829 LogChildExit(int lev, const char *procname, int pid, int exitstatus)
2832 * size of activity_buffer is arbitrary, but set equal to default
2833 * track_activity_query_size
2835 char activity_buffer[1024];
2836 const char *activity = NULL;
2838 if (!EXIT_STATUS_0(exitstatus))
2839 activity = pgstat_get_crashed_backend_activity(pid,
2841 sizeof(activity_buffer));
2843 if (WIFEXITED(exitstatus))
2847 translator: %s is a noun phrase describing a child process, such as
2849 (errmsg("%s (PID %d) exited with exit code %d",
2850 procname, pid, WEXITSTATUS(exitstatus)),
2851 activity ? errdetail("Failed process was running: %s", activity) : 0));
2852 else if (WIFSIGNALED(exitstatus))
2857 translator: %s is a noun phrase describing a child process, such as
2859 (errmsg("%s (PID %d) was terminated by exception 0x%X",
2860 procname, pid, WTERMSIG(exitstatus)),
2861 errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
2862 activity ? errdetail("Failed process was running: %s", activity) : 0));
2863 #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST
2867 translator: %s is a noun phrase describing a child process, such as
2869 (errmsg("%s (PID %d) was terminated by signal %d: %s",
2870 procname, pid, WTERMSIG(exitstatus),
2871 WTERMSIG(exitstatus) < NSIG ?
2872 sys_siglist[WTERMSIG(exitstatus)] : "(unknown)"),
2873 activity ? errdetail("Failed process was running: %s", activity) : 0));
2878 translator: %s is a noun phrase describing a child process, such as
2880 (errmsg("%s (PID %d) was terminated by signal %d",
2881 procname, pid, WTERMSIG(exitstatus)),
2882 activity ? errdetail("Failed process was running: %s", activity) : 0));
2888 translator: %s is a noun phrase describing a child process, such as
2890 (errmsg("%s (PID %d) exited with unrecognized status %d",
2891 procname, pid, exitstatus),
2892 activity ? errdetail("Failed process was running: %s", activity) : 0));
2896 * Advance the postmaster's state machine and take actions as appropriate
2898 * This is common code for pmdie(), reaper() and sigusr1_handler(), which
2899 * receive the signals that might mean we need to change state.
2902 PostmasterStateMachine(void)
2904 if (pmState == PM_WAIT_BACKUP)
2907 * PM_WAIT_BACKUP state ends when online backup mode is not active.
2909 if (!BackupInProgress())
2910 pmState = PM_WAIT_BACKENDS;
2913 if (pmState == PM_WAIT_READONLY)
2916 * PM_WAIT_READONLY state ends when we have no regular backends that
2917 * have been started during recovery. We kill the startup and
2918 * walreceiver processes and transition to PM_WAIT_BACKENDS. Ideally,
2919 * we might like to kill these processes first and then wait for
2920 * backends to die off, but that doesn't work at present because
2921 * killing the startup process doesn't release its locks.
2923 if (CountChildren(BACKEND_TYPE_NORMAL) == 0)
2925 if (StartupPID != 0)
2926 signal_child(StartupPID, SIGTERM);
2927 if (WalReceiverPID != 0)
2928 signal_child(WalReceiverPID, SIGTERM);
2929 pmState = PM_WAIT_BACKENDS;
2934 * If we are in a state-machine state that implies waiting for backends to
2935 * exit, see if they're all gone, and change state if so.
2937 if (pmState == PM_WAIT_BACKENDS)
2940 * PM_WAIT_BACKENDS state ends when we have no regular backends
2941 * (including autovac workers) and no walwriter, autovac launcher or
2942 * bgwriter. If we are doing crash recovery then we expect the
2943 * checkpointer to exit as well, otherwise not. The archiver, stats,
2944 * and syslogger processes are disregarded since they are not
2945 * connected to shared memory; we also disregard dead_end children
2946 * here. Walsenders are also disregarded, they will be terminated
2947 * later after writing the checkpoint record, like the archiver
2950 if (CountChildren(BACKEND_TYPE_NORMAL | BACKEND_TYPE_AUTOVAC) == 0 &&
2952 WalReceiverPID == 0 &&
2954 (CheckpointerPID == 0 || !FatalError) &&
2955 WalWriterPID == 0 &&
2961 * Start waiting for dead_end children to die. This state
2962 * change causes ServerLoop to stop creating new ones.
2964 pmState = PM_WAIT_DEAD_END;
2967 * We already SIGQUIT'd the archiver and stats processes, if
2968 * any, when we entered FatalError state.
2974 * If we get here, we are proceeding with normal shutdown. All
2975 * the regular children are gone, and it's time to tell the
2976 * checkpointer to do a shutdown checkpoint.
2978 Assert(Shutdown > NoShutdown);
2979 /* Start the checkpointer if not running */
2980 if (CheckpointerPID == 0)
2981 CheckpointerPID = StartCheckpointer();
2982 /* And tell it to shut down */
2983 if (CheckpointerPID != 0)
2985 signal_child(CheckpointerPID, SIGUSR2);
2986 pmState = PM_SHUTDOWN;
2991 * If we failed to fork a checkpointer, just shut down.
2992 * Any required cleanup will happen at next restart. We
2993 * set FatalError so that an "abnormal shutdown" message
2994 * gets logged when we exit.
2997 pmState = PM_WAIT_DEAD_END;
2999 /* Kill the walsenders, archiver and stats collector too */
3000 SignalChildren(SIGQUIT);
3002 signal_child(PgArchPID, SIGQUIT);
3004 signal_child(PgStatPID, SIGQUIT);
3010 if (pmState == PM_SHUTDOWN_2)
3013 * PM_SHUTDOWN_2 state ends when there's no other children than
3014 * dead_end children left. There shouldn't be any regular backends
3015 * left by now anyway; what we're really waiting for is walsenders and
3018 * Walreceiver should normally be dead by now, but not when a fast
3019 * shutdown is performed during recovery.
3021 if (PgArchPID == 0 && CountChildren(BACKEND_TYPE_ALL) == 0 &&
3022 WalReceiverPID == 0)
3024 pmState = PM_WAIT_DEAD_END;
3028 if (pmState == PM_WAIT_DEAD_END)
3031 * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
3032 * (ie, no dead_end children remain), and the archiver and stats
3033 * collector are gone too.
3035 * The reason we wait for those two is to protect them against a new
3036 * postmaster starting conflicting subprocesses; this isn't an
3037 * ironclad protection, but it at least helps in the
3038 * shutdown-and-immediately-restart scenario. Note that they have
3039 * already been sent appropriate shutdown signals, either during a
3040 * normal state transition leading up to PM_WAIT_DEAD_END, or during
3041 * FatalError processing.
3043 if (DLGetHead(BackendList) == NULL &&
3044 PgArchPID == 0 && PgStatPID == 0)
3046 /* These other guys should be dead already */
3047 Assert(StartupPID == 0);
3048 Assert(WalReceiverPID == 0);
3049 Assert(BgWriterPID == 0);
3050 Assert(CheckpointerPID == 0);
3051 Assert(WalWriterPID == 0);
3052 Assert(AutoVacPID == 0);
3053 /* syslogger is not considered here */
3054 pmState = PM_NO_CHILDREN;
3059 * If we've been told to shut down, we exit as soon as there are no
3060 * remaining children. If there was a crash, cleanup will occur at the
3061 * next startup. (Before PostgreSQL 8.3, we tried to recover from the
3062 * crash before exiting, but that seems unwise if we are quitting because
3063 * we got SIGTERM from init --- there may well not be time for recovery
3064 * before init decides to SIGKILL us.)
3066 * Note that the syslogger continues to run. It will exit when it sees
3067 * EOF on its input pipe, which happens when there are no more upstream
3070 if (Shutdown > NoShutdown && pmState == PM_NO_CHILDREN)
3074 ereport(LOG, (errmsg("abnormal database system shutdown")));
3080 * Terminate exclusive backup mode to avoid recovery after a clean
3081 * fast shutdown. Since an exclusive backup can only be taken
3082 * during normal running (and not, for example, while running
3083 * under Hot Standby) it only makes sense to do this if we reached
3084 * normal running. If we're still in recovery, the backup file is
3085 * one we're recovering *from*, and we must keep it around so that
3086 * recovery restarts from the right place.
3088 if (ReachedNormalRunning)
3091 /* Normal exit from the postmaster is here */
3097 * If recovery failed, or the user does not want an automatic restart
3098 * after backend crashes, wait for all non-syslogger children to exit, and
3099 * then exit postmaster. We don't try to reinitialize when recovery fails,
3100 * because more than likely it will just fail again and we will keep
3103 if (pmState == PM_NO_CHILDREN && (RecoveryError || !restart_after_crash))
3107 * If we need to recover from a crash, wait for all non-syslogger children
3108 * to exit, then reset shmem and StartupDataBase.
3110 if (FatalError && pmState == PM_NO_CHILDREN)
3113 (errmsg("all server processes terminated; reinitializing")));
3116 reset_shared(PostPortNumber);
3118 StartupPID = StartupDataBase();
3119 Assert(StartupPID != 0);
3120 pmState = PM_STARTUP;
3126 * Send a signal to a postmaster child process
3128 * On systems that have setsid(), each child process sets itself up as a
3129 * process group leader. For signals that are generally interpreted in the
3130 * appropriate fashion, we signal the entire process group not just the
3131 * direct child process. This allows us to, for example, SIGQUIT a blocked
3132 * archive_recovery script, or SIGINT a script being run by a backend via
3135 * There is a race condition for recently-forked children: they might not
3136 * have executed setsid() yet. So we signal the child directly as well as
3137 * the group. We assume such a child will handle the signal before trying
3138 * to spawn any grandchild processes. We also assume that signaling the
3139 * child twice will not cause any problems.
3142 signal_child(pid_t pid, int signal)
3144 if (kill(pid, signal) < 0)
3145 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
3153 if (kill(-pid, signal) < 0)
3154 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) (-pid), signal);
3163 * Send a signal to the targeted children (but NOT special children;
3164 * dead_end children are never signaled, either).
3167 SignalSomeChildren(int signal, int target)
3170 bool signaled = false;
3172 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
3174 Backend *bp = (Backend *) DLE_VAL(curr);
3180 * Since target == BACKEND_TYPE_ALL is the most common case, we test
3181 * it first and avoid touching shared memory for every child.
3183 if (target != BACKEND_TYPE_ALL)
3187 if (bp->is_autovacuum)
3188 child = BACKEND_TYPE_AUTOVAC;
3189 else if (IsPostmasterChildWalSender(bp->child_slot))
3190 child = BACKEND_TYPE_WALSND;
3192 child = BACKEND_TYPE_NORMAL;
3193 if (!(target & child))
3198 (errmsg_internal("sending signal %d to process %d",
3199 signal, (int) bp->pid)));
3200 signal_child(bp->pid, signal);
3207 * BackendStartup -- start backend process
3209 * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
3211 * Note: if you change this code, also consider StartAutovacuumWorker.
3214 BackendStartup(Port *port)
3216 Backend *bn; /* for backend cleanup */
3220 * Create backend data structure. Better before the fork() so we can
3221 * handle failure cleanly.
3223 bn = (Backend *) malloc(sizeof(Backend));
3227 (errcode(ERRCODE_OUT_OF_MEMORY),
3228 errmsg("out of memory")));
3229 return STATUS_ERROR;
3233 * Compute the cancel key that will be assigned to this backend. The
3234 * backend will have its own copy in the forked-off process' value of
3235 * MyCancelKey, so that it can transmit the key to the frontend.
3237 MyCancelKey = PostmasterRandom();
3238 bn->cancel_key = MyCancelKey;
3240 /* Pass down canAcceptConnections state */
3241 port->canAcceptConnections = canAcceptConnections();
3242 bn->dead_end = (port->canAcceptConnections != CAC_OK &&
3243 port->canAcceptConnections != CAC_WAITBACKUP);
3246 * Unless it's a dead_end child, assign it a child slot number
3249 bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
3254 pid = backend_forkexec(port);
3255 #else /* !EXEC_BACKEND */
3256 pid = fork_process();
3257 if (pid == 0) /* child */
3262 * Let's clean up ourselves as the postmaster child, and close the
3263 * postmaster's listen sockets. (In EXEC_BACKEND case this is all
3264 * done in SubPostmasterMain.)
3266 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
3268 MyProcPid = getpid(); /* reset MyProcPid */
3270 MyStartTime = time(NULL);
3272 /* We don't want the postmaster's proc_exit() handlers */
3275 /* Close the postmaster's sockets */
3276 ClosePostmasterPorts(false);
3278 /* Perform additional initialization and collect startup packet */
3279 BackendInitialize(port);
3281 /* And run the backend */
3284 #endif /* EXEC_BACKEND */
3288 /* in parent, fork failed */
3289 int save_errno = errno;
3292 (void) ReleasePostmasterChildSlot(bn->child_slot);
3296 (errmsg("could not fork new process for connection: %m")));
3297 report_fork_failure_to_client(port, save_errno);
3298 return STATUS_ERROR;
3301 /* in parent, successful fork */
3303 (errmsg_internal("forked new backend, pid=%d socket=%d",
3304 (int) pid, (int) port->sock)));
3307 * Everything's been successful, it's safe to add this backend to our list
3311 bn->is_autovacuum = false;
3312 DLInitElem(&bn->elem, bn);
3313 DLAddHead(BackendList, &bn->elem);
3316 ShmemBackendArrayAdd(bn);
3323 * Try to report backend fork() failure to client before we close the
3324 * connection. Since we do not care to risk blocking the postmaster on
3325 * this connection, we set the connection to non-blocking and try only once.
3327 * This is grungy special-purpose code; we cannot use backend libpq since
3328 * it's not up and running.
3331 report_fork_failure_to_client(Port *port, int errnum)
3336 /* Format the error message packet (always V2 protocol) */
3337 snprintf(buffer, sizeof(buffer), "E%s%s\n",
3338 _("could not fork new process for connection: "),
3341 /* Set port to non-blocking. Don't do send() if this fails */
3342 if (!pg_set_noblock(port->sock))
3345 /* We'll retry after EINTR, but ignore all other failures */
3348 rc = send(port->sock, buffer, strlen(buffer) + 1, 0);
3349 } while (rc < 0 && errno == EINTR);
3354 * BackendInitialize -- initialize an interactive (postmaster-child)
3355 * backend process, and collect the client's startup packet.
3357 * returns: nothing. Will not return at all if there's any failure.
3359 * Note: this code does not depend on having any access to shared memory.
3360 * In the EXEC_BACKEND case, we are physically attached to shared memory
3361 * but have not yet set up most of our local pointers to shmem structures.
3364 BackendInitialize(Port *port)
3367 char remote_host[NI_MAXHOST];
3368 char remote_port[NI_MAXSERV];
3369 char remote_ps_data[NI_MAXHOST];
3371 /* Save port etc. for ps status */
3375 * PreAuthDelay is a debugging aid for investigating problems in the
3376 * authentication cycle: it can be set in postgresql.conf to allow time to
3377 * attach to the newly-forked backend with a debugger. (See also
3378 * PostAuthDelay, which we allow clients to pass through PGOPTIONS, but it
3379 * is not honored until after authentication.)
3381 if (PreAuthDelay > 0)
3382 pg_usleep(PreAuthDelay * 1000000L);
3384 /* This flag will remain set until InitPostgres finishes authentication */
3385 ClientAuthInProgress = true; /* limit visibility of log messages */
3387 /* save process start time */
3388 port->SessionStartTime = GetCurrentTimestamp();
3389 MyStartTime = timestamptz_to_time_t(port->SessionStartTime);
3391 /* set these to empty in case they are needed before we set them up */
3392 port->remote_host = "";
3393 port->remote_port = "";
3396 * Initialize libpq and enable reporting of ereport errors to the client.
3397 * Must do this now because authentication uses libpq to send messages.
3399 pq_init(); /* initialize libpq to talk to client */
3400 whereToSendOutput = DestRemote; /* now safe to ereport to client */
3403 * If possible, make this process a group leader, so that the postmaster
3404 * can signal any child processes too. (We do this now on the off chance
3405 * that something might spawn a child process during authentication.)
3409 elog(FATAL, "setsid() failed: %m");
3413 * We arrange for a simple exit(1) if we receive SIGTERM or SIGQUIT or
3414 * timeout while trying to collect the startup packet. Otherwise the
3415 * postmaster cannot shutdown the database FAST or IMMED cleanly if a
3416 * buggy client fails to send the packet promptly.
3418 pqsignal(SIGTERM, startup_die);
3419 pqsignal(SIGQUIT, startup_die);
3420 InitializeTimeouts(); /* establishes SIGALRM handler */
3421 PG_SETMASK(&StartupBlockSig);
3424 * Get the remote host name and port for logging and status display.
3426 remote_host[0] = '\0';
3427 remote_port[0] = '\0';
3428 if (pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
3429 remote_host, sizeof(remote_host),
3430 remote_port, sizeof(remote_port),
3431 (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV) != 0)
3433 int ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
3434 remote_host, sizeof(remote_host),
3435 remote_port, sizeof(remote_port),
3436 NI_NUMERICHOST | NI_NUMERICSERV);
3440 (errmsg_internal("pg_getnameinfo_all() failed: %s",
3441 gai_strerror(ret))));
3443 if (remote_port[0] == '\0')
3444 snprintf(remote_ps_data, sizeof(remote_ps_data), "%s", remote_host);
3446 snprintf(remote_ps_data, sizeof(remote_ps_data), "%s(%s)", remote_host, remote_port);
3448 if (Log_connections)
3452 (errmsg("connection received: host=%s port=%s",
3457 (errmsg("connection received: host=%s",
3462 * save remote_host and remote_port in port structure
3464 port->remote_host = strdup(remote_host);
3465 port->remote_port = strdup(remote_port);
3467 port->remote_hostname = port->remote_host;
3470 * Ready to begin client interaction. We will give up and exit(1) after a
3471 * time delay, so that a broken client can't hog a connection
3472 * indefinitely. PreAuthDelay and any DNS interactions above don't count
3473 * against the time limit.
3475 * Note: AuthenticationTimeout is applied here while waiting for the
3476 * startup packet, and then again in InitPostgres for the duration of any
3477 * authentication operations. So a hostile client could tie up the
3478 * process for nearly twice AuthenticationTimeout before we kick him off.
3480 * Note: because PostgresMain will call InitializeTimeouts again, the
3481 * registration of STARTUP_PACKET_TIMEOUT will be lost. This is okay
3482 * since we never use it again after this function.
3484 RegisterTimeout(STARTUP_PACKET_TIMEOUT, StartupPacketTimeoutHandler);
3485 enable_timeout_after(STARTUP_PACKET_TIMEOUT, AuthenticationTimeout * 1000);
3488 * Receive the startup packet (which might turn out to be a cancel request
3491 status = ProcessStartupPacket(port, false);
3494 * Stop here if it was bad or a cancel packet. ProcessStartupPacket
3495 * already did any appropriate error reporting.
3497 if (status != STATUS_OK)
3501 * Now that we have the user and database name, we can set the process
3502 * title for ps. It's good to do this as early as possible in startup.
3504 * For a walsender, the ps display is set in the following form:
3506 * postgres: wal sender process <user> <host> <activity>
3508 * To achieve that, we pass "wal sender process" as username and username
3509 * as dbname to init_ps_display(). XXX: should add a new variant of
3510 * init_ps_display() to avoid abusing the parameters like this.
3513 init_ps_display("wal sender process", port->user_name, remote_ps_data,
3514 update_process_title ? "authentication" : "");
3516 init_ps_display(port->user_name, port->database_name, remote_ps_data,
3517 update_process_title ? "authentication" : "");
3520 * Disable the timeout, and prevent SIGTERM/SIGQUIT again.
3522 disable_timeout(STARTUP_PACKET_TIMEOUT, false);
3523 PG_SETMASK(&BlockSig);
3528 * BackendRun -- set up the backend's argument list and invoke PostgresMain()
3531 * Shouldn't return at all.
3532 * If PostgresMain() fails, return status.
3535 BackendRun(Port *port)
3545 * Don't want backend to be able to see the postmaster random number
3546 * generator state. We have to clobber the static random_seed *and* start
3547 * a new random sequence in the random() library function.
3550 random_start_time.tv_usec = 0;
3551 /* slightly hacky way to get integer microseconds part of timestamptz */
3552 TimestampDifference(0, port->SessionStartTime, &secs, &usecs);
3553 srandom((unsigned int) (MyProcPid ^ usecs));
3556 * Now, build the argv vector that will be given to PostgresMain.
3558 * The maximum possible number of commandline arguments that could come
3559 * from ExtraOptions is (strlen(ExtraOptions) + 1) / 2; see
3562 maxac = 5; /* for fixed args supplied below */
3563 maxac += (strlen(ExtraOptions) + 1) / 2;
3565 av = (char **) MemoryContextAlloc(TopMemoryContext,
3566 maxac * sizeof(char *));
3569 av[ac++] = "postgres";
3572 * Pass any backend switches specified with -o on the postmaster's own
3573 * command line. We assume these are secure. (It's OK to mangle
3574 * ExtraOptions now, since we're safely inside a subprocess.)
3576 pg_split_opts(av, &ac, ExtraOptions);
3579 * Tell the backend which database to use.
3581 av[ac++] = port->database_name;
3588 * Debug: print arguments being passed to backend
3591 (errmsg_internal("%s child[%d]: starting with (",
3592 progname, (int) getpid())));
3593 for (i = 0; i < ac; ++i)
3595 (errmsg_internal("\t%s", av[i])));
3597 (errmsg_internal(")")));
3600 * Make sure we aren't in PostmasterContext anymore. (We can't delete it
3601 * just yet, though, because InitPostgres will need the HBA data.)
3603 MemoryContextSwitchTo(TopMemoryContext);
3605 PostgresMain(ac, av, port->user_name);
3612 * postmaster_forkexec -- fork and exec a postmaster subprocess
3614 * The caller must have set up the argv array already, except for argv[2]
3615 * which will be filled with the name of the temp variable file.
3617 * Returns the child process PID, or -1 on fork failure (a suitable error
3618 * message has been logged on failure).
3620 * All uses of this routine will dispatch to SubPostmasterMain in the
3624 postmaster_forkexec(int argc, char *argv[])
3628 /* This entry point passes dummy values for the Port variables */
3629 memset(&port, 0, sizeof(port));
3630 return internal_forkexec(argc, argv, &port);
3634 * backend_forkexec -- fork/exec off a backend process
3636 * Some operating systems (WIN32) don't have fork() so we have to simulate
3637 * it by storing parameters that need to be passed to the child and
3638 * then create a new child process.
3640 * returns the pid of the fork/exec'd process, or -1 on failure
3643 backend_forkexec(Port *port)
3648 av[ac++] = "postgres";
3649 av[ac++] = "--forkbackend";
3650 av[ac++] = NULL; /* filled in by internal_forkexec */
3653 Assert(ac < lengthof(av));
3655 return internal_forkexec(ac, av, port);
3661 * internal_forkexec non-win32 implementation
3663 * - writes out backend variables to the parameter file
3664 * - fork():s, and then exec():s the child process
3667 internal_forkexec(int argc, char *argv[], Port *port)
3669 static unsigned long tmpBackendFileNum = 0;
3671 char tmpfilename[MAXPGPATH];
3672 BackendParameters param;
3675 if (!save_backend_variables(¶m, port))
3676 return -1; /* log made by save_backend_variables */
3678 /* Calculate name for temp file */
3679 snprintf(tmpfilename, MAXPGPATH, "%s/%s.backend_var.%d.%lu",
3680 PG_TEMP_FILES_DIR, PG_TEMP_FILE_PREFIX,
3681 MyProcPid, ++tmpBackendFileNum);
3684 fp = AllocateFile(tmpfilename, PG_BINARY_W);
3687 /* As in OpenTemporaryFile, try to make the temp-file directory */
3688 mkdir(PG_TEMP_FILES_DIR, S_IRWXU);
3690 fp = AllocateFile(tmpfilename, PG_BINARY_W);
3694 (errcode_for_file_access(),
3695 errmsg("could not create file \"%s\": %m",
3701 if (fwrite(¶m, sizeof(param), 1, fp) != 1)
3704 (errcode_for_file_access(),
3705 errmsg("could not write to file \"%s\": %m", tmpfilename)));
3714 (errcode_for_file_access(),
3715 errmsg("could not write to file \"%s\": %m", tmpfilename)));
3719 /* Make sure caller set up argv properly */
3721 Assert(argv[argc] == NULL);
3722 Assert(strncmp(argv[1], "--fork", 6) == 0);
3723 Assert(argv[2] == NULL);
3725 /* Insert temp file name after --fork argument */
3726 argv[2] = tmpfilename;
3728 /* Fire off execv in child */
3729 if ((pid = fork_process()) == 0)
3731 if (execv(postgres_exec_path, argv) < 0)
3734 (errmsg("could not execute server process \"%s\": %m",
3735 postgres_exec_path)));
3736 /* We're already in the child process here, can't return */
3741 return pid; /* Parent returns pid, or -1 on fork failure */
3746 * internal_forkexec win32 implementation
3748 * - starts backend using CreateProcess(), in suspended state
3749 * - writes out backend variables to the parameter file
3750 * - during this, duplicates handles and sockets required for
3751 * inheritance into the new process
3752 * - resumes execution of the new process once the backend parameter
3756 internal_forkexec(int argc, char *argv[], Port *port)
3759 PROCESS_INFORMATION pi;
3762 char cmdLine[MAXPGPATH * 2];
3764 BackendParameters *param;
3765 SECURITY_ATTRIBUTES sa;
3766 char paramHandleStr[32];
3767 win32_deadchild_waitinfo *childinfo;
3769 /* Make sure caller set up argv properly */
3771 Assert(argv[argc] == NULL);
3772 Assert(strncmp(argv[1], "--fork", 6) == 0);
3773 Assert(argv[2] == NULL);
3775 /* Set up shared memory for parameter passing */
3776 ZeroMemory(&sa, sizeof(sa));
3777 sa.nLength = sizeof(sa);
3778 sa.bInheritHandle = TRUE;
3779 paramHandle = CreateFileMapping(INVALID_HANDLE_VALUE,
3783 sizeof(BackendParameters),
3785 if (paramHandle == INVALID_HANDLE_VALUE)
3787 elog(LOG, "could not create backend parameter file mapping: error code %lu",
3792 param = MapViewOfFile(paramHandle, FILE_MAP_WRITE, 0, 0, sizeof(BackendParameters));
3795 elog(LOG, "could not map backend parameter memory: error code %lu",
3797 CloseHandle(paramHandle);
3801 /* Insert temp file name after --fork argument */
3803 sprintf(paramHandleStr, "%llu", (LONG_PTR) paramHandle);
3805 sprintf(paramHandleStr, "%lu", (DWORD) paramHandle);
3807 argv[2] = paramHandleStr;
3809 /* Format the cmd line */
3810 cmdLine[sizeof(cmdLine) - 1] = '\0';
3811 cmdLine[sizeof(cmdLine) - 2] = '\0';
3812 snprintf(cmdLine, sizeof(cmdLine) - 1, "\"%s\"", postgres_exec_path);
3814 while (argv[++i] != NULL)
3816 j = strlen(cmdLine);
3817 snprintf(cmdLine + j, sizeof(cmdLine) - 1 - j, " \"%s\"", argv[i]);
3819 if (cmdLine[sizeof(cmdLine) - 2] != '\0')
3821 elog(LOG, "subprocess command line too long");
3825 memset(&pi, 0, sizeof(pi));
3826 memset(&si, 0, sizeof(si));
3830 * Create the subprocess in a suspended state. This will be resumed later,
3831 * once we have written out the parameter file.
3833 if (!CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, CREATE_SUSPENDED,
3834 NULL, NULL, &si, &pi))
3836 elog(LOG, "CreateProcess call failed: %m (error code %lu)",
3841 if (!save_backend_variables(param, port, pi.hProcess, pi.dwProcessId))
3844 * log made by save_backend_variables, but we have to clean up the
3845 * mess with the half-started process
3847 if (!TerminateProcess(pi.hProcess, 255))
3849 (errmsg_internal("could not terminate unstarted process: error code %lu",
3851 CloseHandle(pi.hProcess);
3852 CloseHandle(pi.hThread);
3853 return -1; /* log made by save_backend_variables */
3856 /* Drop the parameter shared memory that is now inherited to the backend */
3857 if (!UnmapViewOfFile(param))
3858 elog(LOG, "could not unmap view of backend parameter file: error code %lu",
3860 if (!CloseHandle(paramHandle))
3861 elog(LOG, "could not close handle to backend parameter file: error code %lu",
3865 * Reserve the memory region used by our main shared memory segment before
3866 * we resume the child process.
3868 if (!pgwin32_ReserveSharedMemoryRegion(pi.hProcess))
3871 * Failed to reserve the memory, so terminate the newly created
3872 * process and give up.
3874 if (!TerminateProcess(pi.hProcess, 255))
3876 (errmsg_internal("could not terminate process that failed to reserve memory: error code %lu",
3878 CloseHandle(pi.hProcess);
3879 CloseHandle(pi.hThread);
3880 return -1; /* logging done made by
3881 * pgwin32_ReserveSharedMemoryRegion() */
3885 * Now that the backend variables are written out, we start the child
3886 * thread so it can start initializing while we set up the rest of the
3889 if (ResumeThread(pi.hThread) == -1)
3891 if (!TerminateProcess(pi.hProcess, 255))
3894 (errmsg_internal("could not terminate unstartable process: error code %lu",
3896 CloseHandle(pi.hProcess);
3897 CloseHandle(pi.hThread);
3900 CloseHandle(pi.hProcess);
3901 CloseHandle(pi.hThread);
3903 (errmsg_internal("could not resume thread of unstarted process: error code %lu",
3909 * Queue a waiter for to signal when this child dies. The wait will be
3910 * handled automatically by an operating system thread pool.
3912 * Note: use malloc instead of palloc, since it needs to be thread-safe.
3913 * Struct will be free():d from the callback function that runs on a
3916 childinfo = malloc(sizeof(win32_deadchild_waitinfo));
3919 (errcode(ERRCODE_OUT_OF_MEMORY),
3920 errmsg("out of memory")));
3922 childinfo->procHandle = pi.hProcess;
3923 childinfo->procId = pi.dwProcessId;
3925 if (!RegisterWaitForSingleObject(&childinfo->waitHandle,
3927 pgwin32_deadchild_callback,
3930 WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD))
3932 (errmsg_internal("could not register process for wait: error code %lu",
3935 /* Don't close pi.hProcess here - the wait thread needs access to it */
3937 CloseHandle(pi.hThread);
3939 return pi.dwProcessId;
3945 * SubPostmasterMain -- Get the fork/exec'd process into a state equivalent
3946 * to what it would be if we'd simply forked on Unix, and then
3947 * dispatch to the appropriate place.
3949 * The first two command line arguments are expected to be "--forkFOO"
3950 * (where FOO indicates which postmaster child we are to become), and
3951 * the name of a variables file that we can read to load data that would
3952 * have been inherited by fork() on Unix. Remaining arguments go to the
3953 * subprocess FooMain() routine.
3956 SubPostmasterMain(int argc, char *argv[])
3960 /* Do this sooner rather than later... */
3961 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
3963 MyProcPid = getpid(); /* reset MyProcPid */
3965 MyStartTime = time(NULL);
3968 * make sure stderr is in binary mode before anything can possibly be
3969 * written to it, in case it's actually the syslogger pipe, so the pipe
3970 * chunking protocol isn't disturbed. Non-logpipe data gets translated on
3971 * redirection (e.g. via pg_ctl -l) anyway.
3974 _setmode(fileno(stderr), _O_BINARY);
3977 /* Lose the postmaster's on-exit routines (really a no-op) */
3980 /* In EXEC_BACKEND case we will not have inherited these settings */
3981 IsPostmasterEnvironment = true;
3982 whereToSendOutput = DestNone;
3984 /* Setup essential subsystems (to ensure elog() behaves sanely) */
3985 MemoryContextInit();
3986 InitializeGUCOptions();
3988 /* Read in the variables file */
3989 memset(&port, 0, sizeof(Port));
3990 read_backend_variables(argv[2], &port);
3993 * Set reference point for stack-depth checking
3998 * Set up memory area for GSS information. Mirrors the code in ConnCreate
3999 * for the non-exec case.
4001 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
4002 port.gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
4005 (errcode(ERRCODE_OUT_OF_MEMORY),
4006 errmsg("out of memory")));
4009 /* Check we got appropriate args */
4011 elog(FATAL, "invalid subpostmaster invocation");
4014 * If appropriate, physically re-attach to shared memory segment. We want
4015 * to do this before going any further to ensure that we can attach at the
4016 * same address the postmaster used.
4018 if (strcmp(argv[1], "--forkbackend") == 0 ||
4019 strcmp(argv[1], "--forkavlauncher") == 0 ||
4020 strcmp(argv[1], "--forkavworker") == 0 ||
4021 strcmp(argv[1], "--forkboot") == 0)
4022 PGSharedMemoryReAttach();
4024 /* autovacuum needs this set before calling InitProcess */
4025 if (strcmp(argv[1], "--forkavlauncher") == 0)
4026 AutovacuumLauncherIAm();
4027 if (strcmp(argv[1], "--forkavworker") == 0)
4028 AutovacuumWorkerIAm();
4031 * Start our win32 signal implementation. This has to be done after we
4032 * read the backend variables, because we need to pick up the signal pipe
4033 * from the parent process.
4036 pgwin32_signal_initialize();
4039 /* In EXEC_BACKEND case we will not have inherited these settings */
4041 PG_SETMASK(&BlockSig);
4043 /* Read in remaining GUC variables */
4044 read_nondefault_variables();
4047 * Reload any libraries that were preloaded by the postmaster. Since we
4048 * exec'd this process, those libraries didn't come along with us; but we
4049 * should load them into all child processes to be consistent with the
4050 * non-EXEC_BACKEND behavior.
4052 process_shared_preload_libraries();
4054 /* Run backend or appropriate child */
4055 if (strcmp(argv[1], "--forkbackend") == 0)
4057 Assert(argc == 3); /* shouldn't be any more args */
4059 /* Close the postmaster's sockets */
4060 ClosePostmasterPorts(false);
4063 * Need to reinitialize the SSL library in the backend, since the
4064 * context structures contain function pointers and cannot be passed
4065 * through the parameter file.
4067 * XXX should we do this in all child processes? For the moment it's
4068 * enough to do it in backend children.
4072 secure_initialize();
4076 * Perform additional initialization and collect startup packet.
4078 * We want to do this before InitProcess() for a couple of reasons: 1.
4079 * so that we aren't eating up a PGPROC slot while waiting on the
4080 * client. 2. so that if InitProcess() fails due to being out of
4081 * PGPROC slots, we have already initialized libpq and are able to
4082 * report the error to the client.
4084 BackendInitialize(&port);
4086 /* Restore basic shared memory pointers */
4087 InitShmemAccess(UsedShmemSegAddr);
4089 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
4093 * Attach process to shared data structures. If testing EXEC_BACKEND
4094 * on Linux, you must run this as root before starting the postmaster:
4096 * echo 0 >/proc/sys/kernel/randomize_va_space
4098 * This prevents a randomized stack base address that causes child
4099 * shared memory to be at a different address than the parent, making
4100 * it impossible to attached to shared memory. Return the value to
4101 * '1' when finished.
4103 CreateSharedMemoryAndSemaphores(false, 0);
4105 /* And run the backend */
4106 BackendRun(&port); /* does not return */
4108 if (strcmp(argv[1], "--forkboot") == 0)
4110 /* Close the postmaster's sockets */
4111 ClosePostmasterPorts(false);
4113 /* Restore basic shared memory pointers */
4114 InitShmemAccess(UsedShmemSegAddr);
4116 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
4117 InitAuxiliaryProcess();
4119 /* Attach process to shared data structures */
4120 CreateSharedMemoryAndSemaphores(false, 0);
4122 AuxiliaryProcessMain(argc - 2, argv + 2); /* does not return */
4124 if (strcmp(argv[1], "--forkavlauncher") == 0)
4126 /* Close the postmaster's sockets */
4127 ClosePostmasterPorts(false);
4129 /* Restore basic shared memory pointers */
4130 InitShmemAccess(UsedShmemSegAddr);
4132 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
4135 /* Attach process to shared data structures */
4136 CreateSharedMemoryAndSemaphores(false, 0);
4138 AutoVacLauncherMain(argc - 2, argv + 2); /* does not return */
4140 if (strcmp(argv[1], "--forkavworker") == 0)
4142 /* Close the postmaster's sockets */
4143 ClosePostmasterPorts(false);
4145 /* Restore basic shared memory pointers */
4146 InitShmemAccess(UsedShmemSegAddr);
4148 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
4151 /* Attach process to shared data structures */
4152 CreateSharedMemoryAndSemaphores(false, 0);
4154 AutoVacWorkerMain(argc - 2, argv + 2); /* does not return */
4156 if (strcmp(argv[1], "--forkarch") == 0)
4158 /* Close the postmaster's sockets */
4159 ClosePostmasterPorts(false);
4161 /* Do not want to attach to shared memory */
4163 PgArchiverMain(argc, argv); /* does not return */
4165 if (strcmp(argv[1], "--forkcol") == 0)
4167 /* Close the postmaster's sockets */
4168 ClosePostmasterPorts(false);
4170 /* Do not want to attach to shared memory */
4172 PgstatCollectorMain(argc, argv); /* does not return */
4174 if (strcmp(argv[1], "--forklog") == 0)
4176 /* Close the postmaster's sockets */
4177 ClosePostmasterPorts(true);
4179 /* Do not want to attach to shared memory */
4181 SysLoggerMain(argc, argv); /* does not return */
4184 abort(); /* shouldn't get here */
4186 #endif /* EXEC_BACKEND */
4190 * ExitPostmaster -- cleanup
4192 * Do NOT call exit() directly --- always go through here!
4195 ExitPostmaster(int status)
4197 /* should cleanup shared memory and kill all backends */
4200 * Not sure of the semantics here. When the Postmaster dies, should the
4201 * backends all be killed? probably not.
4203 * MUST -- vadim 05-10-1999
4210 * sigusr1_handler - handle signal conditions from child processes
4213 sigusr1_handler(SIGNAL_ARGS)
4215 int save_errno = errno;
4217 PG_SETMASK(&BlockSig);
4220 * RECOVERY_STARTED and BEGIN_HOT_STANDBY signals are ignored in
4221 * unexpected states. If the startup process quickly starts up, completes
4222 * recovery, exits, we might process the death of the startup process
4223 * first. We don't want to go back to recovery in that case.
4225 if (CheckPostmasterSignal(PMSIGNAL_RECOVERY_STARTED) &&
4226 pmState == PM_STARTUP)
4228 /* WAL redo has started. We're out of reinitialization. */
4232 * Crank up the background tasks. It doesn't matter if this fails,
4233 * we'll just try again later.
4235 Assert(CheckpointerPID == 0);
4236 CheckpointerPID = StartCheckpointer();
4237 Assert(BgWriterPID == 0);
4238 BgWriterPID = StartBackgroundWriter();
4240 pmState = PM_RECOVERY;
4242 if (CheckPostmasterSignal(PMSIGNAL_BEGIN_HOT_STANDBY) &&
4243 pmState == PM_RECOVERY)
4246 * Likewise, start other special children as needed.
4248 Assert(PgStatPID == 0);
4249 PgStatPID = pgstat_start();
4252 (errmsg("database system is ready to accept read only connections")));
4254 pmState = PM_HOT_STANDBY;
4257 if (CheckPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER) &&
4261 * Send SIGUSR1 to archiver process, to wake it up and begin archiving
4262 * next transaction log file.
4264 signal_child(PgArchPID, SIGUSR1);
4267 if (CheckPostmasterSignal(PMSIGNAL_ROTATE_LOGFILE) &&
4270 /* Tell syslogger to rotate logfile */
4271 signal_child(SysLoggerPID, SIGUSR1);
4274 if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER))
4277 * Start one iteration of the autovacuum daemon, even if autovacuuming
4278 * is nominally not enabled. This is so we can have an active defense
4279 * against transaction ID wraparound. We set a flag for the main loop
4280 * to do it rather than trying to do it here --- this is because the
4281 * autovac process itself may send the signal, and we want to handle
4282 * that by launching another iteration as soon as the current one
4285 start_autovac_launcher = true;
4288 if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER))
4290 /* The autovacuum launcher wants us to start a worker process. */
4291 StartAutovacuumWorker();
4294 if (CheckPostmasterSignal(PMSIGNAL_START_WALRECEIVER) &&
4295 WalReceiverPID == 0 &&
4296 (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
4297 pmState == PM_HOT_STANDBY || pmState == PM_WAIT_READONLY))
4299 /* Startup Process wants us to start the walreceiver process. */
4300 WalReceiverPID = StartWalReceiver();
4303 if (CheckPostmasterSignal(PMSIGNAL_ADVANCE_STATE_MACHINE) &&
4304 (pmState == PM_WAIT_BACKUP || pmState == PM_WAIT_BACKENDS))
4306 /* Advance postmaster's state machine */
4307 PostmasterStateMachine();
4310 if (CheckPromoteSignal() && StartupPID != 0 &&
4311 (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
4312 pmState == PM_HOT_STANDBY || pmState == PM_WAIT_READONLY))
4314 /* Tell startup process to finish recovery */
4315 signal_child(StartupPID, SIGUSR2);
4318 PG_SETMASK(&UnBlockSig);
4324 * SIGTERM or SIGQUIT while processing startup packet.
4325 * Clean up and exit(1).
4327 * XXX: possible future improvement: try to send a message indicating
4328 * why we are disconnecting. Problem is to be sure we don't block while
4329 * doing so, nor mess up SSL initialization. In practice, if the client
4330 * has wedged here, it probably couldn't do anything with the message anyway.
4333 startup_die(SIGNAL_ARGS)
4339 * Dummy signal handler
4341 * We use this for signals that we don't actually use in the postmaster,
4342 * but we do use in backends. If we were to SIG_IGN such signals in the
4343 * postmaster, then a newly started backend might drop a signal that arrives
4344 * before it's able to reconfigure its signal processing. (See notes in
4348 dummy_handler(SIGNAL_ARGS)
4353 * Timeout while processing startup packet.
4354 * As for startup_die(), we clean up and exit(1).
4357 StartupPacketTimeoutHandler(void)
4367 RandomSalt(char *md5Salt)
4372 * We use % 255, sacrificing one possible byte value, so as to ensure that
4373 * all bits of the random() value participate in the result. While at it,
4374 * add one to avoid generating any null bytes.
4376 rand = PostmasterRandom();
4377 md5Salt[0] = (rand % 255) + 1;
4378 rand = PostmasterRandom();
4379 md5Salt[1] = (rand % 255) + 1;
4380 rand = PostmasterRandom();
4381 md5Salt[2] = (rand % 255) + 1;
4382 rand = PostmasterRandom();
4383 md5Salt[3] = (rand % 255) + 1;
4390 PostmasterRandom(void)
4393 * Select a random seed at the time of first receiving a request.
4395 if (random_seed == 0)
4399 struct timeval random_stop_time;
4401 gettimeofday(&random_stop_time, NULL);
4404 * We are not sure how much precision is in tv_usec, so we swap
4405 * the high and low 16 bits of 'random_stop_time' and XOR them
4406 * with 'random_start_time'. On the off chance that the result is
4407 * 0, we loop until it isn't.
4409 random_seed = random_start_time.tv_usec ^
4410 ((random_stop_time.tv_usec << 16) |
4411 ((random_stop_time.tv_usec >> 16) & 0xffff));
4413 while (random_seed == 0);
4415 srandom(random_seed);
4422 * Count up number of child processes of specified types (dead_end chidren
4423 * are always excluded).
4426 CountChildren(int target)
4431 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
4433 Backend *bp = (Backend *) DLE_VAL(curr);
4439 * Since target == BACKEND_TYPE_ALL is the most common case, we test
4440 * it first and avoid touching shared memory for every child.
4442 if (target != BACKEND_TYPE_ALL)
4446 if (bp->is_autovacuum)
4447 child = BACKEND_TYPE_AUTOVAC;
4448 else if (IsPostmasterChildWalSender(bp->child_slot))
4449 child = BACKEND_TYPE_WALSND;
4451 child = BACKEND_TYPE_NORMAL;
4452 if (!(target & child))
4463 * StartChildProcess -- start an auxiliary process for the postmaster
4465 * xlop determines what kind of child will be started. All child types
4466 * initially go to AuxiliaryProcessMain, which will handle common setup.
4468 * Return value of StartChildProcess is subprocess' PID, or 0 if failed
4469 * to start subprocess.
4472 StartChildProcess(AuxProcType type)
4480 * Set up command-line arguments for subprocess
4482 av[ac++] = "postgres";
4485 av[ac++] = "--forkboot";
4486 av[ac++] = NULL; /* filled in by postmaster_forkexec */
4489 snprintf(typebuf, sizeof(typebuf), "-x%d", type);
4493 Assert(ac < lengthof(av));
4496 pid = postmaster_forkexec(ac, av);
4497 #else /* !EXEC_BACKEND */
4498 pid = fork_process();
4500 if (pid == 0) /* child */
4502 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
4504 /* Close the postmaster's sockets */
4505 ClosePostmasterPorts(false);
4507 /* Lose the postmaster's on-exit routines and port connections */
4510 /* Release postmaster's working memory context */
4511 MemoryContextSwitchTo(TopMemoryContext);
4512 MemoryContextDelete(PostmasterContext);
4513 PostmasterContext = NULL;
4515 AuxiliaryProcessMain(ac, av);
4518 #endif /* EXEC_BACKEND */
4522 /* in parent, fork failed */
4523 int save_errno = errno;
4528 case StartupProcess:
4530 (errmsg("could not fork startup process: %m")));
4532 case BgWriterProcess:
4534 (errmsg("could not fork background writer process: %m")));
4536 case CheckpointerProcess:
4538 (errmsg("could not fork checkpointer process: %m")));
4540 case WalWriterProcess:
4542 (errmsg("could not fork WAL writer process: %m")));
4544 case WalReceiverProcess:
4546 (errmsg("could not fork WAL receiver process: %m")));
4550 (errmsg("could not fork process: %m")));
4555 * fork failure is fatal during startup, but there's no need to choke
4556 * immediately if starting other child types fails.
4558 if (type == StartupProcess)
4564 * in parent, successful fork
4570 * StartAutovacuumWorker
4571 * Start an autovac worker process.
4573 * This function is here because it enters the resulting PID into the
4574 * postmaster's private backends list.
4576 * NB -- this code very roughly matches BackendStartup.
4579 StartAutovacuumWorker(void)
4584 * If not in condition to run a process, don't try, but handle it like a
4585 * fork failure. This does not normally happen, since the signal is only
4586 * supposed to be sent by autovacuum launcher when it's OK to do it, but
4587 * we have to check to avoid race-condition problems during DB state
4590 if (canAcceptConnections() == CAC_OK)
4592 bn = (Backend *) malloc(sizeof(Backend));
4596 * Compute the cancel key that will be assigned to this session.
4597 * We probably don't need cancel keys for autovac workers, but
4598 * we'd better have something random in the field to prevent
4599 * unfriendly people from sending cancels to them.
4601 MyCancelKey = PostmasterRandom();
4602 bn->cancel_key = MyCancelKey;
4604 /* Autovac workers are not dead_end and need a child slot */
4605 bn->dead_end = false;
4606 bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
4608 bn->pid = StartAutoVacWorker();
4611 bn->is_autovacuum = true;
4612 DLInitElem(&bn->elem, bn);
4613 DLAddHead(BackendList, &bn->elem);
4615 ShmemBackendArrayAdd(bn);
4622 * fork failed, fall through to report -- actual error message was
4623 * logged by StartAutoVacWorker
4625 (void) ReleasePostmasterChildSlot(bn->child_slot);
4630 (errcode(ERRCODE_OUT_OF_MEMORY),
4631 errmsg("out of memory")));
4635 * Report the failure to the launcher, if it's running. (If it's not, we
4636 * might not even be connected to shared memory, so don't try to call
4637 * AutoVacWorkerFailed.) Note that we also need to signal it so that it
4638 * responds to the condition, but we don't do that here, instead waiting
4639 * for ServerLoop to do it. This way we avoid a ping-pong signalling in
4640 * quick succession between the autovac launcher and postmaster in case
4643 if (AutoVacPID != 0)
4645 AutoVacWorkerFailed();
4646 avlauncher_needs_signal = true;
4651 * Create the opts file
4654 CreateOptsFile(int argc, char *argv[], char *fullprogname)
4659 #define OPTS_FILE "postmaster.opts"
4661 if ((fp = fopen(OPTS_FILE, "w")) == NULL)
4663 elog(LOG, "could not create file \"%s\": %m", OPTS_FILE);
4667 fprintf(fp, "%s", fullprogname);
4668 for (i = 1; i < argc; i++)
4669 fprintf(fp, " \"%s\"", argv[i]);
4674 elog(LOG, "could not write file \"%s\": %m", OPTS_FILE);
4683 * MaxLivePostmasterChildren
4685 * This reports the number of entries needed in per-child-process arrays
4686 * (the PMChildFlags array, and if EXEC_BACKEND the ShmemBackendArray).
4687 * These arrays include regular backends, autovac workers and walsenders,
4688 * but not special children nor dead_end children. This allows the arrays
4689 * to have a fixed maximum size, to wit the same too-many-children limit
4690 * enforced by canAcceptConnections(). The exact value isn't too critical
4691 * as long as it's more than MaxBackends.
4694 MaxLivePostmasterChildren(void)
4696 return 2 * MaxBackends;
4703 * The following need to be available to the save/restore_backend_variables
4706 extern slock_t *ShmemLock;
4707 extern LWLock *LWLockArray;
4708 extern slock_t *ProcStructLock;
4709 extern PGPROC *AuxiliaryProcs;
4710 extern PMSignalData *PMSignalState;
4711 extern pgsocket pgStatSock;
4714 #define write_inheritable_socket(dest, src, childpid) ((*(dest) = (src)), true)
4715 #define read_inheritable_socket(dest, src) (*(dest) = *(src))
4717 static bool write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE child);
4718 static bool write_inheritable_socket(InheritableSocket *dest, SOCKET src,
4720 static void read_inheritable_socket(SOCKET *dest, InheritableSocket *src);
4724 /* Save critical backend variables into the BackendParameters struct */
4727 save_backend_variables(BackendParameters *param, Port *port)
4730 save_backend_variables(BackendParameters *param, Port *port,
4731 HANDLE childProcess, pid_t childPid)
4734 memcpy(¶m->port, port, sizeof(Port));
4735 if (!write_inheritable_socket(¶m->portsocket, port->sock, childPid))
4738 strlcpy(param->DataDir, DataDir, MAXPGPATH);
4740 memcpy(¶m->ListenSocket, &ListenSocket, sizeof(ListenSocket));
4742 param->MyCancelKey = MyCancelKey;
4743 param->MyPMChildSlot = MyPMChildSlot;
4745 param->UsedShmemSegID = UsedShmemSegID;
4746 param->UsedShmemSegAddr = UsedShmemSegAddr;
4748 param->ShmemLock = ShmemLock;
4749 param->ShmemVariableCache = ShmemVariableCache;
4750 param->ShmemBackendArray = ShmemBackendArray;
4752 param->LWLockArray = LWLockArray;
4753 param->ProcStructLock = ProcStructLock;
4754 param->ProcGlobal = ProcGlobal;
4755 param->AuxiliaryProcs = AuxiliaryProcs;
4756 param->PreparedXactProcs = PreparedXactProcs;
4757 param->PMSignalState = PMSignalState;
4758 if (!write_inheritable_socket(¶m->pgStatSock, pgStatSock, childPid))
4761 param->PostmasterPid = PostmasterPid;
4762 param->PgStartTime = PgStartTime;
4763 param->PgReloadTime = PgReloadTime;
4765 param->redirection_done = redirection_done;
4766 param->IsBinaryUpgrade = IsBinaryUpgrade;
4767 param->max_safe_fds = max_safe_fds;
4770 param->PostmasterHandle = PostmasterHandle;
4771 if (!write_duplicated_handle(¶m->initial_signal_pipe,
4772 pgwin32_create_signal_listener(childPid),
4776 memcpy(¶m->postmaster_alive_fds, &postmaster_alive_fds,
4777 sizeof(postmaster_alive_fds));
4780 memcpy(¶m->syslogPipe, &syslogPipe, sizeof(syslogPipe));
4782 strlcpy(param->my_exec_path, my_exec_path, MAXPGPATH);
4784 strlcpy(param->pkglib_path, pkglib_path, MAXPGPATH);
4786 strlcpy(param->ExtraOptions, ExtraOptions, MAXPGPATH);
4794 * Duplicate a handle for usage in a child process, and write the child
4795 * process instance of the handle to the parameter file.
4798 write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE childProcess)
4800 HANDLE hChild = INVALID_HANDLE_VALUE;
4802 if (!DuplicateHandle(GetCurrentProcess(),
4808 DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS))
4811 (errmsg_internal("could not duplicate handle to be written to backend parameter file: error code %lu",
4821 * Duplicate a socket for usage in a child process, and write the resulting
4822 * structure to the parameter file.
4823 * This is required because a number of LSPs (Layered Service Providers) very
4824 * common on Windows (antivirus, firewalls, download managers etc) break
4825 * straight socket inheritance.
4828 write_inheritable_socket(InheritableSocket *dest, SOCKET src, pid_t childpid)
4830 dest->origsocket = src;
4831 if (src != 0 && src != PGINVALID_SOCKET)
4834 if (WSADuplicateSocket(src, childpid, &dest->wsainfo) != 0)
4837 (errmsg("could not duplicate socket %d for use in backend: error code %d",
4838 (int) src, WSAGetLastError())));
4846 * Read a duplicate socket structure back, and get the socket descriptor.
4849 read_inheritable_socket(SOCKET *dest, InheritableSocket *src)
4853 if (src->origsocket == PGINVALID_SOCKET || src->origsocket == 0)
4855 /* Not a real socket! */
4856 *dest = src->origsocket;
4860 /* Actual socket, so create from structure */
4861 s = WSASocket(FROM_PROTOCOL_INFO,
4867 if (s == INVALID_SOCKET)
4869 write_stderr("could not create inherited socket: error code %d\n",
4876 * To make sure we don't get two references to the same socket, close
4877 * the original one. (This would happen when inheritance actually
4880 closesocket(src->origsocket);
4886 read_backend_variables(char *id, Port *port)
4888 BackendParameters param;
4891 /* Non-win32 implementation reads from file */
4895 fp = AllocateFile(id, PG_BINARY_R);
4898 write_stderr("could not read from backend variables file \"%s\": %s\n",
4899 id, strerror(errno));
4903 if (fread(¶m, sizeof(param), 1, fp) != 1)
4905 write_stderr("could not read from backend variables file \"%s\": %s\n",
4906 id, strerror(errno));
4912 if (unlink(id) != 0)
4914 write_stderr("could not remove file \"%s\": %s\n",
4915 id, strerror(errno));
4919 /* Win32 version uses mapped file */
4921 BackendParameters *paramp;
4924 paramHandle = (HANDLE) _atoi64(id);
4926 paramHandle = (HANDLE) atol(id);
4928 paramp = MapViewOfFile(paramHandle, FILE_MAP_READ, 0, 0, 0);
4931 write_stderr("could not map view of backend variables: error code %lu\n",
4936 memcpy(¶m, paramp, sizeof(BackendParameters));
4938 if (!UnmapViewOfFile(paramp))
4940 write_stderr("could not unmap view of backend variables: error code %lu\n",
4945 if (!CloseHandle(paramHandle))
4947 write_stderr("could not close handle to backend parameter variables: error code %lu\n",
4953 restore_backend_variables(¶m, port);
4956 /* Restore critical backend variables from the BackendParameters struct */
4958 restore_backend_variables(BackendParameters *param, Port *port)
4960 memcpy(port, ¶m->port, sizeof(Port));
4961 read_inheritable_socket(&port->sock, ¶m->portsocket);
4963 SetDataDir(param->DataDir);
4965 memcpy(&ListenSocket, ¶m->ListenSocket, sizeof(ListenSocket));
4967 MyCancelKey = param->MyCancelKey;
4968 MyPMChildSlot = param->MyPMChildSlot;
4970 UsedShmemSegID = param->UsedShmemSegID;
4971 UsedShmemSegAddr = param->UsedShmemSegAddr;
4973 ShmemLock = param->ShmemLock;
4974 ShmemVariableCache = param->ShmemVariableCache;
4975 ShmemBackendArray = param->ShmemBackendArray;
4977 LWLockArray = param->LWLockArray;
4978 ProcStructLock = param->ProcStructLock;
4979 ProcGlobal = param->ProcGlobal;
4980 AuxiliaryProcs = param->AuxiliaryProcs;
4981 PreparedXactProcs = param->PreparedXactProcs;
4982 PMSignalState = param->PMSignalState;
4983 read_inheritable_socket(&pgStatSock, ¶m->pgStatSock);
4985 PostmasterPid = param->PostmasterPid;
4986 PgStartTime = param->PgStartTime;
4987 PgReloadTime = param->PgReloadTime;
4989 redirection_done = param->redirection_done;
4990 IsBinaryUpgrade = param->IsBinaryUpgrade;
4991 max_safe_fds = param->max_safe_fds;
4994 PostmasterHandle = param->PostmasterHandle;
4995 pgwin32_initial_signal_pipe = param->initial_signal_pipe;
4997 memcpy(&postmaster_alive_fds, ¶m->postmaster_alive_fds,
4998 sizeof(postmaster_alive_fds));
5001 memcpy(&syslogPipe, ¶m->syslogPipe, sizeof(syslogPipe));
5003 strlcpy(my_exec_path, param->my_exec_path, MAXPGPATH);
5005 strlcpy(pkglib_path, param->pkglib_path, MAXPGPATH);
5007 strlcpy(ExtraOptions, param->ExtraOptions, MAXPGPATH);
5012 ShmemBackendArraySize(void)
5014 return mul_size(MaxLivePostmasterChildren(), sizeof(Backend));
5018 ShmemBackendArrayAllocation(void)
5020 Size size = ShmemBackendArraySize();
5022 ShmemBackendArray = (Backend *) ShmemAlloc(size);
5023 /* Mark all slots as empty */
5024 memset(ShmemBackendArray, 0, size);
5028 ShmemBackendArrayAdd(Backend *bn)
5030 /* The array slot corresponding to my PMChildSlot should be free */
5031 int i = bn->child_slot - 1;
5033 Assert(ShmemBackendArray[i].pid == 0);
5034 ShmemBackendArray[i] = *bn;
5038 ShmemBackendArrayRemove(Backend *bn)
5040 int i = bn->child_slot - 1;
5042 Assert(ShmemBackendArray[i].pid == bn->pid);
5043 /* Mark the slot as empty */
5044 ShmemBackendArray[i].pid = 0;
5046 #endif /* EXEC_BACKEND */
5052 * Subset implementation of waitpid() for Windows. We assume pid is -1
5053 * (that is, check all child processes) and options is WNOHANG (don't wait).
5056 waitpid(pid_t pid, int *exitstatus, int options)
5063 * Check if there are any dead children. If there are, return the pid of
5064 * the first one that died.
5066 if (GetQueuedCompletionStatus(win32ChildQueue, &dwd, &key, &ovl, 0))
5068 *exitstatus = (int) key;
5076 * Note! Code below executes on a thread pool! All operations must
5077 * be thread safe! Note that elog() and friends must *not* be used.
5080 pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
5082 win32_deadchild_waitinfo *childinfo = (win32_deadchild_waitinfo *) lpParameter;
5085 if (TimerOrWaitFired)
5086 return; /* timeout. Should never happen, since we use
5087 * INFINITE as timeout value. */
5090 * Remove handle from wait - required even though it's set to wait only
5093 UnregisterWaitEx(childinfo->waitHandle, NULL);
5095 if (!GetExitCodeProcess(childinfo->procHandle, &exitcode))
5098 * Should never happen. Inform user and set a fixed exitcode.
5100 write_stderr("could not read exit code for process\n");
5104 if (!PostQueuedCompletionStatus(win32ChildQueue, childinfo->procId, (ULONG_PTR) exitcode, NULL))
5105 write_stderr("could not post child completion status\n");
5108 * Handle is per-process, so we close it here instead of in the
5109 * originating thread
5111 CloseHandle(childinfo->procHandle);
5114 * Free struct that was allocated before the call to
5115 * RegisterWaitForSingleObject()
5119 /* Queue SIGCHLD signal */
5120 pg_queue_signal(SIGCHLD);
5125 * Initialize one and only handle for monitoring postmaster death.
5127 * Called once in the postmaster, so that child processes can subsequently
5128 * monitor if their parent is dead.
5131 InitPostmasterDeathWatchHandle(void)
5136 * Create a pipe. Postmaster holds the write end of the pipe open
5137 * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
5138 * the read file descriptor to select() to wake up in case postmaster
5139 * dies, or check for postmaster death with a (read() == 0). Children must
5140 * close the write end as soon as possible after forking, because EOF
5141 * won't be signaled in the read end until all processes have closed the
5142 * write fd. That is taken care of in ClosePostmasterPorts().
5144 Assert(MyProcPid == PostmasterPid);
5145 if (pipe(postmaster_alive_fds))
5147 (errcode_for_file_access(),
5148 errmsg_internal("could not create pipe to monitor postmaster death: %m")));
5151 * Set O_NONBLOCK to allow testing for the fd's presence with a read()
5154 if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK))
5156 (errcode_for_socket_access(),
5157 errmsg_internal("could not set postmaster death monitoring pipe to non-blocking mode: %m")));
5161 * On Windows, we use a process handle for the same purpose.
5163 if (DuplicateHandle(GetCurrentProcess(),
5164 GetCurrentProcess(),
5165 GetCurrentProcess(),
5169 DUPLICATE_SAME_ACCESS) == 0)
5171 (errmsg_internal("could not duplicate postmaster handle: error code %lu",