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-2013, 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/ilist.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/bgworker_internals.h"
107 #include "postmaster/fork_process.h"
108 #include "postmaster/pgarch.h"
109 #include "postmaster/postmaster.h"
110 #include "postmaster/syslogger.h"
111 #include "replication/walsender.h"
112 #include "storage/fd.h"
113 #include "storage/ipc.h"
114 #include "storage/pg_shmem.h"
115 #include "storage/pmsignal.h"
116 #include "storage/proc.h"
117 #include "tcop/tcopprot.h"
118 #include "utils/builtins.h"
119 #include "utils/datetime.h"
120 #include "utils/dynamic_loader.h"
121 #include "utils/guc.h"
122 #include "utils/memutils.h"
123 #include "utils/ps_status.h"
124 #include "utils/timeout.h"
127 #include "storage/spin.h"
132 * Possible types of a backend. Beyond being the possible bkend_type values in
133 * struct bkend, these are OR-able request flag bits for SignalSomeChildren()
134 * and CountChildren().
136 #define BACKEND_TYPE_NORMAL 0x0001 /* normal backend */
137 #define BACKEND_TYPE_AUTOVAC 0x0002 /* autovacuum worker process */
138 #define BACKEND_TYPE_WALSND 0x0004 /* walsender process */
139 #define BACKEND_TYPE_BGWORKER 0x0008 /* bgworker process */
140 #define BACKEND_TYPE_ALL 0x000F /* OR of all the above */
142 #define BACKEND_TYPE_WORKER (BACKEND_TYPE_AUTOVAC | BACKEND_TYPE_BGWORKER)
145 * List of active backends (or child processes anyway; we don't actually
146 * know whether a given child has become a backend or is still in the
147 * authorization phase). This is used mainly to keep track of how many
148 * children we have and send them appropriate signals when necessary.
150 * "Special" children such as the startup, bgwriter and autovacuum launcher
151 * tasks are not in this list. Autovacuum worker and walsender are in it.
152 * Also, "dead_end" children are in it: these are children launched just for
153 * the purpose of sending a friendly rejection message to a would-be client.
154 * We must track them because they are attached to shared memory, but we know
155 * they will never become live backends. dead_end children are not assigned a
158 * Background workers that request shared memory access during registration are
163 pid_t pid; /* process id of backend */
164 long cancel_key; /* cancel key for cancels for this backend */
165 int child_slot; /* PMChildSlot for this backend, if any */
168 * Flavor of backend or auxiliary process. Note that BACKEND_TYPE_WALSND
169 * backends initially announce themselves as BACKEND_TYPE_NORMAL, so if
170 * bkend_type is normal, you should check for a recent transition.
173 bool dead_end; /* is it going to send an error and quit? */
174 bool bgworker_notify; /* gets bgworker start/stop notifications */
175 dlist_node elem; /* list link in BackendList */
178 static dlist_head BackendList = DLIST_STATIC_INIT(BackendList);
181 static Backend *ShmemBackendArray;
184 BackgroundWorker *MyBgworkerEntry = NULL;
188 /* The socket number we are listening for connections on */
191 /* The directory names for Unix socket(s) */
192 char *Unix_socket_directories;
194 /* The TCP listen address(es) */
195 char *ListenAddresses;
198 * ReservedBackends is the number of backends reserved for superuser use.
199 * This number is taken out of the pool size given by MaxBackends so
200 * number of backend slots available to non-superusers is
201 * (MaxBackends - ReservedBackends). Note what this really means is
202 * "if there are <= ReservedBackends connections available, only superusers
203 * can make new connections" --- pre-existing superuser connections don't
204 * count against the limit.
206 int ReservedBackends;
208 /* The socket(s) we're listening to. */
210 static pgsocket ListenSocket[MAXLISTEN];
213 * Set by the -o option
215 static char ExtraOptions[MAXPGPATH];
218 * These globals control the behavior of the postmaster in case some
219 * backend dumps core. Normally, it kills all peers of the dead backend
220 * and reinitializes shared memory. By specifying -s or -n, we can have
221 * the postmaster stop (rather than kill) peers and not reinitialize
222 * shared data structures. (Reinit is currently dead code, though.)
224 static bool Reinit = true;
225 static int SendStop = false;
227 /* still more option variables */
228 bool EnableSSL = false;
230 int PreAuthDelay = 0;
231 int AuthenticationTimeout = 60;
233 bool log_hostname; /* for ps display and logging */
234 bool Log_connections = false;
235 bool Db_user_namespace = false;
237 bool enable_bonjour = false;
239 bool restart_after_crash = true;
241 char *output_config_variable = NULL;
243 /* PIDs of special child processes; 0 when not running */
244 static pid_t StartupPID = 0,
254 /* Startup/shutdown state */
256 #define SmartShutdown 1
257 #define FastShutdown 2
258 #define ImmediateShutdown 3
260 static int Shutdown = NoShutdown;
262 static bool FatalError = false; /* T if recovering from backend crash */
263 static bool RecoveryError = false; /* T if WAL recovery failed */
266 * We use a simple state machine to control startup, shutdown, and
267 * crash recovery (which is rather like shutdown followed by startup).
269 * After doing all the postmaster initialization work, we enter PM_STARTUP
270 * state and the startup process is launched. The startup process begins by
271 * reading the control file and other preliminary initialization steps.
272 * In a normal startup, or after crash recovery, the startup process exits
273 * with exit code 0 and we switch to PM_RUN state. However, archive recovery
274 * is handled specially since it takes much longer and we would like to support
275 * hot standby during archive recovery.
277 * When the startup process is ready to start archive recovery, it signals the
278 * postmaster, and we switch to PM_RECOVERY state. The background writer and
279 * checkpointer are launched, while the startup process continues applying WAL.
280 * If Hot Standby is enabled, then, after reaching a consistent point in WAL
281 * redo, startup process signals us again, and we switch to PM_HOT_STANDBY
282 * state and begin accepting connections to perform read-only queries. When
283 * archive recovery is finished, the startup process exits with exit code 0
284 * and we switch to PM_RUN state.
286 * Normal child backends can only be launched when we are in PM_RUN or
287 * PM_HOT_STANDBY state. (We also allow launch of normal
288 * child backends in PM_WAIT_BACKUP state, but only for superusers.)
289 * In other states we handle connection requests by launching "dead_end"
290 * child processes, which will simply send the client an error message and
291 * quit. (We track these in the BackendList so that we can know when they
292 * are all gone; this is important because they're still connected to shared
293 * memory, and would interfere with an attempt to destroy the shmem segment,
294 * possibly leading to SHMALL failure when we try to make a new one.)
295 * In PM_WAIT_DEAD_END state we are waiting for all the dead_end children
296 * to drain out of the system, and therefore stop accepting connection
297 * requests at all until the last existing child has quit (which hopefully
298 * will not be very long).
300 * Notice that this state variable does not distinguish *why* we entered
301 * states later than PM_RUN --- Shutdown and FatalError must be consulted
302 * to find that out. FatalError is never true in PM_RECOVERY_* or PM_RUN
303 * states, nor in PM_SHUTDOWN states (because we don't enter those states
304 * when trying to recover from a crash). It can be true in PM_STARTUP state,
305 * because we don't clear it until we've successfully started WAL redo.
306 * Similarly, RecoveryError means that we have crashed during recovery, and
307 * should not try to restart.
311 PM_INIT, /* postmaster starting */
312 PM_STARTUP, /* waiting for startup subprocess */
313 PM_RECOVERY, /* in archive recovery mode */
314 PM_HOT_STANDBY, /* in hot standby mode */
315 PM_RUN, /* normal "database is alive" state */
316 PM_WAIT_BACKUP, /* waiting for online backup mode to end */
317 PM_WAIT_READONLY, /* waiting for read only backends to exit */
318 PM_WAIT_BACKENDS, /* waiting for live backends to exit */
319 PM_SHUTDOWN, /* waiting for checkpointer to do shutdown
321 PM_SHUTDOWN_2, /* waiting for archiver and walsenders to
323 PM_WAIT_DEAD_END, /* waiting for dead_end children to exit */
324 PM_NO_CHILDREN /* all important children have exited */
327 static PMState pmState = PM_INIT;
329 /* Start time of abort processing at immediate shutdown or child crash */
330 static time_t AbortStartTime;
331 #define SIGKILL_CHILDREN_AFTER_SECS 5
333 static bool ReachedNormalRunning = false; /* T if we've reached PM_RUN */
335 bool ClientAuthInProgress = false; /* T during new-client
338 bool redirection_done = false; /* stderr redirected for syslogger? */
340 /* received START_AUTOVAC_LAUNCHER signal */
341 static volatile sig_atomic_t start_autovac_launcher = false;
343 /* the launcher needs to be signalled to communicate some condition */
344 static volatile bool avlauncher_needs_signal = false;
346 /* set when there's a worker that needs to be started up */
347 static volatile bool StartWorkerNeeded = true;
348 static volatile bool HaveCrashedWorker = false;
351 * State for assigning random salts and cancel keys.
352 * Also, the global MyCancelKey passes the cancel key assigned to a given
353 * backend from the postmaster to that backend (via fork).
355 static unsigned int random_seed = 0;
356 static struct timeval random_start_time;
362 #ifdef HAVE_INT_OPTRESET
363 extern int optreset; /* might not be declared by system headers */
367 static DNSServiceRef bonjour_sdref = NULL;
371 * postmaster.c - function prototypes
373 static void unlink_external_pid_file(int status, Datum arg);
374 static void getInstallationPaths(const char *argv0);
375 static void checkDataDir(void);
376 static Port *ConnCreate(int serverFd);
377 static void ConnFree(Port *port);
378 static void reset_shared(int port);
379 static void SIGHUP_handler(SIGNAL_ARGS);
380 static void pmdie(SIGNAL_ARGS);
381 static void reaper(SIGNAL_ARGS);
382 static void sigusr1_handler(SIGNAL_ARGS);
383 static void startup_die(SIGNAL_ARGS);
384 static void dummy_handler(SIGNAL_ARGS);
385 static void StartupPacketTimeoutHandler(void);
386 static void CleanupBackend(int pid, int exitstatus);
387 static bool CleanupBackgroundWorker(int pid, int exitstatus);
388 static void HandleChildCrash(int pid, int exitstatus, const char *procname);
389 static void LogChildExit(int lev, const char *procname,
390 int pid, int exitstatus);
391 static void PostmasterStateMachine(void);
392 static void BackendInitialize(Port *port);
393 static void BackendRun(Port *port) __attribute__((noreturn));
394 static void ExitPostmaster(int status) __attribute__((noreturn));
395 static int ServerLoop(void);
396 static int BackendStartup(Port *port);
397 static int ProcessStartupPacket(Port *port, bool SSLdone);
398 static void processCancelRequest(Port *port, void *pkt);
399 static int initMasks(fd_set *rmask);
400 static void report_fork_failure_to_client(Port *port, int errnum);
401 static CAC_state canAcceptConnections(void);
402 static long PostmasterRandom(void);
403 static void RandomSalt(char *md5Salt);
404 static void signal_child(pid_t pid, int signal);
405 static bool SignalSomeChildren(int signal, int targets);
406 static bool SignalUnconnectedWorkers(int signal);
407 static void TerminateChildren(int signal);
409 #define SignalChildren(sig) SignalSomeChildren(sig, BACKEND_TYPE_ALL)
411 static int CountChildren(int target);
412 static int CountUnconnectedWorkers(void);
413 static void maybe_start_bgworker(void);
414 static bool CreateOptsFile(int argc, char *argv[], char *fullprogname);
415 static pid_t StartChildProcess(AuxProcType type);
416 static void StartAutovacuumWorker(void);
417 static void InitPostmasterDeathWatchHandle(void);
422 #define WNOHANG 0 /* ignored, so any integer value will do */
424 static pid_t waitpid(pid_t pid, int *exitstatus, int options);
425 static void WINAPI pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired);
427 static HANDLE win32ChildQueue;
434 } win32_deadchild_waitinfo;
437 static pid_t backend_forkexec(Port *port);
438 static pid_t internal_forkexec(int argc, char *argv[], Port *port);
440 /* Type for a socket that can be inherited to a client process */
444 SOCKET origsocket; /* Original socket value, or PGINVALID_SOCKET
446 WSAPROTOCOL_INFO wsainfo;
449 typedef int InheritableSocket;
452 typedef struct LWLock LWLock; /* ugly kluge */
455 * Structure contains all variables passed to exec:ed backends
460 InheritableSocket portsocket;
461 char DataDir[MAXPGPATH];
462 pgsocket ListenSocket[MAXLISTEN];
466 unsigned long UsedShmemSegID;
468 HANDLE UsedShmemSegID;
470 void *UsedShmemSegAddr;
472 VariableCache ShmemVariableCache;
473 Backend *ShmemBackendArray;
475 slock_t *ProcStructLock;
476 PROC_HDR *ProcGlobal;
477 PGPROC *AuxiliaryProcs;
478 PGPROC *PreparedXactProcs;
479 PMSignalData *PMSignalState;
480 InheritableSocket pgStatSock;
482 TimestampTz PgStartTime;
483 TimestampTz PgReloadTime;
484 pg_time_t first_syslogger_file_time;
485 bool redirection_done;
486 bool IsBinaryUpgrade;
490 HANDLE PostmasterHandle;
491 HANDLE initial_signal_pipe;
492 HANDLE syslogPipe[2];
494 int postmaster_alive_fds[2];
497 char my_exec_path[MAXPGPATH];
498 char pkglib_path[MAXPGPATH];
499 char ExtraOptions[MAXPGPATH];
502 static void read_backend_variables(char *id, Port *port);
503 static void restore_backend_variables(BackendParameters *param, Port *port);
506 static bool save_backend_variables(BackendParameters *param, Port *port);
508 static bool save_backend_variables(BackendParameters *param, Port *port,
509 HANDLE childProcess, pid_t childPid);
512 static void ShmemBackendArrayAdd(Backend *bn);
513 static void ShmemBackendArrayRemove(Backend *bn);
514 #endif /* EXEC_BACKEND */
516 #define StartupDataBase() StartChildProcess(StartupProcess)
517 #define StartBackgroundWriter() StartChildProcess(BgWriterProcess)
518 #define StartCheckpointer() StartChildProcess(CheckpointerProcess)
519 #define StartWalWriter() StartChildProcess(WalWriterProcess)
520 #define StartWalReceiver() StartChildProcess(WalReceiverProcess)
522 /* Macros to check exit status of a child process */
523 #define EXIT_STATUS_0(st) ((st) == 0)
524 #define EXIT_STATUS_1(st) (WIFEXITED(st) && WEXITSTATUS(st) == 1)
528 * File descriptors for pipe used to monitor if postmaster is alive.
529 * First is POSTMASTER_FD_WATCH, second is POSTMASTER_FD_OWN.
531 int postmaster_alive_fds[2] = {-1, -1};
533 /* Process handle of postmaster used for the same purpose on Windows */
534 HANDLE PostmasterHandle;
538 * Postmaster main entry point
541 PostmasterMain(int argc, char *argv[])
545 char *userDoption = NULL;
546 bool listen_addr_saved = false;
549 MyProcPid = PostmasterPid = getpid();
551 MyStartTime = time(NULL);
553 IsPostmasterEnvironment = true;
556 * for security, no dir or file created can be group or other accessible
558 umask(S_IRWXG | S_IRWXO);
561 * Fire up essential subsystems: memory management
566 * By default, palloc() requests in the postmaster will be allocated in
567 * the PostmasterContext, which is space that can be recycled by backends.
568 * Allocated data that needs to be available to backends should be
569 * allocated in TopMemoryContext.
571 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
573 ALLOCSET_DEFAULT_MINSIZE,
574 ALLOCSET_DEFAULT_INITSIZE,
575 ALLOCSET_DEFAULT_MAXSIZE);
576 MemoryContextSwitchTo(PostmasterContext);
578 /* Initialize paths to installation files */
579 getInstallationPaths(argv[0]);
584 InitializeGUCOptions();
589 * Parse command-line options. CAUTION: keep this in sync with
590 * tcop/postgres.c (the option sets should not conflict) and with the
591 * common help() function in main/main.c.
593 while ((opt = getopt(argc, argv, "A:B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:W:-:")) != -1)
598 SetConfigOption("debug_assertions", optarg, PGC_POSTMASTER, PGC_S_ARGV);
602 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
606 /* Undocumented flag used for binary upgrades */
607 IsBinaryUpgrade = true;
611 output_config_variable = strdup(optarg);
615 userDoption = strdup(optarg);
619 set_debug_options(atoi(optarg), PGC_POSTMASTER, PGC_S_ARGV);
623 SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
627 SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
631 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
635 if (!set_plan_disabling_options(optarg, PGC_POSTMASTER, PGC_S_ARGV))
637 write_stderr("%s: invalid argument for option -f: \"%s\"\n",
644 SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
648 SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
652 /* only used by interactive backend */
656 SetConfigOption("unix_socket_directories", optarg, PGC_POSTMASTER, PGC_S_ARGV);
660 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
664 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
668 /* Don't reinit shared mem after abnormal exit */
673 SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
677 /* Other options to pass to the backend on the command line */
678 snprintf(ExtraOptions + strlen(ExtraOptions),
679 sizeof(ExtraOptions) - strlen(ExtraOptions),
684 SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
688 SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
692 /* only used by single-user backend */
696 SetConfigOption("work_mem", optarg, PGC_POSTMASTER, PGC_S_ARGV);
700 SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
706 * In the event that some backend dumps core, send SIGSTOP,
707 * rather than SIGQUIT, to all its peers. This lets the wily
708 * post_hacker collect core dumps from everyone.
715 const char *tmp = get_stats_option_name(optarg);
719 SetConfigOption(tmp, "true", PGC_POSTMASTER, PGC_S_ARGV);
723 write_stderr("%s: invalid argument for option -t: \"%s\"\n",
731 SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
740 ParseLongOption(optarg, &name, &value);
745 (errcode(ERRCODE_SYNTAX_ERROR),
746 errmsg("--%s requires a value",
750 (errcode(ERRCODE_SYNTAX_ERROR),
751 errmsg("-c %s requires a value",
755 SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
763 write_stderr("Try \"%s --help\" for more information.\n",
770 * Postmaster accepts no non-option switch arguments.
774 write_stderr("%s: invalid argument: \"%s\"\n",
775 progname, argv[optind]);
776 write_stderr("Try \"%s --help\" for more information.\n",
782 * Locate the proper configuration files and data directory, and read
783 * postgresql.conf for the first time.
785 if (!SelectConfigFiles(userDoption, progname))
788 if (output_config_variable != NULL)
791 * permission is handled because the user is reading inside the data
794 puts(GetConfigOption(output_config_variable, false, false));
798 /* Verify that DataDir looks reasonable */
801 /* And switch working directory into it */
805 * Check for invalid combinations of GUC settings.
807 if (ReservedBackends >= MaxConnections)
809 write_stderr("%s: superuser_reserved_connections must be less than max_connections\n", progname);
812 if (max_wal_senders >= MaxConnections)
814 write_stderr("%s: max_wal_senders must be less than max_connections\n", progname);
817 if (XLogArchiveMode && wal_level == WAL_LEVEL_MINIMAL)
819 (errmsg("WAL archival (archive_mode=on) requires wal_level \"archive\" or \"hot_standby\"")));
820 if (max_wal_senders > 0 && wal_level == WAL_LEVEL_MINIMAL)
822 (errmsg("WAL streaming (max_wal_senders > 0) requires wal_level \"archive\" or \"hot_standby\"")));
825 * Other one-time internal sanity checks can go here, if they are fast.
826 * (Put any slow processing further down, after postmaster.pid creation.)
828 if (!CheckDateTokenTables())
830 write_stderr("%s: invalid datetoken tables, please fix\n", progname);
835 * Now that we are done processing the postmaster arguments, reset
836 * getopt(3) library so that it will work correctly in subprocesses.
839 #ifdef HAVE_INT_OPTRESET
840 optreset = 1; /* some systems need this too */
843 /* For debugging: display postmaster environment */
845 extern char **environ;
849 (errmsg_internal("%s: PostmasterMain: initial environment dump:",
852 (errmsg_internal("-----------------------------------------")));
853 for (p = environ; *p; ++p)
855 (errmsg_internal("\t%s", *p)));
857 (errmsg_internal("-----------------------------------------")));
861 * Create lockfile for data directory.
863 * We want to do this before we try to grab the input sockets, because the
864 * data directory interlock is more reliable than the socket-file
865 * interlock (thanks to whoever decided to put socket files in /tmp :-().
866 * For the same reason, it's best to grab the TCP socket(s) before the
869 CreateDataDirLockFile(true);
872 * Initialize SSL library, if specified.
880 * process any libraries that should be preloaded at postmaster start
882 process_shared_preload_libraries();
885 * Now that loadable modules have had their chance to register background
886 * workers, calculate MaxBackends.
888 InitializeMaxBackends();
891 * Establish input sockets.
893 for (i = 0; i < MAXLISTEN; i++)
894 ListenSocket[i] = PGINVALID_SOCKET;
903 /* Need a modifiable copy of ListenAddresses */
904 rawstring = pstrdup(ListenAddresses);
906 /* Parse string into list of hostnames */
907 if (!SplitIdentifierString(rawstring, ',', &elemlist))
909 /* syntax error in list */
911 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
912 errmsg("invalid list syntax in parameter \"%s\"",
913 "listen_addresses")));
918 char *curhost = (char *) lfirst(l);
920 if (strcmp(curhost, "*") == 0)
921 status = StreamServerPort(AF_UNSPEC, NULL,
922 (unsigned short) PostPortNumber,
924 ListenSocket, MAXLISTEN);
926 status = StreamServerPort(AF_UNSPEC, curhost,
927 (unsigned short) PostPortNumber,
929 ListenSocket, MAXLISTEN);
931 if (status == STATUS_OK)
934 /* record the first successful host addr in lockfile */
935 if (!listen_addr_saved)
937 AddToDataDirLockFile(LOCK_FILE_LINE_LISTEN_ADDR, curhost);
938 listen_addr_saved = true;
943 (errmsg("could not create listen socket for \"%s\"",
947 if (!success && elemlist != NIL)
949 (errmsg("could not create any TCP/IP sockets")));
956 /* Register for Bonjour only if we opened TCP socket(s) */
957 if (enable_bonjour && ListenSocket[0] != PGINVALID_SOCKET)
959 DNSServiceErrorType err;
962 * We pass 0 for interface_index, which will result in registering on
963 * all "applicable" interfaces. It's not entirely clear from the
964 * DNS-SD docs whether this would be appropriate if we have bound to
965 * just a subset of the available network interfaces.
967 err = DNSServiceRegister(&bonjour_sdref,
974 htons(PostPortNumber),
979 if (err != kDNSServiceErr_NoError)
980 elog(LOG, "DNSServiceRegister() failed: error code %ld",
984 * We don't bother to read the mDNS daemon's reply, and we expect that
985 * it will automatically terminate our registration when the socket is
986 * closed at postmaster termination. So there's nothing more to be
987 * done here. However, the bonjour_sdref is kept around so that
988 * forked children can close their copies of the socket.
993 #ifdef HAVE_UNIX_SOCKETS
994 if (Unix_socket_directories)
1001 /* Need a modifiable copy of Unix_socket_directories */
1002 rawstring = pstrdup(Unix_socket_directories);
1004 /* Parse string into list of directories */
1005 if (!SplitDirectoriesString(rawstring, ',', &elemlist))
1007 /* syntax error in list */
1009 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1010 errmsg("invalid list syntax in parameter \"%s\"",
1011 "unix_socket_directories")));
1014 foreach(l, elemlist)
1016 char *socketdir = (char *) lfirst(l);
1018 status = StreamServerPort(AF_UNIX, NULL,
1019 (unsigned short) PostPortNumber,
1021 ListenSocket, MAXLISTEN);
1023 if (status == STATUS_OK)
1026 /* record the first successful Unix socket in lockfile */
1028 AddToDataDirLockFile(LOCK_FILE_LINE_SOCKET_DIR, socketdir);
1032 (errmsg("could not create Unix-domain socket in directory \"%s\"",
1036 if (!success && elemlist != NIL)
1038 (errmsg("could not create any Unix-domain sockets")));
1040 list_free_deep(elemlist);
1046 * check that we have some socket to listen on
1048 if (ListenSocket[0] == PGINVALID_SOCKET)
1050 (errmsg("no socket created for listening")));
1053 * If no valid TCP ports, write an empty line for listen address,
1054 * indicating the Unix socket must be used. Note that this line is not
1055 * added to the lock file until there is a socket backing it.
1057 if (!listen_addr_saved)
1058 AddToDataDirLockFile(LOCK_FILE_LINE_LISTEN_ADDR, "");
1061 * Set up shared memory and semaphores.
1063 reset_shared(PostPortNumber);
1066 * Estimate number of openable files. This must happen after setting up
1067 * semaphores, because on some platforms semaphores count as open files.
1072 * Set reference point for stack-depth checking.
1077 * Initialize pipe (or process handle on Windows) that allows children to
1078 * wake up from sleep on postmaster death.
1080 InitPostmasterDeathWatchHandle();
1085 * Initialize I/O completion port used to deliver list of dead children.
1087 win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
1088 if (win32ChildQueue == NULL)
1090 (errmsg("could not create I/O completion port for child queue")));
1094 * Record postmaster options. We delay this till now to avoid recording
1095 * bogus options (eg, NBuffers too high for available memory).
1097 if (!CreateOptsFile(argc, argv, my_exec_path))
1101 /* Write out nondefault GUC settings for child processes to use */
1102 write_nondefault_variables(PGC_POSTMASTER);
1106 * Write the external PID file if requested
1108 if (external_pid_file)
1110 FILE *fpidfile = fopen(external_pid_file, "w");
1114 fprintf(fpidfile, "%d\n", MyProcPid);
1117 /* Make PID file world readable */
1118 if (chmod(external_pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) != 0)
1119 write_stderr("%s: could not change permissions of external PID file \"%s\": %s\n",
1120 progname, external_pid_file, strerror(errno));
1123 write_stderr("%s: could not write external PID file \"%s\": %s\n",
1124 progname, external_pid_file, strerror(errno));
1126 on_proc_exit(unlink_external_pid_file, 0);
1130 * Set up signal handlers for the postmaster process.
1132 * CAUTION: when changing this list, check for side-effects on the signal
1133 * handling setup of child processes. See tcop/postgres.c,
1134 * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/walwriter.c,
1135 * postmaster/autovacuum.c, postmaster/pgarch.c, postmaster/pgstat.c,
1136 * postmaster/syslogger.c, postmaster/bgworker.c and
1137 * postmaster/checkpointer.c.
1140 PG_SETMASK(&BlockSig);
1142 pqsignal(SIGHUP, SIGHUP_handler); /* reread config file and have
1143 * children do same */
1144 pqsignal(SIGINT, pmdie); /* send SIGTERM and shut down */
1145 pqsignal(SIGQUIT, pmdie); /* send SIGQUIT and die */
1146 pqsignal(SIGTERM, pmdie); /* wait for children and shut down */
1147 pqsignal(SIGALRM, SIG_IGN); /* ignored */
1148 pqsignal(SIGPIPE, SIG_IGN); /* ignored */
1149 pqsignal(SIGUSR1, sigusr1_handler); /* message from child process */
1150 pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
1151 pqsignal(SIGCHLD, reaper); /* handle child termination */
1152 pqsignal(SIGTTIN, SIG_IGN); /* ignored */
1153 pqsignal(SIGTTOU, SIG_IGN); /* ignored */
1154 /* ignore SIGXFSZ, so that ulimit violations work like disk full */
1156 pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
1160 * If enabled, start up syslogger collection subprocess
1162 SysLoggerPID = SysLogger_Start();
1165 * Reset whereToSendOutput from DestDebug (its starting state) to
1166 * DestNone. This stops ereport from sending log messages to stderr unless
1167 * Log_destination permits. We don't do this until the postmaster is
1168 * fully launched, since startup failures may as well be reported to
1171 * If we are in fact disabling logging to stderr, first emit a log message
1172 * saying so, to provide a breadcrumb trail for users who may not remember
1173 * that their logging is configured to go somewhere else.
1175 if (!(Log_destination & LOG_DESTINATION_STDERR))
1177 (errmsg("ending log output to stderr"),
1178 errhint("Future log output will go to log destination \"%s\".",
1179 Log_destination_string)));
1181 whereToSendOutput = DestNone;
1184 * Initialize stats collection subsystem (this does NOT start the
1185 * collector process!)
1190 * Initialize the autovacuum subsystem (again, no process start yet)
1195 * Load configuration files for client authentication.
1200 * It makes no sense to continue if we fail to load the HBA file,
1201 * since there is no way to connect to the database in this case.
1204 (errmsg("could not load pg_hba.conf")));
1209 * We can start up without the IDENT file, although it means that you
1210 * cannot log in using any of the authentication methods that need a
1211 * user name mapping. load_ident() already logged the details of error
1218 * Remove old temporary files. At this point there can be no other
1219 * Postgres processes running in this directory, so this should be safe.
1221 RemovePgTempFiles();
1224 * Remember postmaster startup time
1226 PgStartTime = GetCurrentTimestamp();
1227 /* PostmasterRandom wants its own copy */
1228 gettimeofday(&random_start_time, NULL);
1231 * We're ready to rock and roll...
1233 StartupPID = StartupDataBase();
1234 Assert(StartupPID != 0);
1235 pmState = PM_STARTUP;
1237 /* Some workers may be scheduled to start now */
1238 maybe_start_bgworker();
1240 status = ServerLoop();
1243 * ServerLoop probably shouldn't ever return, but if it does, close down.
1245 ExitPostmaster(status != STATUS_OK);
1247 abort(); /* not reached */
1252 * on_proc_exit callback to delete external_pid_file
1255 unlink_external_pid_file(int status, Datum arg)
1257 if (external_pid_file)
1258 unlink(external_pid_file);
1263 * Compute and check the directory paths to files that are part of the
1264 * installation (as deduced from the postgres executable's own location)
1267 getInstallationPaths(const char *argv0)
1271 /* Locate the postgres executable itself */
1272 if (find_my_exec(argv0, my_exec_path) < 0)
1273 elog(FATAL, "%s: could not locate my own executable path", argv0);
1276 /* Locate executable backend before we change working directory */
1277 if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1278 postgres_exec_path) < 0)
1280 (errmsg("%s: could not locate matching postgres executable",
1285 * Locate the pkglib directory --- this has to be set early in case we try
1286 * to load any modules from it in response to postgresql.conf entries.
1288 get_pkglib_path(my_exec_path, pkglib_path);
1291 * Verify that there's a readable directory there; otherwise the Postgres
1292 * installation is incomplete or corrupt. (A typical cause of this
1293 * failure is that the postgres executable has been moved or hardlinked to
1294 * some directory that's not a sibling of the installation lib/
1297 pdir = AllocateDir(pkglib_path);
1300 (errcode_for_file_access(),
1301 errmsg("could not open directory \"%s\": %m",
1303 errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1308 * XXX is it worth similarly checking the share/ directory? If the lib/
1309 * directory is there, then share/ probably is too.
1315 * Validate the proposed data directory
1320 char path[MAXPGPATH];
1322 struct stat stat_buf;
1326 if (stat(DataDir, &stat_buf) != 0)
1328 if (errno == ENOENT)
1330 (errcode_for_file_access(),
1331 errmsg("data directory \"%s\" does not exist",
1335 (errcode_for_file_access(),
1336 errmsg("could not read permissions of directory \"%s\": %m",
1340 /* eventual chdir would fail anyway, but let's test ... */
1341 if (!S_ISDIR(stat_buf.st_mode))
1343 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1344 errmsg("specified data directory \"%s\" is not a directory",
1348 * Check that the directory belongs to my userid; if not, reject.
1350 * This check is an essential part of the interlock that prevents two
1351 * postmasters from starting in the same directory (see CreateLockFile()).
1352 * Do not remove or weaken it.
1354 * XXX can we safely enable this check on Windows?
1356 #if !defined(WIN32) && !defined(__CYGWIN__)
1357 if (stat_buf.st_uid != geteuid())
1359 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1360 errmsg("data directory \"%s\" has wrong ownership",
1362 errhint("The server must be started by the user that owns the data directory.")));
1366 * Check if the directory has group or world access. If so, reject.
1368 * It would be possible to allow weaker constraints (for example, allow
1369 * group access) but we cannot make a general assumption that that is
1370 * okay; for example there are platforms where nearly all users
1371 * customarily belong to the same group. Perhaps this test should be
1374 * XXX temporarily suppress check when on Windows, because there may not
1375 * be proper support for Unix-y file permissions. Need to think of a
1376 * reasonable check to apply on Windows.
1378 #if !defined(WIN32) && !defined(__CYGWIN__)
1379 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
1381 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1382 errmsg("data directory \"%s\" has group or world access",
1384 errdetail("Permissions should be u=rwx (0700).")));
1387 /* Look for PG_VERSION before looking for pg_control */
1388 ValidatePgVersion(DataDir);
1390 snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1392 fp = AllocateFile(path, PG_BINARY_R);
1395 write_stderr("%s: could not find the database system\n"
1396 "Expected to find it in the directory \"%s\",\n"
1397 "but could not open file \"%s\": %s\n",
1398 progname, DataDir, path, strerror(errno));
1405 * Determine how long should we let ServerLoop sleep.
1407 * In normal conditions we wait at most one minute, to ensure that the other
1408 * background tasks handled by ServerLoop get done even when no requests are
1409 * arriving. However, if there are background workers waiting to be started,
1410 * we don't actually sleep so that they are quickly serviced.
1413 DetermineSleepTime(struct timeval * timeout)
1415 TimestampTz next_wakeup = 0;
1418 * Normal case: either there are no background workers at all, or we're in
1419 * a shutdown sequence (during which we ignore bgworkers altogether).
1421 if (Shutdown > NoShutdown ||
1422 (!StartWorkerNeeded && !HaveCrashedWorker))
1424 if (AbortStartTime > 0)
1426 /* time left to abort; clamp to 0 in case it already expired */
1427 timeout->tv_sec = Max(SIGKILL_CHILDREN_AFTER_SECS -
1428 (time(NULL) - AbortStartTime), 0);
1429 timeout->tv_usec = 0;
1433 timeout->tv_sec = 60;
1434 timeout->tv_usec = 0;
1439 if (StartWorkerNeeded)
1441 timeout->tv_sec = 0;
1442 timeout->tv_usec = 0;
1446 if (HaveCrashedWorker)
1448 slist_mutable_iter siter;
1451 * When there are crashed bgworkers, we sleep just long enough that
1452 * they are restarted when they request to be. Scan the list to
1453 * determine the minimum of all wakeup times according to most recent
1454 * crash time and requested restart interval.
1456 slist_foreach_modify(siter, &BackgroundWorkerList)
1458 RegisteredBgWorker *rw;
1459 TimestampTz this_wakeup;
1461 rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
1463 if (rw->rw_crashed_at == 0)
1466 if (rw->rw_worker.bgw_restart_time == BGW_NEVER_RESTART)
1468 ForgetBackgroundWorker(&siter);
1472 this_wakeup = TimestampTzPlusMilliseconds(rw->rw_crashed_at,
1473 1000L * rw->rw_worker.bgw_restart_time);
1474 if (next_wakeup == 0 || this_wakeup < next_wakeup)
1475 next_wakeup = this_wakeup;
1479 if (next_wakeup != 0)
1483 TimestampDifference(GetCurrentTimestamp(), next_wakeup,
1484 &timeout->tv_sec, µsecs);
1485 timeout->tv_usec = microsecs;
1487 /* Ensure we don't exceed one minute */
1488 if (timeout->tv_sec > 60)
1490 timeout->tv_sec = 60;
1491 timeout->tv_usec = 0;
1496 timeout->tv_sec = 60;
1497 timeout->tv_usec = 0;
1502 * Main idle loop of postmaster
1512 last_touch_time = time(NULL);
1514 nSockets = initMasks(&readmask);
1522 * Wait for a connection request to arrive.
1524 * If we are in PM_WAIT_DEAD_END state, then we don't want to accept
1525 * any new connections, so we don't call select() at all; just sleep
1526 * for a little bit with signals unblocked.
1528 memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
1530 PG_SETMASK(&UnBlockSig);
1532 if (pmState == PM_WAIT_DEAD_END)
1534 pg_usleep(100000L); /* 100 msec seems reasonable */
1539 /* must set timeout each time; some OSes change it! */
1540 struct timeval timeout;
1542 DetermineSleepTime(&timeout);
1544 selres = select(nSockets, &rmask, NULL, NULL, &timeout);
1548 * Block all signals until we wait again. (This makes it safe for our
1549 * signal handlers to do nontrivial work.)
1551 PG_SETMASK(&BlockSig);
1553 /* Now check the select() result */
1556 if (errno != EINTR && errno != EWOULDBLOCK)
1559 (errcode_for_socket_access(),
1560 errmsg("select() failed in postmaster: %m")));
1561 return STATUS_ERROR;
1566 * New connection pending on any of our sockets? If so, fork a child
1567 * process to deal with it.
1573 for (i = 0; i < MAXLISTEN; i++)
1575 if (ListenSocket[i] == PGINVALID_SOCKET)
1577 if (FD_ISSET(ListenSocket[i], &rmask))
1581 port = ConnCreate(ListenSocket[i]);
1584 BackendStartup(port);
1587 * We no longer need the open socket or port structure
1590 StreamClose(port->sock);
1597 /* If we have lost the log collector, try to start a new one */
1598 if (SysLoggerPID == 0 && Logging_collector)
1599 SysLoggerPID = SysLogger_Start();
1602 * If no background writer process is running, and we are not in a
1603 * state that prevents it, start one. It doesn't matter if this
1604 * fails, we'll just try again later. Likewise for the checkpointer.
1606 if (pmState == PM_RUN || pmState == PM_RECOVERY ||
1607 pmState == PM_HOT_STANDBY)
1609 if (CheckpointerPID == 0)
1610 CheckpointerPID = StartCheckpointer();
1611 if (BgWriterPID == 0)
1612 BgWriterPID = StartBackgroundWriter();
1616 * Likewise, if we have lost the walwriter process, try to start a new
1617 * one. But this is needed only in normal operation (else we cannot
1618 * be writing any new WAL).
1620 if (WalWriterPID == 0 && pmState == PM_RUN)
1621 WalWriterPID = StartWalWriter();
1624 * If we have lost the autovacuum launcher, try to start a new one. We
1625 * don't want autovacuum to run in binary upgrade mode because
1626 * autovacuum might update relfrozenxid for empty tables before the
1627 * physical files are put in place.
1629 if (!IsBinaryUpgrade && AutoVacPID == 0 &&
1630 (AutoVacuumingActive() || start_autovac_launcher) &&
1633 AutoVacPID = StartAutoVacLauncher();
1634 if (AutoVacPID != 0)
1635 start_autovac_launcher = false; /* signal processed */
1638 /* If we have lost the archiver, try to start a new one */
1639 if (XLogArchivingActive() && PgArchPID == 0 && pmState == PM_RUN)
1640 PgArchPID = pgarch_start();
1642 /* If we have lost the stats collector, try to start a new one */
1643 if (PgStatPID == 0 && pmState == PM_RUN)
1644 PgStatPID = pgstat_start();
1646 /* If we need to signal the autovacuum launcher, do so now */
1647 if (avlauncher_needs_signal)
1649 avlauncher_needs_signal = false;
1650 if (AutoVacPID != 0)
1651 kill(AutoVacPID, SIGUSR2);
1654 /* Get other worker processes running, if needed */
1655 if (StartWorkerNeeded || HaveCrashedWorker)
1656 maybe_start_bgworker();
1659 * Touch Unix socket and lock files every 58 minutes, to ensure that
1660 * they are not removed by overzealous /tmp-cleaning tasks. We assume
1661 * no one runs cleaners with cutoff times of less than an hour ...
1664 if (now - last_touch_time >= 58 * SECS_PER_MINUTE)
1667 TouchSocketLockFiles();
1668 last_touch_time = now;
1672 * If we already sent SIGQUIT to children and they are slow to shut
1673 * down, it's time to send them SIGKILL. This doesn't happen normally,
1674 * but under certain conditions backends can get stuck while shutting
1675 * down. This is a last measure to get them unwedged.
1677 * Note we also do this during recovery from a process crash.
1679 if ((Shutdown >= ImmediateShutdown || (FatalError && !SendStop)) &&
1680 AbortStartTime > 0 &&
1681 now - AbortStartTime >= SIGKILL_CHILDREN_AFTER_SECS)
1683 /* We were gentle with them before. Not anymore */
1684 TerminateChildren(SIGKILL);
1685 /* reset flag so we don't SIGKILL again */
1689 * Additionally, unless we're recovering from a process crash, it's
1690 * now the time for postmaster to abandon ship.
1699 * Initialise the masks for select() for the ports we are listening on.
1700 * Return the number of sockets to listen on.
1703 initMasks(fd_set *rmask)
1710 for (i = 0; i < MAXLISTEN; i++)
1712 int fd = ListenSocket[i];
1714 if (fd == PGINVALID_SOCKET)
1727 * Read a client's startup packet and do something according to it.
1729 * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
1730 * not return at all.
1732 * (Note that ereport(FATAL) stuff is sent to the client, so only use it
1733 * if that's what you want. Return STATUS_ERROR if you don't want to
1734 * send anything to the client, which would typically be appropriate
1735 * if we detect a communications failure.)
1738 ProcessStartupPacket(Port *port, bool SSLdone)
1742 ProtocolVersion proto;
1743 MemoryContext oldcontext;
1745 if (pq_getbytes((char *) &len, 4) == EOF)
1748 * EOF after SSLdone probably means the client didn't like our
1749 * response to NEGOTIATE_SSL_CODE. That's not an error condition, so
1750 * don't clutter the log with a complaint.
1754 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1755 errmsg("incomplete startup packet")));
1756 return STATUS_ERROR;
1762 if (len < (int32) sizeof(ProtocolVersion) ||
1763 len > MAX_STARTUP_PACKET_LENGTH)
1766 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1767 errmsg("invalid length of startup packet")));
1768 return STATUS_ERROR;
1772 * Allocate at least the size of an old-style startup packet, plus one
1773 * extra byte, and make sure all are zeroes. This ensures we will have
1774 * null termination of all strings, in both fixed- and variable-length
1777 if (len <= (int32) sizeof(StartupPacket))
1778 buf = palloc0(sizeof(StartupPacket) + 1);
1780 buf = palloc0(len + 1);
1782 if (pq_getbytes(buf, len) == EOF)
1785 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1786 errmsg("incomplete startup packet")));
1787 return STATUS_ERROR;
1791 * The first field is either a protocol version number or a special
1794 port->proto = proto = ntohl(*((ProtocolVersion *) buf));
1796 if (proto == CANCEL_REQUEST_CODE)
1798 processCancelRequest(port, buf);
1799 /* Not really an error, but we don't want to proceed further */
1800 return STATUS_ERROR;
1803 if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
1808 /* No SSL when disabled or on Unix sockets */
1809 if (!EnableSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
1812 SSLok = 'S'; /* Support for SSL */
1814 SSLok = 'N'; /* No support for SSL */
1818 if (send(port->sock, &SSLok, 1, 0) != 1)
1821 goto retry1; /* if interrupted, just retry */
1823 (errcode_for_socket_access(),
1824 errmsg("failed to send SSL negotiation response: %m")));
1825 return STATUS_ERROR; /* close the connection */
1829 if (SSLok == 'S' && secure_open_server(port) == -1)
1830 return STATUS_ERROR;
1832 /* regular startup packet, cancel, etc packet should follow... */
1833 /* but not another SSL negotiation request */
1834 return ProcessStartupPacket(port, true);
1837 /* Could add additional special packet types here */
1840 * Set FrontendProtocol now so that ereport() knows what format to send if
1841 * we fail during startup.
1843 FrontendProtocol = proto;
1845 /* Check we can handle the protocol the frontend is using. */
1847 if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
1848 PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
1849 (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
1850 PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
1852 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1853 errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
1854 PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
1855 PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST),
1856 PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST),
1857 PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))));
1860 * Now fetch parameters out of startup packet and save them into the Port
1861 * structure. All data structures attached to the Port struct must be
1862 * allocated in TopMemoryContext so that they will remain available in a
1863 * running backend (even after PostmasterContext is destroyed). We need
1864 * not worry about leaking this storage on failure, since we aren't in the
1865 * postmaster process anymore.
1867 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1869 if (PG_PROTOCOL_MAJOR(proto) >= 3)
1871 int32 offset = sizeof(ProtocolVersion);
1874 * Scan packet body for name/option pairs. We can assume any string
1875 * beginning within the packet body is null-terminated, thanks to
1876 * zeroing extra byte above.
1878 port->guc_options = NIL;
1880 while (offset < len)
1882 char *nameptr = ((char *) buf) + offset;
1886 if (*nameptr == '\0')
1887 break; /* found packet terminator */
1888 valoffset = offset + strlen(nameptr) + 1;
1889 if (valoffset >= len)
1890 break; /* missing value, will complain below */
1891 valptr = ((char *) buf) + valoffset;
1893 if (strcmp(nameptr, "database") == 0)
1894 port->database_name = pstrdup(valptr);
1895 else if (strcmp(nameptr, "user") == 0)
1896 port->user_name = pstrdup(valptr);
1897 else if (strcmp(nameptr, "options") == 0)
1898 port->cmdline_options = pstrdup(valptr);
1899 else if (strcmp(nameptr, "replication") == 0)
1901 if (!parse_bool(valptr, &am_walsender))
1903 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1904 errmsg("invalid value for boolean option \"replication\"")));
1908 /* Assume it's a generic GUC option */
1909 port->guc_options = lappend(port->guc_options,
1911 port->guc_options = lappend(port->guc_options,
1914 offset = valoffset + strlen(valptr) + 1;
1918 * If we didn't find a packet terminator exactly at the end of the
1919 * given packet length, complain.
1921 if (offset != len - 1)
1923 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1924 errmsg("invalid startup packet layout: expected terminator as last byte")));
1929 * Get the parameters from the old-style, fixed-width-fields startup
1930 * packet as C strings. The packet destination was cleared first so a
1931 * short packet has zeros silently added. We have to be prepared to
1932 * truncate the pstrdup result for oversize fields, though.
1934 StartupPacket *packet = (StartupPacket *) buf;
1936 port->database_name = pstrdup(packet->database);
1937 if (strlen(port->database_name) > sizeof(packet->database))
1938 port->database_name[sizeof(packet->database)] = '\0';
1939 port->user_name = pstrdup(packet->user);
1940 if (strlen(port->user_name) > sizeof(packet->user))
1941 port->user_name[sizeof(packet->user)] = '\0';
1942 port->cmdline_options = pstrdup(packet->options);
1943 if (strlen(port->cmdline_options) > sizeof(packet->options))
1944 port->cmdline_options[sizeof(packet->options)] = '\0';
1945 port->guc_options = NIL;
1948 /* Check a user name was given. */
1949 if (port->user_name == NULL || port->user_name[0] == '\0')
1951 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1952 errmsg("no PostgreSQL user name specified in startup packet")));
1954 /* The database defaults to the user name. */
1955 if (port->database_name == NULL || port->database_name[0] == '\0')
1956 port->database_name = pstrdup(port->user_name);
1958 if (Db_user_namespace)
1961 * If user@, it is a global user, remove '@'. We only want to do this
1962 * if there is an '@' at the end and no earlier in the user string or
1963 * they may fake as a local user of another database attaching to this
1966 if (strchr(port->user_name, '@') ==
1967 port->user_name + strlen(port->user_name) - 1)
1968 *strchr(port->user_name, '@') = '\0';
1971 /* Append '@' and dbname */
1972 port->user_name = psprintf("%s@%s", port->user_name, port->database_name);
1977 * Truncate given database and user names to length of a Postgres name.
1978 * This avoids lookup failures when overlength names are given.
1980 if (strlen(port->database_name) >= NAMEDATALEN)
1981 port->database_name[NAMEDATALEN - 1] = '\0';
1982 if (strlen(port->user_name) >= NAMEDATALEN)
1983 port->user_name[NAMEDATALEN - 1] = '\0';
1985 /* Walsender is not related to a particular database */
1987 port->database_name[0] = '\0';
1990 * Done putting stuff in TopMemoryContext.
1992 MemoryContextSwitchTo(oldcontext);
1995 * If we're going to reject the connection due to database state, say so
1996 * now instead of wasting cycles on an authentication exchange. (This also
1997 * allows a pg_ping utility to be written.)
1999 switch (port->canAcceptConnections)
2003 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
2004 errmsg("the database system is starting up")));
2008 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
2009 errmsg("the database system is shutting down")));
2013 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
2014 errmsg("the database system is in recovery mode")));
2018 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
2019 errmsg("sorry, too many clients already")));
2021 case CAC_WAITBACKUP:
2022 /* OK for now, will check in InitPostgres */
2033 * The client has sent a cancel request packet, not a normal
2034 * start-a-new-connection packet. Perform the necessary processing.
2035 * Nothing is sent back to the client.
2038 processCancelRequest(Port *port, void *pkt)
2040 CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
2042 long cancelAuthCode;
2045 #ifndef EXEC_BACKEND
2051 backendPID = (int) ntohl(canc->backendPID);
2052 cancelAuthCode = (long) ntohl(canc->cancelAuthCode);
2055 * See if we have a matching backend. In the EXEC_BACKEND case, we can no
2056 * longer access the postmaster's own backend list, and must rely on the
2057 * duplicate array in shared memory.
2059 #ifndef EXEC_BACKEND
2060 dlist_foreach(iter, &BackendList)
2062 bp = dlist_container(Backend, elem, iter.cur);
2064 for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
2066 bp = (Backend *) &ShmemBackendArray[i];
2068 if (bp->pid == backendPID)
2070 if (bp->cancel_key == cancelAuthCode)
2072 /* Found a match; signal that backend to cancel current op */
2074 (errmsg_internal("processing cancel request: sending SIGINT to process %d",
2076 signal_child(bp->pid, SIGINT);
2079 /* Right PID, wrong key: no way, Jose */
2081 (errmsg("wrong key in cancel request for process %d",
2087 /* No matching backend */
2089 (errmsg("PID %d in cancel request did not match any process",
2094 * canAcceptConnections --- check to see if database state allows connections.
2097 canAcceptConnections(void)
2099 CAC_state result = CAC_OK;
2102 * Can't start backends when in startup/shutdown/inconsistent recovery
2105 * In state PM_WAIT_BACKUP only superusers can connect (this must be
2106 * allowed so that a superuser can end online backup mode); we return
2107 * CAC_WAITBACKUP code to indicate that this must be checked later. Note
2108 * that neither CAC_OK nor CAC_WAITBACKUP can safely be returned until we
2109 * have checked for too many children.
2111 if (pmState != PM_RUN)
2113 if (pmState == PM_WAIT_BACKUP)
2114 result = CAC_WAITBACKUP; /* allow superusers only */
2115 else if (Shutdown > NoShutdown)
2116 return CAC_SHUTDOWN; /* shutdown is pending */
2117 else if (!FatalError &&
2118 (pmState == PM_STARTUP ||
2119 pmState == PM_RECOVERY))
2120 return CAC_STARTUP; /* normal startup */
2121 else if (!FatalError &&
2122 pmState == PM_HOT_STANDBY)
2123 result = CAC_OK; /* connection OK during hot standby */
2125 return CAC_RECOVERY; /* else must be crash recovery */
2129 * Don't start too many children.
2131 * We allow more connections than we can have backends here because some
2132 * might still be authenticating; they might fail auth, or some existing
2133 * backend might exit before the auth cycle is completed. The exact
2134 * MaxBackends limit is enforced when a new backend tries to join the
2135 * shared-inval backend array.
2137 * The limit here must match the sizes of the per-child-process arrays;
2138 * see comments for MaxLivePostmasterChildren().
2140 if (CountChildren(BACKEND_TYPE_ALL) >= MaxLivePostmasterChildren())
2141 result = CAC_TOOMANY;
2148 * ConnCreate -- create a local connection data structure
2150 * Returns NULL on failure, other than out-of-memory which is fatal.
2153 ConnCreate(int serverFd)
2157 if (!(port = (Port *) calloc(1, sizeof(Port))))
2160 (errcode(ERRCODE_OUT_OF_MEMORY),
2161 errmsg("out of memory")));
2165 if (StreamConnection(serverFd, port) != STATUS_OK)
2167 if (port->sock >= 0)
2168 StreamClose(port->sock);
2174 * Precompute password salt values to use for this connection. It's
2175 * slightly annoying to do this long in advance of knowing whether we'll
2176 * need 'em or not, but we must do the random() calls before we fork, not
2177 * after. Else the postmaster's random sequence won't get advanced, and
2178 * all backends would end up using the same salt...
2180 RandomSalt(port->md5Salt);
2183 * Allocate GSSAPI specific state struct
2185 #ifndef EXEC_BACKEND
2186 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2187 port->gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
2191 (errcode(ERRCODE_OUT_OF_MEMORY),
2192 errmsg("out of memory")));
2203 * ConnFree -- free a local connection data structure
2206 ConnFree(Port *conn)
2218 * ClosePostmasterPorts -- close all the postmaster's open sockets
2220 * This is called during child process startup to release file descriptors
2221 * that are not needed by that child process. The postmaster still has
2222 * them open, of course.
2224 * Note: we pass am_syslogger as a boolean because we don't want to set
2225 * the global variable yet when this is called.
2228 ClosePostmasterPorts(bool am_syslogger)
2235 * Close the write end of postmaster death watch pipe. It's important to
2236 * do this as early as possible, so that if postmaster dies, others won't
2237 * think that it's still running because we're holding the pipe open.
2239 if (close(postmaster_alive_fds[POSTMASTER_FD_OWN]))
2241 (errcode_for_file_access(),
2242 errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
2243 postmaster_alive_fds[POSTMASTER_FD_OWN] = -1;
2246 /* Close the listen sockets */
2247 for (i = 0; i < MAXLISTEN; i++)
2249 if (ListenSocket[i] != PGINVALID_SOCKET)
2251 StreamClose(ListenSocket[i]);
2252 ListenSocket[i] = PGINVALID_SOCKET;
2256 /* If using syslogger, close the read side of the pipe */
2260 if (syslogPipe[0] >= 0)
2261 close(syslogPipe[0]);
2265 CloseHandle(syslogPipe[0]);
2271 /* If using Bonjour, close the connection to the mDNS daemon */
2273 close(DNSServiceRefSockFD(bonjour_sdref));
2279 * reset_shared -- reset shared memory and semaphores
2282 reset_shared(int port)
2285 * Create or re-create shared memory and semaphores.
2287 * Note: in each "cycle of life" we will normally assign the same IPC keys
2288 * (if using SysV shmem and/or semas), since the port number is used to
2289 * determine IPC keys. This helps ensure that we will clean up dead IPC
2290 * objects if the postmaster crashes and is restarted.
2292 CreateSharedMemoryAndSemaphores(false, port);
2297 * SIGHUP -- reread config files, and tell children to do same
2300 SIGHUP_handler(SIGNAL_ARGS)
2302 int save_errno = errno;
2304 PG_SETMASK(&BlockSig);
2306 if (Shutdown <= SmartShutdown)
2309 (errmsg("received SIGHUP, reloading configuration files")));
2310 ProcessConfigFile(PGC_SIGHUP);
2311 SignalChildren(SIGHUP);
2312 SignalUnconnectedWorkers(SIGHUP);
2313 if (StartupPID != 0)
2314 signal_child(StartupPID, SIGHUP);
2315 if (BgWriterPID != 0)
2316 signal_child(BgWriterPID, SIGHUP);
2317 if (CheckpointerPID != 0)
2318 signal_child(CheckpointerPID, SIGHUP);
2319 if (WalWriterPID != 0)
2320 signal_child(WalWriterPID, SIGHUP);
2321 if (WalReceiverPID != 0)
2322 signal_child(WalReceiverPID, SIGHUP);
2323 if (AutoVacPID != 0)
2324 signal_child(AutoVacPID, SIGHUP);
2326 signal_child(PgArchPID, SIGHUP);
2327 if (SysLoggerPID != 0)
2328 signal_child(SysLoggerPID, SIGHUP);
2330 signal_child(PgStatPID, SIGHUP);
2332 /* Reload authentication config files too */
2335 (errmsg("pg_hba.conf not reloaded")));
2339 (errmsg("pg_ident.conf not reloaded")));
2342 /* Update the starting-point file for future children */
2343 write_nondefault_variables(PGC_SIGHUP);
2347 PG_SETMASK(&UnBlockSig);
2354 * pmdie -- signal handler for processing various postmaster signals.
2359 int save_errno = errno;
2361 PG_SETMASK(&BlockSig);
2364 (errmsg_internal("postmaster received signal %d",
2365 postgres_signal_arg)));
2367 switch (postgres_signal_arg)
2374 * Wait for children to end their work, then shut down.
2376 if (Shutdown >= SmartShutdown)
2378 Shutdown = SmartShutdown;
2380 (errmsg("received smart shutdown request")));
2382 if (pmState == PM_RUN || pmState == PM_RECOVERY ||
2383 pmState == PM_HOT_STANDBY || pmState == PM_STARTUP)
2385 /* autovac workers are told to shut down immediately */
2386 /* and bgworkers too; does this need tweaking? */
2387 SignalSomeChildren(SIGTERM,
2388 BACKEND_TYPE_AUTOVAC | BACKEND_TYPE_BGWORKER);
2389 SignalUnconnectedWorkers(SIGTERM);
2390 /* and the autovac launcher too */
2391 if (AutoVacPID != 0)
2392 signal_child(AutoVacPID, SIGTERM);
2393 /* and the bgwriter too */
2394 if (BgWriterPID != 0)
2395 signal_child(BgWriterPID, SIGTERM);
2396 /* and the walwriter too */
2397 if (WalWriterPID != 0)
2398 signal_child(WalWriterPID, SIGTERM);
2401 * If we're in recovery, we can't kill the startup process
2402 * right away, because at present doing so does not release
2403 * its locks. We might want to change this in a future
2404 * release. For the time being, the PM_WAIT_READONLY state
2405 * indicates that we're waiting for the regular (read only)
2406 * backends to die off; once they do, we'll kill the startup
2407 * and walreceiver processes.
2409 pmState = (pmState == PM_RUN) ?
2410 PM_WAIT_BACKUP : PM_WAIT_READONLY;
2414 * Now wait for online backup mode to end and backends to exit. If
2415 * that is already the case, PostmasterStateMachine will take the
2418 PostmasterStateMachine();
2426 * Abort all children with SIGTERM (rollback active transactions
2427 * and exit) and shut down when they are gone.
2429 if (Shutdown >= FastShutdown)
2431 Shutdown = FastShutdown;
2433 (errmsg("received fast shutdown request")));
2435 if (StartupPID != 0)
2436 signal_child(StartupPID, SIGTERM);
2437 if (BgWriterPID != 0)
2438 signal_child(BgWriterPID, SIGTERM);
2439 if (WalReceiverPID != 0)
2440 signal_child(WalReceiverPID, SIGTERM);
2441 SignalUnconnectedWorkers(SIGTERM);
2442 if (pmState == PM_RECOVERY)
2445 * Only startup, bgwriter, walreceiver, unconnected bgworkers,
2446 * and/or checkpointer should be active in this state; we just
2447 * signaled the first four, and we don't want to kill
2450 pmState = PM_WAIT_BACKENDS;
2452 else if (pmState == PM_RUN ||
2453 pmState == PM_WAIT_BACKUP ||
2454 pmState == PM_WAIT_READONLY ||
2455 pmState == PM_WAIT_BACKENDS ||
2456 pmState == PM_HOT_STANDBY)
2459 (errmsg("aborting any active transactions")));
2460 /* shut down all backends and workers */
2461 SignalSomeChildren(SIGTERM,
2462 BACKEND_TYPE_NORMAL | BACKEND_TYPE_AUTOVAC |
2463 BACKEND_TYPE_BGWORKER);
2464 /* and the autovac launcher too */
2465 if (AutoVacPID != 0)
2466 signal_child(AutoVacPID, SIGTERM);
2467 /* and the walwriter too */
2468 if (WalWriterPID != 0)
2469 signal_child(WalWriterPID, SIGTERM);
2470 pmState = PM_WAIT_BACKENDS;
2474 * Now wait for backends to exit. If there are none,
2475 * PostmasterStateMachine will take the next step.
2477 PostmasterStateMachine();
2483 * Immediate Shutdown:
2485 * abort all children with SIGQUIT, wait for them to exit,
2486 * terminate remaining ones with SIGKILL, then exit without
2487 * attempt to properly shut down the data base system.
2489 if (Shutdown >= ImmediateShutdown)
2491 Shutdown = ImmediateShutdown;
2493 (errmsg("received immediate shutdown request")));
2495 TerminateChildren(SIGQUIT);
2496 pmState = PM_WAIT_BACKENDS;
2498 /* set stopwatch for them to die */
2499 AbortStartTime = time(NULL);
2502 * Now wait for backends to exit. If there are none,
2503 * PostmasterStateMachine will take the next step.
2505 PostmasterStateMachine();
2509 PG_SETMASK(&UnBlockSig);
2515 * Reaper -- signal handler to cleanup after a child process dies.
2520 int save_errno = errno;
2521 int pid; /* process id of dead child process */
2522 int exitstatus; /* its exit status */
2524 PG_SETMASK(&BlockSig);
2527 (errmsg_internal("reaping dead processes")));
2529 while ((pid = waitpid(-1, &exitstatus, WNOHANG)) > 0)
2532 * Check if this child was a startup process.
2534 if (pid == StartupPID)
2539 * Startup process exited in response to a shutdown request (or it
2540 * completed normally regardless of the shutdown request).
2542 if (Shutdown > NoShutdown &&
2543 (EXIT_STATUS_0(exitstatus) || EXIT_STATUS_1(exitstatus)))
2545 pmState = PM_WAIT_BACKENDS;
2546 /* PostmasterStateMachine logic does the rest */
2551 * Unexpected exit of startup process (including FATAL exit)
2552 * during PM_STARTUP is treated as catastrophic. There are no
2553 * other processes running yet, so we can just exit.
2555 if (pmState == PM_STARTUP && !EXIT_STATUS_0(exitstatus))
2557 LogChildExit(LOG, _("startup process"),
2560 (errmsg("aborting startup due to startup process failure")));
2565 * After PM_STARTUP, any unexpected exit (including FATAL exit) of
2566 * the startup process is catastrophic, so kill other children,
2567 * and set RecoveryError so we don't try to reinitialize after
2568 * they're gone. Exception: if FatalError is already set, that
2569 * implies we previously sent the startup process a SIGQUIT, so
2570 * that's probably the reason it died, and we do want to try to
2571 * restart in that case.
2573 if (!EXIT_STATUS_0(exitstatus))
2576 RecoveryError = true;
2577 HandleChildCrash(pid, exitstatus,
2578 _("startup process"));
2583 * Startup succeeded, commence normal operations
2586 Assert(AbortStartTime == 0);
2587 ReachedNormalRunning = true;
2591 * Crank up the background tasks, if we didn't do that already
2592 * when we entered consistent recovery state. It doesn't matter
2593 * if this fails, we'll just try again later.
2595 if (CheckpointerPID == 0)
2596 CheckpointerPID = StartCheckpointer();
2597 if (BgWriterPID == 0)
2598 BgWriterPID = StartBackgroundWriter();
2599 if (WalWriterPID == 0)
2600 WalWriterPID = StartWalWriter();
2603 * Likewise, start other special children as needed. In a restart
2604 * situation, some of them may be alive already.
2606 if (!IsBinaryUpgrade && AutoVacuumingActive() && AutoVacPID == 0)
2607 AutoVacPID = StartAutoVacLauncher();
2608 if (XLogArchivingActive() && PgArchPID == 0)
2609 PgArchPID = pgarch_start();
2611 PgStatPID = pgstat_start();
2613 /* some workers may be scheduled to start now */
2614 maybe_start_bgworker();
2616 /* at this point we are really open for business */
2618 (errmsg("database system is ready to accept connections")));
2624 * Was it the bgwriter? Normal exit can be ignored; we'll start a new
2625 * one at the next iteration of the postmaster's main loop, if
2626 * necessary. Any other exit condition is treated as a crash.
2628 if (pid == BgWriterPID)
2631 if (!EXIT_STATUS_0(exitstatus))
2632 HandleChildCrash(pid, exitstatus,
2633 _("background writer process"));
2638 * Was it the checkpointer?
2640 if (pid == CheckpointerPID)
2642 CheckpointerPID = 0;
2643 if (EXIT_STATUS_0(exitstatus) && pmState == PM_SHUTDOWN)
2646 * OK, we saw normal exit of the checkpointer after it's been
2647 * told to shut down. We expect that it wrote a shutdown
2648 * checkpoint. (If for some reason it didn't, recovery will
2649 * occur on next postmaster start.)
2651 * At this point we should have no normal backend children
2652 * left (else we'd not be in PM_SHUTDOWN state) but we might
2653 * have dead_end children to wait for.
2655 * If we have an archiver subprocess, tell it to do a last
2656 * archive cycle and quit. Likewise, if we have walsender
2657 * processes, tell them to send any remaining WAL and quit.
2659 Assert(Shutdown > NoShutdown);
2661 /* Waken archiver for the last time */
2663 signal_child(PgArchPID, SIGUSR2);
2666 * Waken walsenders for the last time. No regular backends
2667 * should be around anymore.
2669 SignalChildren(SIGUSR2);
2671 pmState = PM_SHUTDOWN_2;
2674 * We can also shut down the stats collector now; there's
2675 * nothing left for it to do.
2678 signal_child(PgStatPID, SIGQUIT);
2683 * Any unexpected exit of the checkpointer (including FATAL
2684 * exit) is treated as a crash.
2686 HandleChildCrash(pid, exitstatus,
2687 _("checkpointer process"));
2694 * Was it the wal writer? Normal exit can be ignored; we'll start a
2695 * new one at the next iteration of the postmaster's main loop, if
2696 * necessary. Any other exit condition is treated as a crash.
2698 if (pid == WalWriterPID)
2701 if (!EXIT_STATUS_0(exitstatus))
2702 HandleChildCrash(pid, exitstatus,
2703 _("WAL writer process"));
2708 * Was it the wal receiver? If exit status is zero (normal) or one
2709 * (FATAL exit), we assume everything is all right just like normal
2712 if (pid == WalReceiverPID)
2715 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2716 HandleChildCrash(pid, exitstatus,
2717 _("WAL receiver process"));
2722 * Was it the autovacuum launcher? Normal exit can be ignored; we'll
2723 * start a new one at the next iteration of the postmaster's main
2724 * loop, if necessary. Any other exit condition is treated as a
2727 if (pid == AutoVacPID)
2730 if (!EXIT_STATUS_0(exitstatus))
2731 HandleChildCrash(pid, exitstatus,
2732 _("autovacuum launcher process"));
2737 * Was it the archiver? If so, just try to start a new one; no need
2738 * to force reset of the rest of the system. (If fail, we'll try
2739 * again in future cycles of the main loop.). Unless we were waiting
2740 * for it to shut down; don't restart it in that case, and
2741 * PostmasterStateMachine() will advance to the next shutdown step.
2743 if (pid == PgArchPID)
2746 if (!EXIT_STATUS_0(exitstatus))
2747 LogChildExit(LOG, _("archiver process"),
2749 if (XLogArchivingActive() && pmState == PM_RUN)
2750 PgArchPID = pgarch_start();
2755 * Was it the statistics collector? If so, just try to start a new
2756 * one; no need to force reset of the rest of the system. (If fail,
2757 * we'll try again in future cycles of the main loop.)
2759 if (pid == PgStatPID)
2762 if (!EXIT_STATUS_0(exitstatus))
2763 LogChildExit(LOG, _("statistics collector process"),
2765 if (pmState == PM_RUN)
2766 PgStatPID = pgstat_start();
2770 /* Was it the system logger? If so, try to start a new one */
2771 if (pid == SysLoggerPID)
2774 /* for safety's sake, launch new logger *first* */
2775 SysLoggerPID = SysLogger_Start();
2776 if (!EXIT_STATUS_0(exitstatus))
2777 LogChildExit(LOG, _("system logger process"),
2782 /* Was it one of our background workers? */
2783 if (CleanupBackgroundWorker(pid, exitstatus))
2785 /* have it be restarted */
2786 HaveCrashedWorker = true;
2791 * Else do standard backend child cleanup.
2793 CleanupBackend(pid, exitstatus);
2794 } /* loop over pending child-death reports */
2797 * After cleaning out the SIGCHLD queue, see if we have any state changes
2798 * or actions to make.
2800 PostmasterStateMachine();
2802 /* Done with signal handler */
2803 PG_SETMASK(&UnBlockSig);
2809 * Scan the bgworkers list and see if the given PID (which has just stopped
2810 * or crashed) is in it. Handle its shutdown if so, and return true. If not a
2811 * bgworker, return false.
2813 * This is heavily based on CleanupBackend. One important difference is that
2814 * we don't know yet that the dying process is a bgworker, so we must be silent
2815 * until we're sure it is.
2818 CleanupBackgroundWorker(int pid,
2819 int exitstatus) /* child's exit status */
2821 char namebuf[MAXPGPATH];
2824 slist_foreach(iter, &BackgroundWorkerList)
2826 RegisteredBgWorker *rw;
2828 rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
2830 if (rw->rw_pid != pid)
2834 /* see CleanupBackend */
2835 if (exitstatus == ERROR_WAIT_NO_CHILDREN)
2839 snprintf(namebuf, MAXPGPATH, "%s: %s", _("worker process"),
2840 rw->rw_worker.bgw_name);
2842 /* Delay restarting any bgworker that exits with a nonzero status. */
2843 if (!EXIT_STATUS_0(exitstatus))
2844 rw->rw_crashed_at = GetCurrentTimestamp();
2846 rw->rw_crashed_at = 0;
2849 * Additionally, for shared-memory-connected workers, just like a
2850 * backend, any exit status other than 0 or 1 is considered a crash
2851 * and causes a system-wide restart.
2853 if (rw->rw_worker.bgw_flags & BGWORKER_SHMEM_ACCESS)
2855 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2857 rw->rw_crashed_at = GetCurrentTimestamp();
2858 HandleChildCrash(pid, exitstatus, namebuf);
2863 if (!ReleasePostmasterChildSlot(rw->rw_child_slot))
2866 * Uh-oh, the child failed to clean itself up. Treat as a crash
2869 rw->rw_crashed_at = GetCurrentTimestamp();
2870 HandleChildCrash(pid, exitstatus, namebuf);
2874 /* Get it out of the BackendList and clear out remaining data */
2877 Assert(rw->rw_worker.bgw_flags & BGWORKER_BACKEND_DATABASE_CONNECTION);
2878 dlist_delete(&rw->rw_backend->elem);
2880 ShmemBackendArrayRemove(rw->rw_backend);
2883 * It's possible that this background worker started some OTHER
2884 * background worker and asked to be notified when that worker
2885 * started or stopped. If so, cancel any notifications destined
2886 * for the now-dead backend.
2888 if (rw->rw_backend->bgworker_notify)
2889 BackgroundWorkerStopNotifications(rw->rw_pid);
2890 free(rw->rw_backend);
2891 rw->rw_backend = NULL;
2894 rw->rw_child_slot = 0;
2895 ReportBackgroundWorkerPID(rw); /* report child death */
2897 LogChildExit(LOG, namebuf, pid, exitstatus);
2906 * CleanupBackend -- cleanup after terminated backend.
2908 * Remove all local state associated with backend.
2910 * If you change this, see also CleanupBackgroundWorker.
2913 CleanupBackend(int pid,
2914 int exitstatus) /* child's exit status. */
2916 dlist_mutable_iter iter;
2918 LogChildExit(DEBUG2, _("server process"), pid, exitstatus);
2921 * If a backend dies in an ugly way then we must signal all other backends
2922 * to quickdie. If exit status is zero (normal) or one (FATAL exit), we
2923 * assume everything is all right and proceed to remove the backend from
2924 * the active backend list.
2929 * On win32, also treat ERROR_WAIT_NO_CHILDREN (128) as nonfatal case,
2930 * since that sometimes happens under load when the process fails to start
2931 * properly (long before it starts using shared memory). Microsoft reports
2932 * it is related to mutex failure:
2933 * http://archives.postgresql.org/pgsql-hackers/2010-09/msg00790.php
2935 if (exitstatus == ERROR_WAIT_NO_CHILDREN)
2937 LogChildExit(LOG, _("server process"), pid, exitstatus);
2942 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2944 HandleChildCrash(pid, exitstatus, _("server process"));
2948 dlist_foreach_modify(iter, &BackendList)
2950 Backend *bp = dlist_container(Backend, elem, iter.cur);
2956 if (!ReleasePostmasterChildSlot(bp->child_slot))
2959 * Uh-oh, the child failed to clean itself up. Treat as a
2962 HandleChildCrash(pid, exitstatus, _("server process"));
2966 ShmemBackendArrayRemove(bp);
2969 if (bp->bgworker_notify)
2972 * This backend may have been slated to receive SIGUSR1
2973 * when some background worker started or stopped. Cancel
2974 * those notifications, as we don't want to signal PIDs that
2975 * are not PostgreSQL backends. This gets skipped in the
2976 * (probably very common) case where the backend has never
2977 * requested any such notifications.
2979 BackgroundWorkerStopNotifications(bp->pid);
2981 dlist_delete(iter.cur);
2989 * HandleChildCrash -- cleanup after failed backend, bgwriter, checkpointer,
2990 * walwriter, autovacuum, or background worker.
2992 * The objectives here are to clean up our local state about the child
2993 * process, and to signal all other remaining children to quickdie.
2996 HandleChildCrash(int pid, int exitstatus, const char *procname)
2998 dlist_mutable_iter iter;
3004 * We only log messages and send signals if this is the first process crash
3005 * and we're not doing an immediate shutdown; otherwise, we're only here to
3006 * update postmaster's idea of live processes. If we have already signalled
3007 * children, nonzero exit status is to be expected, so don't clutter log.
3009 take_action = !FatalError && Shutdown != ImmediateShutdown;
3013 LogChildExit(LOG, procname, pid, exitstatus);
3015 (errmsg("terminating any other active server processes")));
3018 /* Process background workers. */
3019 slist_foreach(siter, &BackgroundWorkerList)
3021 RegisteredBgWorker *rw;
3023 rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
3024 if (rw->rw_pid == 0)
3025 continue; /* not running */
3026 if (rw->rw_pid == pid)
3029 * Found entry for freshly-dead worker, so remove it.
3031 (void) ReleasePostmasterChildSlot(rw->rw_child_slot);
3034 dlist_delete(&rw->rw_backend->elem);
3036 ShmemBackendArrayRemove(rw->rw_backend);
3038 free(rw->rw_backend);
3039 rw->rw_backend = NULL;
3042 rw->rw_child_slot = 0;
3043 /* don't reset crashed_at */
3044 /* don't report child stop, either */
3045 /* Keep looping so we can signal remaining workers */
3050 * This worker is still alive. Unless we did so already, tell it
3051 * to commit hara-kiri.
3053 * SIGQUIT is the special signal that says exit without proc_exit
3054 * and let the user know what's going on. But if SendStop is set
3055 * (-s on command line), then we send SIGSTOP instead, so that we
3056 * can get core dumps from all backends by hand.
3061 (errmsg_internal("sending %s to process %d",
3062 (SendStop ? "SIGSTOP" : "SIGQUIT"),
3063 (int) rw->rw_pid)));
3064 signal_child(rw->rw_pid, (SendStop ? SIGSTOP : SIGQUIT));
3069 /* Process regular backends */
3070 dlist_foreach_modify(iter, &BackendList)
3072 bp = dlist_container(Backend, elem, iter.cur);
3077 * Found entry for freshly-dead backend, so remove it.
3081 (void) ReleasePostmasterChildSlot(bp->child_slot);
3083 ShmemBackendArrayRemove(bp);
3086 dlist_delete(iter.cur);
3088 /* Keep looping so we can signal remaining backends */
3093 * This backend is still alive. Unless we did so already, tell it
3094 * to commit hara-kiri.
3096 * SIGQUIT is the special signal that says exit without proc_exit
3097 * and let the user know what's going on. But if SendStop is set
3098 * (-s on command line), then we send SIGSTOP instead, so that we
3099 * can get core dumps from all backends by hand.
3101 * We could exclude dead_end children here, but at least in the
3102 * SIGSTOP case it seems better to include them.
3104 * Background workers were already processed above; ignore them
3107 if (bp->bkend_type == BACKEND_TYPE_BGWORKER)
3113 (errmsg_internal("sending %s to process %d",
3114 (SendStop ? "SIGSTOP" : "SIGQUIT"),
3116 signal_child(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
3121 /* Take care of the startup process too */
3122 if (pid == StartupPID)
3124 else if (StartupPID != 0 && take_action)
3127 (errmsg_internal("sending %s to process %d",
3128 (SendStop ? "SIGSTOP" : "SIGQUIT"),
3129 (int) StartupPID)));
3130 signal_child(StartupPID, (SendStop ? SIGSTOP : SIGQUIT));
3133 /* Take care of the bgwriter too */
3134 if (pid == BgWriterPID)
3136 else if (BgWriterPID != 0 && take_action)
3139 (errmsg_internal("sending %s to process %d",
3140 (SendStop ? "SIGSTOP" : "SIGQUIT"),
3141 (int) BgWriterPID)));
3142 signal_child(BgWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
3145 /* Take care of the checkpointer too */
3146 if (pid == CheckpointerPID)
3147 CheckpointerPID = 0;
3148 else if (CheckpointerPID != 0 && take_action)
3151 (errmsg_internal("sending %s to process %d",
3152 (SendStop ? "SIGSTOP" : "SIGQUIT"),
3153 (int) CheckpointerPID)));
3154 signal_child(CheckpointerPID, (SendStop ? SIGSTOP : SIGQUIT));
3157 /* Take care of the walwriter too */
3158 if (pid == WalWriterPID)
3160 else if (WalWriterPID != 0 && take_action)
3163 (errmsg_internal("sending %s to process %d",
3164 (SendStop ? "SIGSTOP" : "SIGQUIT"),
3165 (int) WalWriterPID)));
3166 signal_child(WalWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
3169 /* Take care of the walreceiver too */
3170 if (pid == WalReceiverPID)
3172 else if (WalReceiverPID != 0 && take_action)
3175 (errmsg_internal("sending %s to process %d",
3176 (SendStop ? "SIGSTOP" : "SIGQUIT"),
3177 (int) WalReceiverPID)));
3178 signal_child(WalReceiverPID, (SendStop ? SIGSTOP : SIGQUIT));
3181 /* Take care of the autovacuum launcher too */
3182 if (pid == AutoVacPID)
3184 else if (AutoVacPID != 0 && take_action)
3187 (errmsg_internal("sending %s to process %d",
3188 (SendStop ? "SIGSTOP" : "SIGQUIT"),
3189 (int) AutoVacPID)));
3190 signal_child(AutoVacPID, (SendStop ? SIGSTOP : SIGQUIT));
3194 * Force a power-cycle of the pgarch process too. (This isn't absolutely
3195 * necessary, but it seems like a good idea for robustness, and it
3196 * simplifies the state-machine logic in the case where a shutdown request
3197 * arrives during crash processing.)
3199 if (PgArchPID != 0 && take_action)
3202 (errmsg_internal("sending %s to process %d",
3205 signal_child(PgArchPID, SIGQUIT);
3209 * Force a power-cycle of the pgstat process too. (This isn't absolutely
3210 * necessary, but it seems like a good idea for robustness, and it
3211 * simplifies the state-machine logic in the case where a shutdown request
3212 * arrives during crash processing.)
3214 if (PgStatPID != 0 && take_action)
3217 (errmsg_internal("sending %s to process %d",
3220 signal_child(PgStatPID, SIGQUIT);
3221 allow_immediate_pgstat_restart();
3224 /* We do NOT restart the syslogger */
3226 if (Shutdown != ImmediateShutdown)
3229 /* We now transit into a state of waiting for children to die */
3230 if (pmState == PM_RECOVERY ||
3231 pmState == PM_HOT_STANDBY ||
3232 pmState == PM_RUN ||
3233 pmState == PM_WAIT_BACKUP ||
3234 pmState == PM_WAIT_READONLY ||
3235 pmState == PM_SHUTDOWN)
3236 pmState = PM_WAIT_BACKENDS;
3239 * .. and if this doesn't happen quickly enough, now the clock is ticking
3240 * for us to kill them without mercy.
3242 if (AbortStartTime == 0)
3243 AbortStartTime = time(NULL);
3247 * Log the death of a child process.
3250 LogChildExit(int lev, const char *procname, int pid, int exitstatus)
3253 * size of activity_buffer is arbitrary, but set equal to default
3254 * track_activity_query_size
3256 char activity_buffer[1024];
3257 const char *activity = NULL;
3259 if (!EXIT_STATUS_0(exitstatus))
3260 activity = pgstat_get_crashed_backend_activity(pid,
3262 sizeof(activity_buffer));
3264 if (WIFEXITED(exitstatus))
3268 translator: %s is a noun phrase describing a child process, such as
3270 (errmsg("%s (PID %d) exited with exit code %d",
3271 procname, pid, WEXITSTATUS(exitstatus)),
3272 activity ? errdetail("Failed process was running: %s", activity) : 0));
3273 else if (WIFSIGNALED(exitstatus))
3278 translator: %s is a noun phrase describing a child process, such as
3280 (errmsg("%s (PID %d) was terminated by exception 0x%X",
3281 procname, pid, WTERMSIG(exitstatus)),
3282 errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
3283 activity ? errdetail("Failed process was running: %s", activity) : 0));
3284 #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST
3288 translator: %s is a noun phrase describing a child process, such as
3290 (errmsg("%s (PID %d) was terminated by signal %d: %s",
3291 procname, pid, WTERMSIG(exitstatus),
3292 WTERMSIG(exitstatus) < NSIG ?
3293 sys_siglist[WTERMSIG(exitstatus)] : "(unknown)"),
3294 activity ? errdetail("Failed process was running: %s", activity) : 0));
3299 translator: %s is a noun phrase describing a child process, such as
3301 (errmsg("%s (PID %d) was terminated by signal %d",
3302 procname, pid, WTERMSIG(exitstatus)),
3303 activity ? errdetail("Failed process was running: %s", activity) : 0));
3309 translator: %s is a noun phrase describing a child process, such as
3311 (errmsg("%s (PID %d) exited with unrecognized status %d",
3312 procname, pid, exitstatus),
3313 activity ? errdetail("Failed process was running: %s", activity) : 0));
3317 * Advance the postmaster's state machine and take actions as appropriate
3319 * This is common code for pmdie(), reaper() and sigusr1_handler(), which
3320 * receive the signals that might mean we need to change state.
3323 PostmasterStateMachine(void)
3325 if (pmState == PM_WAIT_BACKUP)
3328 * PM_WAIT_BACKUP state ends when online backup mode is not active.
3330 if (!BackupInProgress())
3331 pmState = PM_WAIT_BACKENDS;
3334 if (pmState == PM_WAIT_READONLY)
3337 * PM_WAIT_READONLY state ends when we have no regular backends that
3338 * have been started during recovery. We kill the startup and
3339 * walreceiver processes and transition to PM_WAIT_BACKENDS. Ideally,
3340 * we might like to kill these processes first and then wait for
3341 * backends to die off, but that doesn't work at present because
3342 * killing the startup process doesn't release its locks.
3344 if (CountChildren(BACKEND_TYPE_NORMAL) == 0)
3346 if (StartupPID != 0)
3347 signal_child(StartupPID, SIGTERM);
3348 if (WalReceiverPID != 0)
3349 signal_child(WalReceiverPID, SIGTERM);
3350 pmState = PM_WAIT_BACKENDS;
3355 * If we are in a state-machine state that implies waiting for backends to
3356 * exit, see if they're all gone, and change state if so.
3358 if (pmState == PM_WAIT_BACKENDS)
3361 * PM_WAIT_BACKENDS state ends when we have no regular backends
3362 * (including autovac workers), no bgworkers (including unconnected
3363 * ones), and no walwriter, autovac launcher or bgwriter. If we are
3364 * doing crash recovery or an immediate shutdown then we expect
3365 * the checkpointer to exit as well, otherwise not. The archiver,
3366 * stats, and syslogger processes are disregarded since
3367 * they are not connected to shared memory; we also disregard
3368 * dead_end children here. Walsenders are also disregarded,
3369 * they will be terminated later after writing the checkpoint record,
3370 * like the archiver process.
3372 if (CountChildren(BACKEND_TYPE_NORMAL | BACKEND_TYPE_WORKER) == 0 &&
3373 CountUnconnectedWorkers() == 0 &&
3375 WalReceiverPID == 0 &&
3377 (CheckpointerPID == 0 ||
3378 (!FatalError && Shutdown < ImmediateShutdown)) &&
3379 WalWriterPID == 0 &&
3382 if (Shutdown >= ImmediateShutdown || FatalError)
3385 * Start waiting for dead_end children to die. This state
3386 * change causes ServerLoop to stop creating new ones.
3388 pmState = PM_WAIT_DEAD_END;
3391 * We already SIGQUIT'd the archiver and stats processes, if
3392 * any, when we started immediate shutdown or entered
3399 * If we get here, we are proceeding with normal shutdown. All
3400 * the regular children are gone, and it's time to tell the
3401 * checkpointer to do a shutdown checkpoint.
3403 Assert(Shutdown > NoShutdown);
3404 /* Start the checkpointer if not running */
3405 if (CheckpointerPID == 0)
3406 CheckpointerPID = StartCheckpointer();
3407 /* And tell it to shut down */
3408 if (CheckpointerPID != 0)
3410 signal_child(CheckpointerPID, SIGUSR2);
3411 pmState = PM_SHUTDOWN;
3416 * If we failed to fork a checkpointer, just shut down.
3417 * Any required cleanup will happen at next restart. We
3418 * set FatalError so that an "abnormal shutdown" message
3419 * gets logged when we exit.
3422 pmState = PM_WAIT_DEAD_END;
3424 /* Kill the walsenders, archiver and stats collector too */
3425 SignalChildren(SIGQUIT);
3427 signal_child(PgArchPID, SIGQUIT);
3429 signal_child(PgStatPID, SIGQUIT);
3435 if (pmState == PM_SHUTDOWN_2)
3438 * PM_SHUTDOWN_2 state ends when there's no other children than
3439 * dead_end children left. There shouldn't be any regular backends
3440 * left by now anyway; what we're really waiting for is walsenders and
3443 * Walreceiver should normally be dead by now, but not when a fast
3444 * shutdown is performed during recovery.
3446 if (PgArchPID == 0 && CountChildren(BACKEND_TYPE_ALL) == 0 &&
3447 WalReceiverPID == 0)
3449 pmState = PM_WAIT_DEAD_END;
3453 if (pmState == PM_WAIT_DEAD_END)
3456 * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
3457 * (ie, no dead_end children remain), and the archiver and stats
3458 * collector are gone too.
3460 * The reason we wait for those two is to protect them against a new
3461 * postmaster starting conflicting subprocesses; this isn't an
3462 * ironclad protection, but it at least helps in the
3463 * shutdown-and-immediately-restart scenario. Note that they have
3464 * already been sent appropriate shutdown signals, either during a
3465 * normal state transition leading up to PM_WAIT_DEAD_END, or during
3466 * FatalError processing.
3468 if (dlist_is_empty(&BackendList) &&
3469 PgArchPID == 0 && PgStatPID == 0)
3471 /* These other guys should be dead already */
3472 Assert(StartupPID == 0);
3473 Assert(WalReceiverPID == 0);
3474 Assert(BgWriterPID == 0);
3475 Assert(CheckpointerPID == 0);
3476 Assert(WalWriterPID == 0);
3477 Assert(AutoVacPID == 0);
3478 /* syslogger is not considered here */
3479 pmState = PM_NO_CHILDREN;
3484 * If we've been told to shut down, we exit as soon as there are no
3485 * remaining children. If there was a crash, cleanup will occur at the
3486 * next startup. (Before PostgreSQL 8.3, we tried to recover from the
3487 * crash before exiting, but that seems unwise if we are quitting because
3488 * we got SIGTERM from init --- there may well not be time for recovery
3489 * before init decides to SIGKILL us.)
3491 * Note that the syslogger continues to run. It will exit when it sees
3492 * EOF on its input pipe, which happens when there are no more upstream
3495 if (Shutdown > NoShutdown && pmState == PM_NO_CHILDREN)
3499 ereport(LOG, (errmsg("abnormal database system shutdown")));
3505 * Terminate exclusive backup mode to avoid recovery after a clean
3506 * fast shutdown. Since an exclusive backup can only be taken
3507 * during normal running (and not, for example, while running
3508 * under Hot Standby) it only makes sense to do this if we reached
3509 * normal running. If we're still in recovery, the backup file is
3510 * one we're recovering *from*, and we must keep it around so that
3511 * recovery restarts from the right place.
3513 if (ReachedNormalRunning)
3516 /* Normal exit from the postmaster is here */
3522 * If recovery failed, or the user does not want an automatic restart
3523 * after backend crashes, wait for all non-syslogger children to exit, and
3524 * then exit postmaster. We don't try to reinitialize when recovery fails,
3525 * because more than likely it will just fail again and we will keep
3528 if (pmState == PM_NO_CHILDREN && (RecoveryError || !restart_after_crash))
3532 * If we need to recover from a crash, wait for all non-syslogger children
3533 * to exit, then reset shmem and StartupDataBase.
3535 if (FatalError && pmState == PM_NO_CHILDREN)
3538 (errmsg("all server processes terminated; reinitializing")));
3541 reset_shared(PostPortNumber);
3543 StartupPID = StartupDataBase();
3544 Assert(StartupPID != 0);
3545 pmState = PM_STARTUP;
3546 /* crash recovery started, reset SIGKILL flag */
3553 * Send a signal to a postmaster child process
3555 * On systems that have setsid(), each child process sets itself up as a
3556 * process group leader. For signals that are generally interpreted in the
3557 * appropriate fashion, we signal the entire process group not just the
3558 * direct child process. This allows us to, for example, SIGQUIT a blocked
3559 * archive_recovery script, or SIGINT a script being run by a backend via
3562 * There is a race condition for recently-forked children: they might not
3563 * have executed setsid() yet. So we signal the child directly as well as
3564 * the group. We assume such a child will handle the signal before trying
3565 * to spawn any grandchild processes. We also assume that signaling the
3566 * child twice will not cause any problems.
3569 signal_child(pid_t pid, int signal)
3571 if (kill(pid, signal) < 0)
3572 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
3581 if (kill(-pid, signal) < 0)
3582 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) (-pid), signal);
3591 * Send a signal to bgworkers that did not request backend connections
3593 * The reason this is interesting is that workers that did request connections
3594 * are considered by SignalChildren; this function complements that one.
3597 SignalUnconnectedWorkers(int signal)
3600 bool signaled = false;
3602 slist_foreach(iter, &BackgroundWorkerList)
3604 RegisteredBgWorker *rw;
3606 rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
3608 if (rw->rw_pid == 0)
3610 /* ignore connected workers */
3611 if (rw->rw_backend != NULL)
3615 (errmsg_internal("sending signal %d to process %d",
3616 signal, (int) rw->rw_pid)));
3617 signal_child(rw->rw_pid, signal);
3624 * Send a signal to the targeted children (but NOT special children;
3625 * dead_end children are never signaled, either).
3628 SignalSomeChildren(int signal, int target)
3631 bool signaled = false;
3633 dlist_foreach(iter, &BackendList)
3635 Backend *bp = dlist_container(Backend, elem, iter.cur);
3641 * Since target == BACKEND_TYPE_ALL is the most common case, we test
3642 * it first and avoid touching shared memory for every child.
3644 if (target != BACKEND_TYPE_ALL)
3647 * Assign bkend_type for any recently announced WAL Sender
3650 if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
3651 IsPostmasterChildWalSender(bp->child_slot))
3652 bp->bkend_type = BACKEND_TYPE_WALSND;
3654 if (!(target & bp->bkend_type))
3659 (errmsg_internal("sending signal %d to process %d",
3660 signal, (int) bp->pid)));
3661 signal_child(bp->pid, signal);
3668 * Send a termination signal to children. This considers all of our children
3669 * processes, except syslogger and dead_end backends.
3672 TerminateChildren(int signal)
3674 SignalChildren(signal);
3675 if (StartupPID != 0)
3676 signal_child(StartupPID, signal);
3677 if (BgWriterPID != 0)
3678 signal_child(BgWriterPID, signal);
3679 if (CheckpointerPID != 0)
3680 signal_child(CheckpointerPID, signal);
3681 if (WalWriterPID != 0)
3682 signal_child(WalWriterPID, signal);
3683 if (WalReceiverPID != 0)
3684 signal_child(WalReceiverPID, signal);
3685 if (AutoVacPID != 0)
3686 signal_child(AutoVacPID, signal);
3688 signal_child(PgArchPID, signal);
3690 signal_child(PgStatPID, signal);
3691 SignalUnconnectedWorkers(signal);
3695 * BackendStartup -- start backend process
3697 * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
3699 * Note: if you change this code, also consider StartAutovacuumWorker.
3702 BackendStartup(Port *port)
3704 Backend *bn; /* for backend cleanup */
3708 * Create backend data structure. Better before the fork() so we can
3709 * handle failure cleanly.
3711 bn = (Backend *) malloc(sizeof(Backend));
3715 (errcode(ERRCODE_OUT_OF_MEMORY),
3716 errmsg("out of memory")));
3717 return STATUS_ERROR;
3721 * Compute the cancel key that will be assigned to this backend. The
3722 * backend will have its own copy in the forked-off process' value of
3723 * MyCancelKey, so that it can transmit the key to the frontend.
3725 MyCancelKey = PostmasterRandom();
3726 bn->cancel_key = MyCancelKey;
3728 /* Pass down canAcceptConnections state */
3729 port->canAcceptConnections = canAcceptConnections();
3730 bn->dead_end = (port->canAcceptConnections != CAC_OK &&
3731 port->canAcceptConnections != CAC_WAITBACKUP);
3734 * Unless it's a dead_end child, assign it a child slot number
3737 bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
3741 /* Hasn't asked to be notified about any bgworkers yet */
3742 bn->bgworker_notify = false;
3745 pid = backend_forkexec(port);
3746 #else /* !EXEC_BACKEND */
3747 pid = fork_process();
3748 if (pid == 0) /* child */
3753 * Let's clean up ourselves as the postmaster child, and close the
3754 * postmaster's listen sockets. (In EXEC_BACKEND case this is all
3755 * done in SubPostmasterMain.)
3757 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
3759 MyProcPid = getpid(); /* reset MyProcPid */
3761 MyStartTime = time(NULL);
3763 /* We don't want the postmaster's proc_exit() handlers */
3766 /* Close the postmaster's sockets */
3767 ClosePostmasterPorts(false);
3769 /* Perform additional initialization and collect startup packet */
3770 BackendInitialize(port);
3772 /* And run the backend */
3775 #endif /* EXEC_BACKEND */
3779 /* in parent, fork failed */
3780 int save_errno = errno;
3783 (void) ReleasePostmasterChildSlot(bn->child_slot);
3787 (errmsg("could not fork new process for connection: %m")));
3788 report_fork_failure_to_client(port, save_errno);
3789 return STATUS_ERROR;
3792 /* in parent, successful fork */
3794 (errmsg_internal("forked new backend, pid=%d socket=%d",
3795 (int) pid, (int) port->sock)));
3798 * Everything's been successful, it's safe to add this backend to our list
3802 bn->bkend_type = BACKEND_TYPE_NORMAL; /* Can change later to WALSND */
3803 dlist_push_head(&BackendList, &bn->elem);
3807 ShmemBackendArrayAdd(bn);
3814 * Try to report backend fork() failure to client before we close the
3815 * connection. Since we do not care to risk blocking the postmaster on
3816 * this connection, we set the connection to non-blocking and try only once.
3818 * This is grungy special-purpose code; we cannot use backend libpq since
3819 * it's not up and running.
3822 report_fork_failure_to_client(Port *port, int errnum)
3827 /* Format the error message packet (always V2 protocol) */
3828 snprintf(buffer, sizeof(buffer), "E%s%s\n",
3829 _("could not fork new process for connection: "),
3832 /* Set port to non-blocking. Don't do send() if this fails */
3833 if (!pg_set_noblock(port->sock))
3836 /* We'll retry after EINTR, but ignore all other failures */
3839 rc = send(port->sock, buffer, strlen(buffer) + 1, 0);
3840 } while (rc < 0 && errno == EINTR);
3845 * BackendInitialize -- initialize an interactive (postmaster-child)
3846 * backend process, and collect the client's startup packet.
3848 * returns: nothing. Will not return at all if there's any failure.
3850 * Note: this code does not depend on having any access to shared memory.
3851 * In the EXEC_BACKEND case, we are physically attached to shared memory
3852 * but have not yet set up most of our local pointers to shmem structures.
3855 BackendInitialize(Port *port)
3859 char remote_host[NI_MAXHOST];
3860 char remote_port[NI_MAXSERV];
3861 char remote_ps_data[NI_MAXHOST];
3863 /* Save port etc. for ps status */
3867 * PreAuthDelay is a debugging aid for investigating problems in the
3868 * authentication cycle: it can be set in postgresql.conf to allow time to
3869 * attach to the newly-forked backend with a debugger. (See also
3870 * PostAuthDelay, which we allow clients to pass through PGOPTIONS, but it
3871 * is not honored until after authentication.)
3873 if (PreAuthDelay > 0)
3874 pg_usleep(PreAuthDelay * 1000000L);
3876 /* This flag will remain set until InitPostgres finishes authentication */
3877 ClientAuthInProgress = true; /* limit visibility of log messages */
3879 /* save process start time */
3880 port->SessionStartTime = GetCurrentTimestamp();
3881 MyStartTime = timestamptz_to_time_t(port->SessionStartTime);
3883 /* set these to empty in case they are needed before we set them up */
3884 port->remote_host = "";
3885 port->remote_port = "";
3888 * Initialize libpq and enable reporting of ereport errors to the client.
3889 * Must do this now because authentication uses libpq to send messages.
3891 pq_init(); /* initialize libpq to talk to client */
3892 whereToSendOutput = DestRemote; /* now safe to ereport to client */
3895 * If possible, make this process a group leader, so that the postmaster
3896 * can signal any child processes too. (We do this now on the off chance
3897 * that something might spawn a child process during authentication.)
3901 elog(FATAL, "setsid() failed: %m");
3905 * We arrange for a simple exit(1) if we receive SIGTERM or SIGQUIT or
3906 * timeout while trying to collect the startup packet. Otherwise the
3907 * postmaster cannot shutdown the database FAST or IMMED cleanly if a
3908 * buggy client fails to send the packet promptly.
3910 pqsignal(SIGTERM, startup_die);
3911 pqsignal(SIGQUIT, startup_die);
3912 InitializeTimeouts(); /* establishes SIGALRM handler */
3913 PG_SETMASK(&StartupBlockSig);
3916 * Get the remote host name and port for logging and status display.
3918 remote_host[0] = '\0';
3919 remote_port[0] = '\0';
3920 if ((ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
3921 remote_host, sizeof(remote_host),
3922 remote_port, sizeof(remote_port),
3923 (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV)) != 0)
3925 (errmsg_internal("pg_getnameinfo_all() failed: %s",
3926 gai_strerror(ret))));
3927 if (remote_port[0] == '\0')
3928 snprintf(remote_ps_data, sizeof(remote_ps_data), "%s", remote_host);
3930 snprintf(remote_ps_data, sizeof(remote_ps_data), "%s(%s)", remote_host, remote_port);
3932 if (Log_connections)
3936 (errmsg("connection received: host=%s port=%s",
3941 (errmsg("connection received: host=%s",
3946 * save remote_host and remote_port in port structure
3948 port->remote_host = strdup(remote_host);
3949 port->remote_port = strdup(remote_port);
3951 port->remote_hostname = port->remote_host;
3954 * Ready to begin client interaction. We will give up and exit(1) after a
3955 * time delay, so that a broken client can't hog a connection
3956 * indefinitely. PreAuthDelay and any DNS interactions above don't count
3957 * against the time limit.
3959 * Note: AuthenticationTimeout is applied here while waiting for the
3960 * startup packet, and then again in InitPostgres for the duration of any
3961 * authentication operations. So a hostile client could tie up the
3962 * process for nearly twice AuthenticationTimeout before we kick him off.
3964 * Note: because PostgresMain will call InitializeTimeouts again, the
3965 * registration of STARTUP_PACKET_TIMEOUT will be lost. This is okay
3966 * since we never use it again after this function.
3968 RegisterTimeout(STARTUP_PACKET_TIMEOUT, StartupPacketTimeoutHandler);
3969 enable_timeout_after(STARTUP_PACKET_TIMEOUT, AuthenticationTimeout * 1000);
3972 * Receive the startup packet (which might turn out to be a cancel request
3975 status = ProcessStartupPacket(port, false);
3978 * Stop here if it was bad or a cancel packet. ProcessStartupPacket
3979 * already did any appropriate error reporting.
3981 if (status != STATUS_OK)
3985 * Now that we have the user and database name, we can set the process
3986 * title for ps. It's good to do this as early as possible in startup.
3988 * For a walsender, the ps display is set in the following form:
3990 * postgres: wal sender process <user> <host> <activity>
3992 * To achieve that, we pass "wal sender process" as username and username
3993 * as dbname to init_ps_display(). XXX: should add a new variant of
3994 * init_ps_display() to avoid abusing the parameters like this.
3997 init_ps_display("wal sender process", port->user_name, remote_ps_data,
3998 update_process_title ? "authentication" : "");
4000 init_ps_display(port->user_name, port->database_name, remote_ps_data,
4001 update_process_title ? "authentication" : "");
4004 * Disable the timeout, and prevent SIGTERM/SIGQUIT again.
4006 disable_timeout(STARTUP_PACKET_TIMEOUT, false);
4007 PG_SETMASK(&BlockSig);
4012 * BackendRun -- set up the backend's argument list and invoke PostgresMain()
4015 * Shouldn't return at all.
4016 * If PostgresMain() fails, return status.
4019 BackendRun(Port *port)
4029 * Don't want backend to be able to see the postmaster random number
4030 * generator state. We have to clobber the static random_seed *and* start
4031 * a new random sequence in the random() library function.
4034 random_start_time.tv_usec = 0;
4035 /* slightly hacky way to get integer microseconds part of timestamptz */
4036 TimestampDifference(0, port->SessionStartTime, &secs, &usecs);
4037 srandom((unsigned int) (MyProcPid ^ usecs));
4040 * Now, build the argv vector that will be given to PostgresMain.
4042 * The maximum possible number of commandline arguments that could come
4043 * from ExtraOptions is (strlen(ExtraOptions) + 1) / 2; see
4046 maxac = 2; /* for fixed args supplied below */
4047 maxac += (strlen(ExtraOptions) + 1) / 2;
4049 av = (char **) MemoryContextAlloc(TopMemoryContext,
4050 maxac * sizeof(char *));
4053 av[ac++] = "postgres";
4056 * Pass any backend switches specified with -o on the postmaster's own
4057 * command line. We assume these are secure. (It's OK to mangle
4058 * ExtraOptions now, since we're safely inside a subprocess.)
4060 pg_split_opts(av, &ac, ExtraOptions);
4067 * Debug: print arguments being passed to backend
4070 (errmsg_internal("%s child[%d]: starting with (",
4071 progname, (int) getpid())));
4072 for (i = 0; i < ac; ++i)
4074 (errmsg_internal("\t%s", av[i])));
4076 (errmsg_internal(")")));
4079 * Make sure we aren't in PostmasterContext anymore. (We can't delete it
4080 * just yet, though, because InitPostgres will need the HBA data.)
4082 MemoryContextSwitchTo(TopMemoryContext);
4084 PostgresMain(ac, av, port->database_name, port->user_name);
4091 * postmaster_forkexec -- fork and exec a postmaster subprocess
4093 * The caller must have set up the argv array already, except for argv[2]
4094 * which will be filled with the name of the temp variable file.
4096 * Returns the child process PID, or -1 on fork failure (a suitable error
4097 * message has been logged on failure).
4099 * All uses of this routine will dispatch to SubPostmasterMain in the
4103 postmaster_forkexec(int argc, char *argv[])
4107 /* This entry point passes dummy values for the Port variables */
4108 memset(&port, 0, sizeof(port));
4109 return internal_forkexec(argc, argv, &port);
4113 * backend_forkexec -- fork/exec off a backend process
4115 * Some operating systems (WIN32) don't have fork() so we have to simulate
4116 * it by storing parameters that need to be passed to the child and
4117 * then create a new child process.
4119 * returns the pid of the fork/exec'd process, or -1 on failure
4122 backend_forkexec(Port *port)
4127 av[ac++] = "postgres";
4128 av[ac++] = "--forkbackend";
4129 av[ac++] = NULL; /* filled in by internal_forkexec */
4132 Assert(ac < lengthof(av));
4134 return internal_forkexec(ac, av, port);
4140 * internal_forkexec non-win32 implementation
4142 * - writes out backend variables to the parameter file
4143 * - fork():s, and then exec():s the child process
4146 internal_forkexec(int argc, char *argv[], Port *port)
4148 static unsigned long tmpBackendFileNum = 0;
4150 char tmpfilename[MAXPGPATH];
4151 BackendParameters param;
4154 if (!save_backend_variables(¶m, port))
4155 return -1; /* log made by save_backend_variables */
4157 /* Calculate name for temp file */
4158 snprintf(tmpfilename, MAXPGPATH, "%s/%s.backend_var.%d.%lu",
4159 PG_TEMP_FILES_DIR, PG_TEMP_FILE_PREFIX,
4160 MyProcPid, ++tmpBackendFileNum);
4163 fp = AllocateFile(tmpfilename, PG_BINARY_W);
4167 * As in OpenTemporaryFileInTablespace, try to make the temp-file
4170 mkdir(PG_TEMP_FILES_DIR, S_IRWXU);
4172 fp = AllocateFile(tmpfilename, PG_BINARY_W);
4176 (errcode_for_file_access(),
4177 errmsg("could not create file \"%s\": %m",
4183 if (fwrite(¶m, sizeof(param), 1, fp) != 1)
4186 (errcode_for_file_access(),
4187 errmsg("could not write to file \"%s\": %m", tmpfilename)));
4196 (errcode_for_file_access(),
4197 errmsg("could not write to file \"%s\": %m", tmpfilename)));
4201 /* Make sure caller set up argv properly */
4203 Assert(argv[argc] == NULL);
4204 Assert(strncmp(argv[1], "--fork", 6) == 0);
4205 Assert(argv[2] == NULL);
4207 /* Insert temp file name after --fork argument */
4208 argv[2] = tmpfilename;
4210 /* Fire off execv in child */
4211 if ((pid = fork_process()) == 0)
4213 if (execv(postgres_exec_path, argv) < 0)
4216 (errmsg("could not execute server process \"%s\": %m",
4217 postgres_exec_path)));
4218 /* We're already in the child process here, can't return */
4223 return pid; /* Parent returns pid, or -1 on fork failure */
4228 * internal_forkexec win32 implementation
4230 * - starts backend using CreateProcess(), in suspended state
4231 * - writes out backend variables to the parameter file
4232 * - during this, duplicates handles and sockets required for
4233 * inheritance into the new process
4234 * - resumes execution of the new process once the backend parameter
4238 internal_forkexec(int argc, char *argv[], Port *port)
4241 PROCESS_INFORMATION pi;
4244 char cmdLine[MAXPGPATH * 2];
4246 BackendParameters *param;
4247 SECURITY_ATTRIBUTES sa;
4248 char paramHandleStr[32];
4249 win32_deadchild_waitinfo *childinfo;
4251 /* Make sure caller set up argv properly */
4253 Assert(argv[argc] == NULL);
4254 Assert(strncmp(argv[1], "--fork", 6) == 0);
4255 Assert(argv[2] == NULL);
4257 /* Set up shared memory for parameter passing */
4258 ZeroMemory(&sa, sizeof(sa));
4259 sa.nLength = sizeof(sa);
4260 sa.bInheritHandle = TRUE;
4261 paramHandle = CreateFileMapping(INVALID_HANDLE_VALUE,
4265 sizeof(BackendParameters),
4267 if (paramHandle == INVALID_HANDLE_VALUE)
4269 elog(LOG, "could not create backend parameter file mapping: error code %lu",
4274 param = MapViewOfFile(paramHandle, FILE_MAP_WRITE, 0, 0, sizeof(BackendParameters));
4277 elog(LOG, "could not map backend parameter memory: error code %lu",
4279 CloseHandle(paramHandle);
4283 /* Insert temp file name after --fork argument */
4285 sprintf(paramHandleStr, "%llu", (LONG_PTR) paramHandle);
4287 sprintf(paramHandleStr, "%lu", (DWORD) paramHandle);
4289 argv[2] = paramHandleStr;
4291 /* Format the cmd line */
4292 cmdLine[sizeof(cmdLine) - 1] = '\0';
4293 cmdLine[sizeof(cmdLine) - 2] = '\0';
4294 snprintf(cmdLine, sizeof(cmdLine) - 1, "\"%s\"", postgres_exec_path);
4296 while (argv[++i] != NULL)
4298 j = strlen(cmdLine);
4299 snprintf(cmdLine + j, sizeof(cmdLine) - 1 - j, " \"%s\"", argv[i]);
4301 if (cmdLine[sizeof(cmdLine) - 2] != '\0')
4303 elog(LOG, "subprocess command line too long");
4307 memset(&pi, 0, sizeof(pi));
4308 memset(&si, 0, sizeof(si));
4312 * Create the subprocess in a suspended state. This will be resumed later,
4313 * once we have written out the parameter file.
4315 if (!CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, CREATE_SUSPENDED,
4316 NULL, NULL, &si, &pi))
4318 elog(LOG, "CreateProcess call failed: %m (error code %lu)",
4323 if (!save_backend_variables(param, port, pi.hProcess, pi.dwProcessId))
4326 * log made by save_backend_variables, but we have to clean up the
4327 * mess with the half-started process
4329 if (!TerminateProcess(pi.hProcess, 255))
4331 (errmsg_internal("could not terminate unstarted process: error code %lu",
4333 CloseHandle(pi.hProcess);
4334 CloseHandle(pi.hThread);
4335 return -1; /* log made by save_backend_variables */
4338 /* Drop the parameter shared memory that is now inherited to the backend */
4339 if (!UnmapViewOfFile(param))
4340 elog(LOG, "could not unmap view of backend parameter file: error code %lu",
4342 if (!CloseHandle(paramHandle))
4343 elog(LOG, "could not close handle to backend parameter file: error code %lu",
4347 * Reserve the memory region used by our main shared memory segment before
4348 * we resume the child process.
4350 if (!pgwin32_ReserveSharedMemoryRegion(pi.hProcess))
4353 * Failed to reserve the memory, so terminate the newly created
4354 * process and give up.
4356 if (!TerminateProcess(pi.hProcess, 255))
4358 (errmsg_internal("could not terminate process that failed to reserve memory: error code %lu",
4360 CloseHandle(pi.hProcess);
4361 CloseHandle(pi.hThread);
4362 return -1; /* logging done made by
4363 * pgwin32_ReserveSharedMemoryRegion() */
4367 * Now that the backend variables are written out, we start the child
4368 * thread so it can start initializing while we set up the rest of the
4371 if (ResumeThread(pi.hThread) == -1)
4373 if (!TerminateProcess(pi.hProcess, 255))
4376 (errmsg_internal("could not terminate unstartable process: error code %lu",
4378 CloseHandle(pi.hProcess);
4379 CloseHandle(pi.hThread);
4382 CloseHandle(pi.hProcess);
4383 CloseHandle(pi.hThread);
4385 (errmsg_internal("could not resume thread of unstarted process: error code %lu",
4391 * Queue a waiter for to signal when this child dies. The wait will be
4392 * handled automatically by an operating system thread pool.
4394 * Note: use malloc instead of palloc, since it needs to be thread-safe.
4395 * Struct will be free():d from the callback function that runs on a
4398 childinfo = malloc(sizeof(win32_deadchild_waitinfo));
4401 (errcode(ERRCODE_OUT_OF_MEMORY),
4402 errmsg("out of memory")));
4404 childinfo->procHandle = pi.hProcess;
4405 childinfo->procId = pi.dwProcessId;
4407 if (!RegisterWaitForSingleObject(&childinfo->waitHandle,
4409 pgwin32_deadchild_callback,
4412 WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD))
4414 (errmsg_internal("could not register process for wait: error code %lu",
4417 /* Don't close pi.hProcess here - the wait thread needs access to it */
4419 CloseHandle(pi.hThread);
4421 return pi.dwProcessId;
4427 * SubPostmasterMain -- Get the fork/exec'd process into a state equivalent
4428 * to what it would be if we'd simply forked on Unix, and then
4429 * dispatch to the appropriate place.
4431 * The first two command line arguments are expected to be "--forkFOO"
4432 * (where FOO indicates which postmaster child we are to become), and
4433 * the name of a variables file that we can read to load data that would
4434 * have been inherited by fork() on Unix. Remaining arguments go to the
4435 * subprocess FooMain() routine.
4438 SubPostmasterMain(int argc, char *argv[])
4442 /* Do this sooner rather than later... */
4443 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
4445 MyProcPid = getpid(); /* reset MyProcPid */
4447 MyStartTime = time(NULL);
4450 * make sure stderr is in binary mode before anything can possibly be
4451 * written to it, in case it's actually the syslogger pipe, so the pipe
4452 * chunking protocol isn't disturbed. Non-logpipe data gets translated on
4453 * redirection (e.g. via pg_ctl -l) anyway.
4456 _setmode(fileno(stderr), _O_BINARY);
4459 /* Lose the postmaster's on-exit routines (really a no-op) */
4462 /* In EXEC_BACKEND case we will not have inherited these settings */
4463 IsPostmasterEnvironment = true;
4464 whereToSendOutput = DestNone;
4466 /* Setup essential subsystems (to ensure elog() behaves sanely) */
4467 MemoryContextInit();
4468 InitializeGUCOptions();
4470 /* Read in the variables file */
4471 memset(&port, 0, sizeof(Port));
4472 read_backend_variables(argv[2], &port);
4475 * Set reference point for stack-depth checking
4480 * Set up memory area for GSS information. Mirrors the code in ConnCreate
4481 * for the non-exec case.
4483 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
4484 port.gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
4487 (errcode(ERRCODE_OUT_OF_MEMORY),
4488 errmsg("out of memory")));
4491 /* Check we got appropriate args */
4493 elog(FATAL, "invalid subpostmaster invocation");
4496 * If appropriate, physically re-attach to shared memory segment. We want
4497 * to do this before going any further to ensure that we can attach at the
4498 * same address the postmaster used.
4500 if (strcmp(argv[1], "--forkbackend") == 0 ||
4501 strcmp(argv[1], "--forkavlauncher") == 0 ||
4502 strcmp(argv[1], "--forkavworker") == 0 ||
4503 strcmp(argv[1], "--forkboot") == 0 ||
4504 strncmp(argv[1], "--forkbgworker=", 15) == 0)
4505 PGSharedMemoryReAttach();
4507 /* autovacuum needs this set before calling InitProcess */
4508 if (strcmp(argv[1], "--forkavlauncher") == 0)
4509 AutovacuumLauncherIAm();
4510 if (strcmp(argv[1], "--forkavworker") == 0)
4511 AutovacuumWorkerIAm();
4514 * Start our win32 signal implementation. This has to be done after we
4515 * read the backend variables, because we need to pick up the signal pipe
4516 * from the parent process.
4519 pgwin32_signal_initialize();
4522 /* In EXEC_BACKEND case we will not have inherited these settings */
4524 PG_SETMASK(&BlockSig);
4526 /* Read in remaining GUC variables */
4527 read_nondefault_variables();
4530 * Reload any libraries that were preloaded by the postmaster. Since we
4531 * exec'd this process, those libraries didn't come along with us; but we
4532 * should load them into all child processes to be consistent with the
4533 * non-EXEC_BACKEND behavior.
4535 process_shared_preload_libraries();
4537 /* Run backend or appropriate child */
4538 if (strcmp(argv[1], "--forkbackend") == 0)
4540 Assert(argc == 3); /* shouldn't be any more args */
4542 /* Close the postmaster's sockets */
4543 ClosePostmasterPorts(false);
4546 * Need to reinitialize the SSL library in the backend, since the
4547 * context structures contain function pointers and cannot be passed
4548 * through the parameter file.
4550 * XXX should we do this in all child processes? For the moment it's
4551 * enough to do it in backend children.
4555 secure_initialize();
4559 * Perform additional initialization and collect startup packet.
4561 * We want to do this before InitProcess() for a couple of reasons: 1.
4562 * so that we aren't eating up a PGPROC slot while waiting on the
4563 * client. 2. so that if InitProcess() fails due to being out of
4564 * PGPROC slots, we have already initialized libpq and are able to
4565 * report the error to the client.
4567 BackendInitialize(&port);
4569 /* Restore basic shared memory pointers */
4570 InitShmemAccess(UsedShmemSegAddr);
4572 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
4576 * Attach process to shared data structures. If testing EXEC_BACKEND
4577 * on Linux, you must run this as root before starting the postmaster:
4579 * echo 0 >/proc/sys/kernel/randomize_va_space
4581 * This prevents a randomized stack base address that causes child
4582 * shared memory to be at a different address than the parent, making
4583 * it impossible to attached to shared memory. Return the value to
4584 * '1' when finished.
4586 CreateSharedMemoryAndSemaphores(false, 0);
4588 /* And run the backend */
4589 BackendRun(&port); /* does not return */
4591 if (strcmp(argv[1], "--forkboot") == 0)
4593 /* Close the postmaster's sockets */
4594 ClosePostmasterPorts(false);
4596 /* Restore basic shared memory pointers */
4597 InitShmemAccess(UsedShmemSegAddr);
4599 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
4600 InitAuxiliaryProcess();
4602 /* Attach process to shared data structures */
4603 CreateSharedMemoryAndSemaphores(false, 0);
4605 AuxiliaryProcessMain(argc - 2, argv + 2); /* does not return */
4607 if (strcmp(argv[1], "--forkavlauncher") == 0)
4609 /* Close the postmaster's sockets */
4610 ClosePostmasterPorts(false);
4612 /* Restore basic shared memory pointers */
4613 InitShmemAccess(UsedShmemSegAddr);
4615 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
4618 /* Attach process to shared data structures */
4619 CreateSharedMemoryAndSemaphores(false, 0);
4621 AutoVacLauncherMain(argc - 2, argv + 2); /* does not return */
4623 if (strcmp(argv[1], "--forkavworker") == 0)
4625 /* Close the postmaster's sockets */
4626 ClosePostmasterPorts(false);
4628 /* Restore basic shared memory pointers */
4629 InitShmemAccess(UsedShmemSegAddr);
4631 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
4634 /* Attach process to shared data structures */
4635 CreateSharedMemoryAndSemaphores(false, 0);
4637 AutoVacWorkerMain(argc - 2, argv + 2); /* does not return */
4639 if (strncmp(argv[1], "--forkbgworker=", 15) == 0)
4643 /* Close the postmaster's sockets */
4644 ClosePostmasterPorts(false);
4646 /* Restore basic shared memory pointers */
4647 InitShmemAccess(UsedShmemSegAddr);
4649 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
4652 /* Attach process to shared data structures */
4653 CreateSharedMemoryAndSemaphores(false, 0);
4655 shmem_slot = atoi(argv[1] + 15);
4656 MyBgworkerEntry = BackgroundWorkerEntry(shmem_slot);
4657 StartBackgroundWorker();
4659 if (strcmp(argv[1], "--forkarch") == 0)
4661 /* Close the postmaster's sockets */
4662 ClosePostmasterPorts(false);
4664 /* Do not want to attach to shared memory */
4666 PgArchiverMain(argc, argv); /* does not return */
4668 if (strcmp(argv[1], "--forkcol") == 0)
4670 /* Close the postmaster's sockets */
4671 ClosePostmasterPorts(false);
4673 /* Do not want to attach to shared memory */
4675 PgstatCollectorMain(argc, argv); /* does not return */
4677 if (strcmp(argv[1], "--forklog") == 0)
4679 /* Close the postmaster's sockets */
4680 ClosePostmasterPorts(true);
4682 /* Do not want to attach to shared memory */
4684 SysLoggerMain(argc, argv); /* does not return */
4687 abort(); /* shouldn't get here */
4689 #endif /* EXEC_BACKEND */
4693 * ExitPostmaster -- cleanup
4695 * Do NOT call exit() directly --- always go through here!
4698 ExitPostmaster(int status)
4700 /* should cleanup shared memory and kill all backends */
4703 * Not sure of the semantics here. When the Postmaster dies, should the
4704 * backends all be killed? probably not.
4706 * MUST -- vadim 05-10-1999
4713 * sigusr1_handler - handle signal conditions from child processes
4716 sigusr1_handler(SIGNAL_ARGS)
4718 int save_errno = errno;
4719 bool start_bgworker = false;
4721 PG_SETMASK(&BlockSig);
4723 /* Process background worker state change. */
4724 if (CheckPostmasterSignal(PMSIGNAL_BACKGROUND_WORKER_CHANGE))
4726 BackgroundWorkerStateChange();
4727 start_bgworker = true;
4731 * RECOVERY_STARTED and BEGIN_HOT_STANDBY signals are ignored in
4732 * unexpected states. If the startup process quickly starts up, completes
4733 * recovery, exits, we might process the death of the startup process
4734 * first. We don't want to go back to recovery in that case.
4736 if (CheckPostmasterSignal(PMSIGNAL_RECOVERY_STARTED) &&
4737 pmState == PM_STARTUP && Shutdown == NoShutdown)
4739 /* WAL redo has started. We're out of reinitialization. */
4741 Assert(AbortStartTime == 0);
4744 * Crank up the background tasks. It doesn't matter if this fails,
4745 * we'll just try again later.
4747 Assert(CheckpointerPID == 0);
4748 CheckpointerPID = StartCheckpointer();
4749 Assert(BgWriterPID == 0);
4750 BgWriterPID = StartBackgroundWriter();
4752 pmState = PM_RECOVERY;
4754 if (CheckPostmasterSignal(PMSIGNAL_BEGIN_HOT_STANDBY) &&
4755 pmState == PM_RECOVERY && Shutdown == NoShutdown)
4758 * Likewise, start other special children as needed.
4760 Assert(PgStatPID == 0);
4761 PgStatPID = pgstat_start();
4764 (errmsg("database system is ready to accept read only connections")));
4766 pmState = PM_HOT_STANDBY;
4767 /* Some workers may be scheduled to start now */
4768 start_bgworker = true;
4772 maybe_start_bgworker();
4774 if (CheckPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER) &&
4778 * Send SIGUSR1 to archiver process, to wake it up and begin archiving
4779 * next transaction log file.
4781 signal_child(PgArchPID, SIGUSR1);
4784 if (CheckPostmasterSignal(PMSIGNAL_ROTATE_LOGFILE) &&
4787 /* Tell syslogger to rotate logfile */
4788 signal_child(SysLoggerPID, SIGUSR1);
4791 if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER) &&
4792 Shutdown == NoShutdown)
4795 * Start one iteration of the autovacuum daemon, even if autovacuuming
4796 * is nominally not enabled. This is so we can have an active defense
4797 * against transaction ID wraparound. We set a flag for the main loop
4798 * to do it rather than trying to do it here --- this is because the
4799 * autovac process itself may send the signal, and we want to handle
4800 * that by launching another iteration as soon as the current one
4803 start_autovac_launcher = true;
4806 if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER) &&
4807 Shutdown == NoShutdown)
4809 /* The autovacuum launcher wants us to start a worker process. */
4810 StartAutovacuumWorker();
4813 if (CheckPostmasterSignal(PMSIGNAL_START_WALRECEIVER) &&
4814 WalReceiverPID == 0 &&
4815 (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
4816 pmState == PM_HOT_STANDBY || pmState == PM_WAIT_READONLY) &&
4817 Shutdown == NoShutdown)
4819 /* Startup Process wants us to start the walreceiver process. */
4820 WalReceiverPID = StartWalReceiver();
4823 if (CheckPostmasterSignal(PMSIGNAL_ADVANCE_STATE_MACHINE) &&
4824 (pmState == PM_WAIT_BACKUP || pmState == PM_WAIT_BACKENDS))
4826 /* Advance postmaster's state machine */
4827 PostmasterStateMachine();
4830 if (CheckPromoteSignal() && StartupPID != 0 &&
4831 (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
4832 pmState == PM_HOT_STANDBY || pmState == PM_WAIT_READONLY))
4834 /* Tell startup process to finish recovery */
4835 signal_child(StartupPID, SIGUSR2);
4838 PG_SETMASK(&UnBlockSig);
4844 * SIGTERM or SIGQUIT while processing startup packet.
4845 * Clean up and exit(1).
4847 * XXX: possible future improvement: try to send a message indicating
4848 * why we are disconnecting. Problem is to be sure we don't block while
4849 * doing so, nor mess up SSL initialization. In practice, if the client
4850 * has wedged here, it probably couldn't do anything with the message anyway.
4853 startup_die(SIGNAL_ARGS)
4859 * Dummy signal handler
4861 * We use this for signals that we don't actually use in the postmaster,
4862 * but we do use in backends. If we were to SIG_IGN such signals in the
4863 * postmaster, then a newly started backend might drop a signal that arrives
4864 * before it's able to reconfigure its signal processing. (See notes in
4868 dummy_handler(SIGNAL_ARGS)
4873 * Timeout while processing startup packet.
4874 * As for startup_die(), we clean up and exit(1).
4877 StartupPacketTimeoutHandler(void)
4887 RandomSalt(char *md5Salt)
4892 * We use % 255, sacrificing one possible byte value, so as to ensure that
4893 * all bits of the random() value participate in the result. While at it,
4894 * add one to avoid generating any null bytes.
4896 rand = PostmasterRandom();
4897 md5Salt[0] = (rand % 255) + 1;
4898 rand = PostmasterRandom();
4899 md5Salt[1] = (rand % 255) + 1;
4900 rand = PostmasterRandom();
4901 md5Salt[2] = (rand % 255) + 1;
4902 rand = PostmasterRandom();
4903 md5Salt[3] = (rand % 255) + 1;
4910 PostmasterRandom(void)
4913 * Select a random seed at the time of first receiving a request.
4915 if (random_seed == 0)
4919 struct timeval random_stop_time;
4921 gettimeofday(&random_stop_time, NULL);
4924 * We are not sure how much precision is in tv_usec, so we swap
4925 * the high and low 16 bits of 'random_stop_time' and XOR them
4926 * with 'random_start_time'. On the off chance that the result is
4927 * 0, we loop until it isn't.
4929 random_seed = random_start_time.tv_usec ^
4930 ((random_stop_time.tv_usec << 16) |
4931 ((random_stop_time.tv_usec >> 16) & 0xffff));
4933 while (random_seed == 0);
4935 srandom(random_seed);
4942 * Count up number of worker processes that did not request backend connections
4943 * See SignalUnconnectedWorkers for why this is interesting.
4946 CountUnconnectedWorkers(void)
4951 slist_foreach(iter, &BackgroundWorkerList)
4953 RegisteredBgWorker *rw;
4955 rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
4957 if (rw->rw_pid == 0)
4959 /* ignore connected workers */
4960 if (rw->rw_backend != NULL)
4969 * Count up number of child processes of specified types (dead_end chidren
4970 * are always excluded).
4973 CountChildren(int target)
4978 dlist_foreach(iter, &BackendList)
4980 Backend *bp = dlist_container(Backend, elem, iter.cur);
4986 * Since target == BACKEND_TYPE_ALL is the most common case, we test
4987 * it first and avoid touching shared memory for every child.
4989 if (target != BACKEND_TYPE_ALL)
4992 * Assign bkend_type for any recently announced WAL Sender
4995 if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
4996 IsPostmasterChildWalSender(bp->child_slot))
4997 bp->bkend_type = BACKEND_TYPE_WALSND;
4999 if (!(target & bp->bkend_type))
5010 * StartChildProcess -- start an auxiliary process for the postmaster
5012 * xlop determines what kind of child will be started. All child types
5013 * initially go to AuxiliaryProcessMain, which will handle common setup.
5015 * Return value of StartChildProcess is subprocess' PID, or 0 if failed
5016 * to start subprocess.
5019 StartChildProcess(AuxProcType type)
5027 * Set up command-line arguments for subprocess
5029 av[ac++] = "postgres";
5032 av[ac++] = "--forkboot";
5033 av[ac++] = NULL; /* filled in by postmaster_forkexec */
5036 snprintf(typebuf, sizeof(typebuf), "-x%d", type);
5040 Assert(ac < lengthof(av));
5043 pid = postmaster_forkexec(ac, av);
5044 #else /* !EXEC_BACKEND */
5045 pid = fork_process();
5047 if (pid == 0) /* child */
5049 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
5051 /* Close the postmaster's sockets */
5052 ClosePostmasterPorts(false);
5054 /* Lose the postmaster's on-exit routines and port connections */
5057 /* Release postmaster's working memory context */
5058 MemoryContextSwitchTo(TopMemoryContext);
5059 MemoryContextDelete(PostmasterContext);
5060 PostmasterContext = NULL;
5062 AuxiliaryProcessMain(ac, av);
5065 #endif /* EXEC_BACKEND */
5069 /* in parent, fork failed */
5070 int save_errno = errno;
5075 case StartupProcess:
5077 (errmsg("could not fork startup process: %m")));
5079 case BgWriterProcess:
5081 (errmsg("could not fork background writer process: %m")));
5083 case CheckpointerProcess:
5085 (errmsg("could not fork checkpointer process: %m")));
5087 case WalWriterProcess:
5089 (errmsg("could not fork WAL writer process: %m")));
5091 case WalReceiverProcess:
5093 (errmsg("could not fork WAL receiver process: %m")));
5097 (errmsg("could not fork process: %m")));
5102 * fork failure is fatal during startup, but there's no need to choke
5103 * immediately if starting other child types fails.
5105 if (type == StartupProcess)
5111 * in parent, successful fork
5117 * StartAutovacuumWorker
5118 * Start an autovac worker process.
5120 * This function is here because it enters the resulting PID into the
5121 * postmaster's private backends list.
5123 * NB -- this code very roughly matches BackendStartup.
5126 StartAutovacuumWorker(void)
5131 * If not in condition to run a process, don't try, but handle it like a
5132 * fork failure. This does not normally happen, since the signal is only
5133 * supposed to be sent by autovacuum launcher when it's OK to do it, but
5134 * we have to check to avoid race-condition problems during DB state
5137 if (canAcceptConnections() == CAC_OK)
5139 bn = (Backend *) malloc(sizeof(Backend));
5143 * Compute the cancel key that will be assigned to this session.
5144 * We probably don't need cancel keys for autovac workers, but
5145 * we'd better have something random in the field to prevent
5146 * unfriendly people from sending cancels to them.
5148 MyCancelKey = PostmasterRandom();
5149 bn->cancel_key = MyCancelKey;
5151 /* Autovac workers are not dead_end and need a child slot */
5152 bn->dead_end = false;
5153 bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
5154 bn->bgworker_notify = false;
5156 bn->pid = StartAutoVacWorker();
5159 bn->bkend_type = BACKEND_TYPE_AUTOVAC;
5160 dlist_push_head(&BackendList, &bn->elem);
5162 ShmemBackendArrayAdd(bn);
5169 * fork failed, fall through to report -- actual error message was
5170 * logged by StartAutoVacWorker
5172 (void) ReleasePostmasterChildSlot(bn->child_slot);
5177 (errcode(ERRCODE_OUT_OF_MEMORY),
5178 errmsg("out of memory")));
5182 * Report the failure to the launcher, if it's running. (If it's not, we
5183 * might not even be connected to shared memory, so don't try to call
5184 * AutoVacWorkerFailed.) Note that we also need to signal it so that it
5185 * responds to the condition, but we don't do that here, instead waiting
5186 * for ServerLoop to do it. This way we avoid a ping-pong signalling in
5187 * quick succession between the autovac launcher and postmaster in case
5190 if (AutoVacPID != 0)
5192 AutoVacWorkerFailed();
5193 avlauncher_needs_signal = true;
5198 * Create the opts file
5201 CreateOptsFile(int argc, char *argv[], char *fullprogname)
5206 #define OPTS_FILE "postmaster.opts"
5208 if ((fp = fopen(OPTS_FILE, "w")) == NULL)
5210 elog(LOG, "could not create file \"%s\": %m", OPTS_FILE);
5214 fprintf(fp, "%s", fullprogname);
5215 for (i = 1; i < argc; i++)
5216 fprintf(fp, " \"%s\"", argv[i]);
5221 elog(LOG, "could not write file \"%s\": %m", OPTS_FILE);
5230 * MaxLivePostmasterChildren
5232 * This reports the number of entries needed in per-child-process arrays
5233 * (the PMChildFlags array, and if EXEC_BACKEND the ShmemBackendArray).
5234 * These arrays include regular backends, autovac workers, walsenders
5235 * and background workers, but not special children nor dead_end children.
5236 * This allows the arrays to have a fixed maximum size, to wit the same
5237 * too-many-children limit enforced by canAcceptConnections(). The exact value
5238 * isn't too critical as long as it's more than MaxBackends.
5241 MaxLivePostmasterChildren(void)
5243 return 2 * (MaxConnections + autovacuum_max_workers + 1 +
5244 max_worker_processes);
5248 * Connect background worker to a database.
5251 BackgroundWorkerInitializeConnection(char *dbname, char *username)
5253 BackgroundWorker *worker = MyBgworkerEntry;
5255 /* XXX is this the right errcode? */
5256 if (!(worker->bgw_flags & BGWORKER_BACKEND_DATABASE_CONNECTION))
5258 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5259 errmsg("database connection requirement not indicated during registration")));
5261 InitPostgres(dbname, InvalidOid, username, NULL);
5263 /* it had better not gotten out of "init" mode yet */
5264 if (!IsInitProcessingMode())
5266 (errmsg("invalid processing mode in background worker")));
5267 SetProcessingMode(NormalProcessing);
5271 * Block/unblock signals in a background worker
5274 BackgroundWorkerBlockSignals(void)
5276 PG_SETMASK(&BlockSig);
5280 BackgroundWorkerUnblockSignals(void)
5282 PG_SETMASK(&UnBlockSig);
5287 bgworker_forkexec(int shmem_slot)
5291 char forkav[MAXPGPATH];
5293 snprintf(forkav, MAXPGPATH, "--forkbgworker=%d", shmem_slot);
5295 av[ac++] = "postgres";
5297 av[ac++] = NULL; /* filled in by postmaster_forkexec */
5300 Assert(ac < lengthof(av));
5302 return postmaster_forkexec(ac, av);
5307 * Start a new bgworker.
5308 * Starting time conditions must have been checked already.
5310 * This code is heavily based on autovacuum.c, q.v.
5313 do_start_bgworker(RegisteredBgWorker *rw)
5318 (errmsg("starting background worker process \"%s\"",
5319 rw->rw_worker.bgw_name)));
5322 switch ((worker_pid = bgworker_forkexec(rw->rw_shmem_slot)))
5324 switch ((worker_pid = fork_process()))
5329 (errmsg("could not fork worker process: %m")));
5332 #ifndef EXEC_BACKEND
5334 /* in postmaster child ... */
5335 /* Close the postmaster's sockets */
5336 ClosePostmasterPorts(false);
5338 /* Lose the postmaster's on-exit routines */
5341 /* Do NOT release postmaster's working memory context */
5343 MyBgworkerEntry = &rw->rw_worker;
5344 StartBackgroundWorker();
5348 rw->rw_pid = worker_pid;
5350 rw->rw_backend->pid = rw->rw_pid;
5351 ReportBackgroundWorkerPID(rw);
5356 * Does the current postmaster state require starting a worker with the
5357 * specified start_time?
5360 bgworker_should_start_now(BgWorkerStartTime start_time)
5364 case PM_NO_CHILDREN:
5365 case PM_WAIT_DEAD_END:
5368 case PM_WAIT_BACKENDS:
5369 case PM_WAIT_READONLY:
5370 case PM_WAIT_BACKUP:
5374 if (start_time == BgWorkerStart_RecoveryFinished)
5378 case PM_HOT_STANDBY:
5379 if (start_time == BgWorkerStart_ConsistentState)
5386 if (start_time == BgWorkerStart_PostmasterStart)
5396 * Allocate the Backend struct for a connected background worker, but don't
5397 * add it to the list of backends just yet.
5399 * Some info from the Backend is copied into the passed rw.
5402 assign_backendlist_entry(RegisteredBgWorker *rw)
5404 Backend *bn = malloc(sizeof(Backend));
5409 (errcode(ERRCODE_OUT_OF_MEMORY),
5410 errmsg("out of memory")));
5413 * The worker didn't really crash, but setting this nonzero makes
5414 * postmaster wait a bit before attempting to start it again; if it
5415 * tried again right away, most likely it'd find itself under the same
5418 rw->rw_crashed_at = GetCurrentTimestamp();
5423 * Compute the cancel key that will be assigned to this session. We
5424 * probably don't need cancel keys for background workers, but we'd better
5425 * have something random in the field to prevent unfriendly people from
5426 * sending cancels to them.
5428 MyCancelKey = PostmasterRandom();
5429 bn->cancel_key = MyCancelKey;
5431 bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
5432 bn->bkend_type = BACKEND_TYPE_BGWORKER;
5433 bn->dead_end = false;
5434 bn->bgworker_notify = false;
5436 rw->rw_backend = bn;
5437 rw->rw_child_slot = bn->child_slot;
5443 * If the time is right, start one background worker.
5445 * As a side effect, the bgworker control variables are set or reset whenever
5446 * there are more workers to start after this one, and whenever the overall
5447 * system state requires it.
5450 maybe_start_bgworker(void)
5452 slist_mutable_iter iter;
5453 TimestampTz now = 0;
5457 StartWorkerNeeded = false;
5458 HaveCrashedWorker = false;
5459 return; /* not yet */
5462 HaveCrashedWorker = false;
5464 slist_foreach_modify(iter, &BackgroundWorkerList)
5466 RegisteredBgWorker *rw;
5468 rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
5470 /* already running? */
5471 if (rw->rw_pid != 0)
5475 * If this worker has crashed previously, maybe it needs to be
5476 * restarted (unless on registration it specified it doesn't want to
5477 * be restarted at all). Check how long ago did a crash last happen.
5478 * If the last crash is too recent, don't start it right away; let it
5479 * be restarted once enough time has passed.
5481 if (rw->rw_crashed_at != 0)
5483 if (rw->rw_worker.bgw_restart_time == BGW_NEVER_RESTART)
5485 ForgetBackgroundWorker(&iter);
5490 now = GetCurrentTimestamp();
5492 if (!TimestampDifferenceExceeds(rw->rw_crashed_at, now,
5493 rw->rw_worker.bgw_restart_time * 1000))
5495 HaveCrashedWorker = true;
5500 if (bgworker_should_start_now(rw->rw_worker.bgw_start_time))
5502 /* reset crash time before calling assign_backendlist_entry */
5503 rw->rw_crashed_at = 0;
5506 * If necessary, allocate and assign the Backend element. Note we
5507 * must do this before forking, so that we can handle out of
5510 * If not connected, we don't need a Backend element, but we still
5511 * need a PMChildSlot.
5513 if (rw->rw_worker.bgw_flags & BGWORKER_BACKEND_DATABASE_CONNECTION)
5515 if (!assign_backendlist_entry(rw))
5519 rw->rw_child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
5521 do_start_bgworker(rw); /* sets rw->rw_pid */
5525 dlist_push_head(&BackendList, &rw->rw_backend->elem);
5527 ShmemBackendArrayAdd(rw->rw_backend);
5532 * Have ServerLoop call us again. Note that there might not
5533 * actually *be* another runnable worker, but we don't care all
5534 * that much; we will find out the next time we run.
5536 StartWorkerNeeded = true;
5541 /* no runnable worker found */
5542 StartWorkerNeeded = false;
5546 * When a backend asks to be notified about worker state changes, we
5547 * set a flag in its backend entry. The background worker machinery needs
5548 * to know when such backends exit.
5551 PostmasterMarkPIDForWorkerNotify(int pid)
5556 dlist_foreach(iter, &BackendList)
5558 bp = dlist_container(Backend, elem, iter.cur);
5561 bp->bgworker_notify = true;
5571 * The following need to be available to the save/restore_backend_variables
5572 * functions. They are marked NON_EXEC_STATIC in their home modules.
5574 extern slock_t *ShmemLock;
5575 extern LWLock *LWLockArray;
5576 extern slock_t *ProcStructLock;
5577 extern PGPROC *AuxiliaryProcs;
5578 extern PMSignalData *PMSignalState;
5579 extern pgsocket pgStatSock;
5580 extern pg_time_t first_syslogger_file_time;
5583 #define write_inheritable_socket(dest, src, childpid) ((*(dest) = (src)), true)
5584 #define read_inheritable_socket(dest, src) (*(dest) = *(src))
5586 static bool write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE child);
5587 static bool write_inheritable_socket(InheritableSocket *dest, SOCKET src,
5589 static void read_inheritable_socket(SOCKET *dest, InheritableSocket *src);
5593 /* Save critical backend variables into the BackendParameters struct */
5596 save_backend_variables(BackendParameters *param, Port *port)
5599 save_backend_variables(BackendParameters *param, Port *port,
5600 HANDLE childProcess, pid_t childPid)
5603 memcpy(¶m->port, port, sizeof(Port));
5604 if (!write_inheritable_socket(¶m->portsocket, port->sock, childPid))
5607 strlcpy(param->DataDir, DataDir, MAXPGPATH);
5609 memcpy(¶m->ListenSocket, &ListenSocket, sizeof(ListenSocket));
5611 param->MyCancelKey = MyCancelKey;
5612 param->MyPMChildSlot = MyPMChildSlot;
5614 param->UsedShmemSegID = UsedShmemSegID;
5615 param->UsedShmemSegAddr = UsedShmemSegAddr;
5617 param->ShmemLock = ShmemLock;
5618 param->ShmemVariableCache = ShmemVariableCache;
5619 param->ShmemBackendArray = ShmemBackendArray;
5621 param->LWLockArray = LWLockArray;
5622 param->ProcStructLock = ProcStructLock;
5623 param->ProcGlobal = ProcGlobal;
5624 param->AuxiliaryProcs = AuxiliaryProcs;
5625 param->PreparedXactProcs = PreparedXactProcs;
5626 param->PMSignalState = PMSignalState;
5627 if (!write_inheritable_socket(¶m->pgStatSock, pgStatSock, childPid))
5630 param->PostmasterPid = PostmasterPid;
5631 param->PgStartTime = PgStartTime;
5632 param->PgReloadTime = PgReloadTime;
5633 param->first_syslogger_file_time = first_syslogger_file_time;
5635 param->redirection_done = redirection_done;
5636 param->IsBinaryUpgrade = IsBinaryUpgrade;
5637 param->max_safe_fds = max_safe_fds;
5639 param->MaxBackends = MaxBackends;
5642 param->PostmasterHandle = PostmasterHandle;
5643 if (!write_duplicated_handle(¶m->initial_signal_pipe,
5644 pgwin32_create_signal_listener(childPid),
5648 memcpy(¶m->postmaster_alive_fds, &postmaster_alive_fds,
5649 sizeof(postmaster_alive_fds));
5652 memcpy(¶m->syslogPipe, &syslogPipe, sizeof(syslogPipe));
5654 strlcpy(param->my_exec_path, my_exec_path, MAXPGPATH);
5656 strlcpy(param->pkglib_path, pkglib_path, MAXPGPATH);
5658 strlcpy(param->ExtraOptions, ExtraOptions, MAXPGPATH);
5666 * Duplicate a handle for usage in a child process, and write the child
5667 * process instance of the handle to the parameter file.
5670 write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE childProcess)
5672 HANDLE hChild = INVALID_HANDLE_VALUE;
5674 if (!DuplicateHandle(GetCurrentProcess(),
5680 DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS))
5683 (errmsg_internal("could not duplicate handle to be written to backend parameter file: error code %lu",
5693 * Duplicate a socket for usage in a child process, and write the resulting
5694 * structure to the parameter file.
5695 * This is required because a number of LSPs (Layered Service Providers) very
5696 * common on Windows (antivirus, firewalls, download managers etc) break
5697 * straight socket inheritance.
5700 write_inheritable_socket(InheritableSocket *dest, SOCKET src, pid_t childpid)
5702 dest->origsocket = src;
5703 if (src != 0 && src != PGINVALID_SOCKET)
5706 if (WSADuplicateSocket(src, childpid, &dest->wsainfo) != 0)
5709 (errmsg("could not duplicate socket %d for use in backend: error code %d",
5710 (int) src, WSAGetLastError())));
5718 * Read a duplicate socket structure back, and get the socket descriptor.
5721 read_inheritable_socket(SOCKET *dest, InheritableSocket *src)
5725 if (src->origsocket == PGINVALID_SOCKET || src->origsocket == 0)
5727 /* Not a real socket! */
5728 *dest = src->origsocket;
5732 /* Actual socket, so create from structure */
5733 s = WSASocket(FROM_PROTOCOL_INFO,
5739 if (s == INVALID_SOCKET)
5741 write_stderr("could not create inherited socket: error code %d\n",
5748 * To make sure we don't get two references to the same socket, close
5749 * the original one. (This would happen when inheritance actually
5752 closesocket(src->origsocket);
5758 read_backend_variables(char *id, Port *port)
5760 BackendParameters param;
5763 /* Non-win32 implementation reads from file */
5767 fp = AllocateFile(id, PG_BINARY_R);
5770 write_stderr("could not read from backend variables file \"%s\": %s\n",
5771 id, strerror(errno));
5775 if (fread(¶m, sizeof(param), 1, fp) != 1)
5777 write_stderr("could not read from backend variables file \"%s\": %s\n",
5778 id, strerror(errno));
5784 if (unlink(id) != 0)
5786 write_stderr("could not remove file \"%s\": %s\n",
5787 id, strerror(errno));
5791 /* Win32 version uses mapped file */
5793 BackendParameters *paramp;
5796 paramHandle = (HANDLE) _atoi64(id);
5798 paramHandle = (HANDLE) atol(id);
5800 paramp = MapViewOfFile(paramHandle, FILE_MAP_READ, 0, 0, 0);
5803 write_stderr("could not map view of backend variables: error code %lu\n",
5808 memcpy(¶m, paramp, sizeof(BackendParameters));
5810 if (!UnmapViewOfFile(paramp))
5812 write_stderr("could not unmap view of backend variables: error code %lu\n",
5817 if (!CloseHandle(paramHandle))
5819 write_stderr("could not close handle to backend parameter variables: error code %lu\n",
5825 restore_backend_variables(¶m, port);
5828 /* Restore critical backend variables from the BackendParameters struct */
5830 restore_backend_variables(BackendParameters *param, Port *port)
5832 memcpy(port, ¶m->port, sizeof(Port));
5833 read_inheritable_socket(&port->sock, ¶m->portsocket);
5835 SetDataDir(param->DataDir);
5837 memcpy(&ListenSocket, ¶m->ListenSocket, sizeof(ListenSocket));
5839 MyCancelKey = param->MyCancelKey;
5840 MyPMChildSlot = param->MyPMChildSlot;
5842 UsedShmemSegID = param->UsedShmemSegID;
5843 UsedShmemSegAddr = param->UsedShmemSegAddr;
5845 ShmemLock = param->ShmemLock;
5846 ShmemVariableCache = param->ShmemVariableCache;
5847 ShmemBackendArray = param->ShmemBackendArray;
5849 LWLockArray = param->LWLockArray;
5850 ProcStructLock = param->ProcStructLock;
5851 ProcGlobal = param->ProcGlobal;
5852 AuxiliaryProcs = param->AuxiliaryProcs;
5853 PreparedXactProcs = param->PreparedXactProcs;
5854 PMSignalState = param->PMSignalState;
5855 read_inheritable_socket(&pgStatSock, ¶m->pgStatSock);
5857 PostmasterPid = param->PostmasterPid;
5858 PgStartTime = param->PgStartTime;
5859 PgReloadTime = param->PgReloadTime;
5860 first_syslogger_file_time = param->first_syslogger_file_time;
5862 redirection_done = param->redirection_done;
5863 IsBinaryUpgrade = param->IsBinaryUpgrade;
5864 max_safe_fds = param->max_safe_fds;
5866 MaxBackends = param->MaxBackends;
5869 PostmasterHandle = param->PostmasterHandle;
5870 pgwin32_initial_signal_pipe = param->initial_signal_pipe;
5872 memcpy(&postmaster_alive_fds, ¶m->postmaster_alive_fds,
5873 sizeof(postmaster_alive_fds));
5876 memcpy(&syslogPipe, ¶m->syslogPipe, sizeof(syslogPipe));
5878 strlcpy(my_exec_path, param->my_exec_path, MAXPGPATH);
5880 strlcpy(pkglib_path, param->pkglib_path, MAXPGPATH);
5882 strlcpy(ExtraOptions, param->ExtraOptions, MAXPGPATH);
5887 ShmemBackendArraySize(void)
5889 return mul_size(MaxLivePostmasterChildren(), sizeof(Backend));
5893 ShmemBackendArrayAllocation(void)
5895 Size size = ShmemBackendArraySize();
5897 ShmemBackendArray = (Backend *) ShmemAlloc(size);
5898 /* Mark all slots as empty */
5899 memset(ShmemBackendArray, 0, size);
5903 ShmemBackendArrayAdd(Backend *bn)
5905 /* The array slot corresponding to my PMChildSlot should be free */
5906 int i = bn->child_slot - 1;
5908 Assert(ShmemBackendArray[i].pid == 0);
5909 ShmemBackendArray[i] = *bn;
5913 ShmemBackendArrayRemove(Backend *bn)
5915 int i = bn->child_slot - 1;
5917 Assert(ShmemBackendArray[i].pid == bn->pid);
5918 /* Mark the slot as empty */
5919 ShmemBackendArray[i].pid = 0;
5921 #endif /* EXEC_BACKEND */
5927 * Subset implementation of waitpid() for Windows. We assume pid is -1
5928 * (that is, check all child processes) and options is WNOHANG (don't wait).
5931 waitpid(pid_t pid, int *exitstatus, int options)
5938 * Check if there are any dead children. If there are, return the pid of
5939 * the first one that died.
5941 if (GetQueuedCompletionStatus(win32ChildQueue, &dwd, &key, &ovl, 0))
5943 *exitstatus = (int) key;
5951 * Note! Code below executes on a thread pool! All operations must
5952 * be thread safe! Note that elog() and friends must *not* be used.
5955 pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
5957 win32_deadchild_waitinfo *childinfo = (win32_deadchild_waitinfo *) lpParameter;
5960 if (TimerOrWaitFired)
5961 return; /* timeout. Should never happen, since we use
5962 * INFINITE as timeout value. */
5965 * Remove handle from wait - required even though it's set to wait only
5968 UnregisterWaitEx(childinfo->waitHandle, NULL);
5970 if (!GetExitCodeProcess(childinfo->procHandle, &exitcode))
5973 * Should never happen. Inform user and set a fixed exitcode.
5975 write_stderr("could not read exit code for process\n");
5979 if (!PostQueuedCompletionStatus(win32ChildQueue, childinfo->procId, (ULONG_PTR) exitcode, NULL))
5980 write_stderr("could not post child completion status\n");
5983 * Handle is per-process, so we close it here instead of in the
5984 * originating thread
5986 CloseHandle(childinfo->procHandle);
5989 * Free struct that was allocated before the call to
5990 * RegisterWaitForSingleObject()
5994 /* Queue SIGCHLD signal */
5995 pg_queue_signal(SIGCHLD);
6000 * Initialize one and only handle for monitoring postmaster death.
6002 * Called once in the postmaster, so that child processes can subsequently
6003 * monitor if their parent is dead.
6006 InitPostmasterDeathWatchHandle(void)
6011 * Create a pipe. Postmaster holds the write end of the pipe open
6012 * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
6013 * the read file descriptor to select() to wake up in case postmaster
6014 * dies, or check for postmaster death with a (read() == 0). Children must
6015 * close the write end as soon as possible after forking, because EOF
6016 * won't be signaled in the read end until all processes have closed the
6017 * write fd. That is taken care of in ClosePostmasterPorts().
6019 Assert(MyProcPid == PostmasterPid);
6020 if (pipe(postmaster_alive_fds))
6022 (errcode_for_file_access(),
6023 errmsg_internal("could not create pipe to monitor postmaster death: %m")));
6026 * Set O_NONBLOCK to allow testing for the fd's presence with a read()
6029 if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK))
6031 (errcode_for_socket_access(),
6032 errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
6036 * On Windows, we use a process handle for the same purpose.
6038 if (DuplicateHandle(GetCurrentProcess(),
6039 GetCurrentProcess(),
6040 GetCurrentProcess(),
6044 DUPLICATE_SAME_ACCESS) == 0)
6046 (errmsg_internal("could not duplicate postmaster handle: error code %lu",