Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * postmaster.c
4 : : * This program acts as a clearing house for requests to the
5 : : * POSTGRES system. Frontend programs connect to the Postmaster,
6 : : * and postmaster forks a new backend process to handle the
7 : : * connection.
8 : : *
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.
14 : : *
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.
24 : : *
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
32 : : * clients.
33 : : *
34 : : *
35 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
36 : : * Portions Copyright (c) 1994, Regents of the University of California
37 : : *
38 : : *
39 : : * IDENTIFICATION
40 : : * src/backend/postmaster/postmaster.c
41 : : *
42 : : * NOTES
43 : : *
44 : : * Initialization:
45 : : * The Postmaster sets up shared memory data structures
46 : : * for the backends.
47 : : *
48 : : * Synchronization:
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.
53 : : *
54 : : * Garbage Collection:
55 : : * The Postmaster cleans up after backends if they have an emergency
56 : : * exit and/or core dump.
57 : : *
58 : : * Error Reporting:
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().
62 : : *
63 : : *-------------------------------------------------------------------------
64 : : */
65 : :
66 : : #include "postgres.h"
67 : :
68 : : #include <unistd.h>
69 : : #include <signal.h>
70 : : #include <time.h>
71 : : #include <sys/wait.h>
72 : : #include <ctype.h>
73 : : #include <sys/stat.h>
74 : : #include <sys/socket.h>
75 : : #include <fcntl.h>
76 : : #include <sys/param.h>
77 : : #include <netdb.h>
78 : : #include <limits.h>
79 : :
80 : : #ifdef USE_BONJOUR
81 : : #include <dns_sd.h>
82 : : #endif
83 : :
84 : : #ifdef USE_SYSTEMD
85 : : #include <systemd/sd-daemon.h>
86 : : #endif
87 : :
88 : : #ifdef HAVE_PTHREAD_IS_THREADED_NP
89 : : #include <pthread.h>
90 : : #endif
91 : :
92 : : #include "access/xlog.h"
93 : : #include "access/xlog_internal.h"
94 : : #include "access/xlogrecovery.h"
95 : : #include "common/file_perm.h"
96 : : #include "common/pg_prng.h"
97 : : #include "lib/ilist.h"
98 : : #include "libpq/libpq.h"
99 : : #include "libpq/pqsignal.h"
100 : : #include "pgstat.h"
101 : : #include "port/pg_bswap.h"
102 : : #include "port/pg_getopt_ctx.h"
103 : : #include "postmaster/autovacuum.h"
104 : : #include "postmaster/bgworker_internals.h"
105 : : #include "postmaster/pgarch.h"
106 : : #include "postmaster/postmaster.h"
107 : : #include "postmaster/syslogger.h"
108 : : #include "postmaster/walsummarizer.h"
109 : : #include "replication/logicallauncher.h"
110 : : #include "replication/slotsync.h"
111 : : #include "replication/walsender.h"
112 : : #include "storage/aio_subsys.h"
113 : : #include "storage/fd.h"
114 : : #include "storage/io_worker.h"
115 : : #include "storage/ipc.h"
116 : : #include "storage/pmsignal.h"
117 : : #include "storage/proc.h"
118 : : #include "storage/shmem_internal.h"
119 : : #include "tcop/backend_startup.h"
120 : : #include "tcop/tcopprot.h"
121 : : #include "utils/datetime.h"
122 : : #include "utils/memutils.h"
123 : : #include "utils/pidfile.h"
124 : : #include "utils/timestamp.h"
125 : : #include "utils/varlena.h"
126 : :
127 : : #ifdef EXEC_BACKEND
128 : : #include "common/file_utils.h"
129 : : #include "storage/pg_shmem.h"
130 : : #endif
131 : :
132 : :
133 : : /*
134 : : * CountChildren and SignalChildren take a bitmask argument to represent
135 : : * BackendTypes to count or signal. Define a separate type and functions to
136 : : * work with the bitmasks, to avoid accidentally passing a plain BackendType
137 : : * in place of a bitmask or vice versa.
138 : : */
139 : : typedef struct
140 : : {
141 : : uint32 mask;
142 : : } BackendTypeMask;
143 : :
144 : : StaticAssertDecl(BACKEND_NUM_TYPES < 32, "too many backend types for uint32");
145 : :
146 : : static const BackendTypeMask BTYPE_MASK_ALL = {(1 << BACKEND_NUM_TYPES) - 1};
147 : : static const BackendTypeMask BTYPE_MASK_NONE = {0};
148 : :
149 : : static inline BackendTypeMask
150 : 1850 : btmask(BackendType t)
151 : : {
152 : 1850 : BackendTypeMask mask = {.mask = 1 << t};
153 : :
154 : 1850 : return mask;
155 : : }
156 : :
157 : : static inline BackendTypeMask
158 : 18579 : btmask_add_n(BackendTypeMask mask, int nargs, BackendType *t)
159 : : {
160 [ + + ]: 81865 : for (int i = 0; i < nargs; i++)
161 : 63286 : mask.mask |= 1 << t[i];
162 : 18579 : return mask;
163 : : }
164 : :
165 : : #define btmask_add(mask, ...) \
166 : : btmask_add_n(mask, \
167 : : lengthof(((BackendType[]){__VA_ARGS__})), \
168 : : (BackendType[]){__VA_ARGS__} \
169 : : )
170 : :
171 : : static inline BackendTypeMask
172 : 5263 : btmask_del(BackendTypeMask mask, BackendType t)
173 : : {
174 : 5263 : mask.mask &= ~(1 << t);
175 : 5263 : return mask;
176 : : }
177 : :
178 : : static inline BackendTypeMask
179 : 3043 : btmask_all_except_n(int nargs, BackendType *t)
180 : : {
181 : 3043 : BackendTypeMask mask = BTYPE_MASK_ALL;
182 : :
183 [ + + ]: 8306 : for (int i = 0; i < nargs; i++)
184 : 5263 : mask = btmask_del(mask, t[i]);
185 : 3043 : return mask;
186 : : }
187 : :
188 : : #define btmask_all_except(...) \
189 : : btmask_all_except_n( \
190 : : lengthof(((BackendType[]){__VA_ARGS__})), \
191 : : (BackendType[]){__VA_ARGS__} \
192 : : )
193 : :
194 : : static inline bool
195 : 132021 : btmask_contains(BackendTypeMask mask, BackendType t)
196 : : {
197 : 132021 : return (mask.mask & (1 << t)) != 0;
198 : : }
199 : :
200 : :
201 : : BackgroundWorker *MyBgworkerEntry = NULL;
202 : :
203 : : /* The socket number we are listening for connections on */
204 : : int PostPortNumber = DEF_PGPORT;
205 : :
206 : : /* The directory names for Unix socket(s) */
207 : : char *Unix_socket_directories;
208 : :
209 : : /* The TCP listen address(es) */
210 : : char *ListenAddresses;
211 : :
212 : : /*
213 : : * SuperuserReservedConnections is the number of backends reserved for
214 : : * superuser use, and ReservedConnections is the number of backends reserved
215 : : * for use by roles with privileges of the pg_use_reserved_connections
216 : : * predefined role. These are taken out of the pool of MaxConnections backend
217 : : * slots, so the number of backend slots available for roles that are neither
218 : : * superuser nor have privileges of pg_use_reserved_connections is
219 : : * (MaxConnections - SuperuserReservedConnections - ReservedConnections).
220 : : *
221 : : * If the number of remaining slots is less than or equal to
222 : : * SuperuserReservedConnections, only superusers can make new connections. If
223 : : * the number of remaining slots is greater than SuperuserReservedConnections
224 : : * but less than or equal to
225 : : * (SuperuserReservedConnections + ReservedConnections), only superusers and
226 : : * roles with privileges of pg_use_reserved_connections can make new
227 : : * connections. Note that pre-existing superuser and
228 : : * pg_use_reserved_connections connections don't count against the limits.
229 : : */
230 : : int SuperuserReservedConnections;
231 : : int ReservedConnections;
232 : :
233 : : /* The socket(s) we're listening to. */
234 : : #define MAXLISTEN 64
235 : : static int NumListenSockets = 0;
236 : : static pgsocket *ListenSockets = NULL;
237 : :
238 : : /* still more option variables */
239 : : bool EnableSSL = false;
240 : :
241 : : int PreAuthDelay = 0;
242 : : int AuthenticationTimeout = 60;
243 : :
244 : : bool log_hostname; /* for ps display and logging */
245 : :
246 : : bool enable_bonjour = false;
247 : : char *bonjour_name;
248 : : bool restart_after_crash = true;
249 : : bool remove_temp_files_after_crash = true;
250 : :
251 : : /*
252 : : * When terminating child processes after fatal errors, like a crash of a
253 : : * child process, we normally send SIGQUIT -- and most other comments in this
254 : : * file are written on the assumption that we do -- but developers might
255 : : * prefer to use SIGABRT to collect per-child core dumps.
256 : : */
257 : : bool send_abort_for_crash = false;
258 : : bool send_abort_for_kill = false;
259 : :
260 : : /* special child processes; NULL when not running */
261 : : static PMChild *StartupPMChild = NULL,
262 : : *BgWriterPMChild = NULL,
263 : : *CheckpointerPMChild = NULL,
264 : : *WalWriterPMChild = NULL,
265 : : *WalReceiverPMChild = NULL,
266 : : *WalSummarizerPMChild = NULL,
267 : : *AutoVacLauncherPMChild = NULL,
268 : : *PgArchPMChild = NULL,
269 : : *SysLoggerPMChild = NULL,
270 : : *SlotSyncWorkerPMChild = NULL;
271 : :
272 : : /* Startup process's status */
273 : : typedef enum
274 : : {
275 : : STARTUP_NOT_RUNNING,
276 : : STARTUP_RUNNING,
277 : : STARTUP_SIGNALED, /* we sent it a SIGQUIT or SIGKILL */
278 : : STARTUP_CRASHED,
279 : : } StartupStatusEnum;
280 : :
281 : : static StartupStatusEnum StartupStatus = STARTUP_NOT_RUNNING;
282 : :
283 : : /* Startup/shutdown state */
284 : : #define NoShutdown 0
285 : : #define SmartShutdown 1
286 : : #define FastShutdown 2
287 : : #define ImmediateShutdown 3
288 : :
289 : : static int Shutdown = NoShutdown;
290 : :
291 : : static bool FatalError = false; /* T if recovering from backend crash */
292 : :
293 : : /*
294 : : * We use a simple state machine to control startup, shutdown, and
295 : : * crash recovery (which is rather like shutdown followed by startup).
296 : : *
297 : : * After doing all the postmaster initialization work, we enter PM_STARTUP
298 : : * state and the startup process is launched. The startup process begins by
299 : : * reading the control file and other preliminary initialization steps.
300 : : * In a normal startup, or after crash recovery, the startup process exits
301 : : * with exit code 0 and we switch to PM_RUN state. However, archive recovery
302 : : * is handled specially since it takes much longer and we would like to support
303 : : * hot standby during archive recovery.
304 : : *
305 : : * When the startup process is ready to start archive recovery, it signals the
306 : : * postmaster, and we switch to PM_RECOVERY state. The background writer and
307 : : * checkpointer are already running (as these are launched during PM_STARTUP),
308 : : * and the startup process continues applying WAL. If Hot Standby is enabled,
309 : : * then, after reaching a consistent point in WAL redo, startup process
310 : : * signals us again, and we switch to PM_HOT_STANDBY state and begin accepting
311 : : * connections to perform read-only queries. When archive recovery is
312 : : * finished, the startup process exits with exit code 0 and we switch to
313 : : * PM_RUN state.
314 : : *
315 : : * Normal child backends can only be launched when we are in PM_RUN or
316 : : * PM_HOT_STANDBY state. (connsAllowed can also restrict launching.)
317 : : * In other states we handle connection requests by launching "dead-end"
318 : : * child processes, which will simply send the client an error message and
319 : : * quit. (We track these in the ActiveChildList so that we can know when they
320 : : * are all gone; this is important because they're still connected to shared
321 : : * memory, and would interfere with an attempt to destroy the shmem segment,
322 : : * possibly leading to SHMALL failure when we try to make a new one.)
323 : : * In PM_WAIT_DEAD_END state we are waiting for all the dead-end children
324 : : * to drain out of the system, and therefore stop accepting connection
325 : : * requests at all until the last existing child has quit (which hopefully
326 : : * will not be very long).
327 : : *
328 : : * Notice that this state variable does not distinguish *why* we entered
329 : : * states later than PM_RUN --- Shutdown and FatalError must be consulted
330 : : * to find that out. FatalError is never true in PM_RECOVERY, PM_HOT_STANDBY,
331 : : * or PM_RUN states, nor in PM_WAIT_XLOG_SHUTDOWN states (because we don't
332 : : * enter those states when trying to recover from a crash). It can be true in
333 : : * PM_STARTUP state, because we don't clear it until we've successfully
334 : : * started WAL redo.
335 : : */
336 : : typedef enum
337 : : {
338 : : PM_INIT, /* postmaster starting */
339 : : PM_STARTUP, /* waiting for startup subprocess */
340 : : PM_RECOVERY, /* in archive recovery mode */
341 : : PM_HOT_STANDBY, /* in hot standby mode */
342 : : PM_RUN, /* normal "database is alive" state */
343 : : PM_STOP_BACKENDS, /* need to stop remaining backends */
344 : : PM_WAIT_BACKENDS, /* waiting for live backends to exit */
345 : : PM_WAIT_XLOG_SHUTDOWN, /* waiting for checkpointer to do shutdown
346 : : * ckpt */
347 : : PM_WAIT_XLOG_ARCHIVAL, /* waiting for archiver and walsenders to
348 : : * finish */
349 : : PM_WAIT_IO_WORKERS, /* waiting for io workers to exit */
350 : : PM_WAIT_CHECKPOINTER, /* waiting for checkpointer to shut down */
351 : : PM_WAIT_DEAD_END, /* waiting for dead-end children to exit */
352 : : PM_NO_CHILDREN, /* all important children have exited */
353 : : } PMState;
354 : :
355 : : static PMState pmState = PM_INIT;
356 : :
357 : : /*
358 : : * While performing a "smart shutdown", we restrict new connections but stay
359 : : * in PM_RUN or PM_HOT_STANDBY state until all the client backends are gone.
360 : : * connsAllowed is a sub-state indicator showing the active restriction.
361 : : * It is of no interest unless pmState is PM_RUN or PM_HOT_STANDBY.
362 : : */
363 : : static bool connsAllowed = true;
364 : :
365 : : /* Start time of SIGKILL timeout during immediate shutdown or child crash */
366 : : /* Zero means timeout is not running */
367 : : static time_t AbortStartTime = 0;
368 : :
369 : : /* Length of said timeout */
370 : : #define SIGKILL_CHILDREN_AFTER_SECS 5
371 : :
372 : : bool ClientAuthInProgress = false; /* T during new-client
373 : : * authentication */
374 : :
375 : : bool redirection_done = false; /* stderr redirected for syslogger? */
376 : :
377 : : /* received START_AUTOVAC_LAUNCHER signal */
378 : : static bool start_autovac_launcher = false;
379 : :
380 : : /* the launcher needs to be signaled to communicate some condition */
381 : : static bool avlauncher_needs_signal = false;
382 : :
383 : : /* received START_WALRECEIVER signal */
384 : : static bool WalReceiverRequested = false;
385 : :
386 : : /* set when there's a worker that needs to be started up */
387 : : static bool StartWorkerNeeded = true;
388 : : static bool HaveCrashedWorker = false;
389 : :
390 : : /* set when signals arrive */
391 : : static volatile sig_atomic_t pending_pm_pmsignal;
392 : : static volatile sig_atomic_t pending_pm_child_exit;
393 : : static volatile sig_atomic_t pending_pm_reload_request;
394 : : static volatile sig_atomic_t pending_pm_shutdown_request;
395 : : static volatile sig_atomic_t pending_pm_fast_shutdown_request;
396 : : static volatile sig_atomic_t pending_pm_immediate_shutdown_request;
397 : :
398 : : /* event multiplexing object */
399 : : static WaitEventSet *pm_wait_set;
400 : :
401 : : #ifdef USE_SSL
402 : : /* Set when and if SSL has been initialized properly */
403 : : bool LoadedSSL = false;
404 : : #endif
405 : :
406 : : #ifdef USE_BONJOUR
407 : : static DNSServiceRef bonjour_sdref = NULL;
408 : : #endif
409 : :
410 : : /* State for IO worker management. */
411 : : static TimestampTz io_worker_launch_next_time = 0;
412 : : static int io_worker_count = 0;
413 : : static PMChild *io_worker_children[MAX_IO_WORKERS];
414 : :
415 : : /*
416 : : * postmaster.c - function prototypes
417 : : */
418 : : static void CloseServerPorts(int status, Datum arg);
419 : : static void unlink_external_pid_file(int status, Datum arg);
420 : : static void getInstallationPaths(const char *argv0);
421 : : static void checkControlFile(void);
422 : : static void handle_pm_pmsignal_signal(SIGNAL_ARGS);
423 : : static void handle_pm_child_exit_signal(SIGNAL_ARGS);
424 : : static void handle_pm_reload_request_signal(SIGNAL_ARGS);
425 : : static void handle_pm_shutdown_request_signal(SIGNAL_ARGS);
426 : : static void process_pm_pmsignal(void);
427 : : static void process_pm_child_exit(void);
428 : : static void process_pm_reload_request(void);
429 : : static void process_pm_shutdown_request(void);
430 : : static void dummy_handler(SIGNAL_ARGS);
431 : : static void CleanupBackend(PMChild *bp, int exitstatus);
432 : : static void HandleChildCrash(int pid, int exitstatus, const char *procname);
433 : : static void HandleFatalError(QuitSignalReason reason, bool consider_sigabrt);
434 : : static void LogChildExit(int lev, const char *procname,
435 : : int pid, int exitstatus);
436 : : static void PostmasterStateMachine(void);
437 : : static void UpdatePMState(PMState newState);
438 : :
439 : : pg_noreturn static void ExitPostmaster(int status);
440 : : static int ServerLoop(void);
441 : : static int BackendStartup(ClientSocket *client_sock);
442 : : static void report_fork_failure_to_client(ClientSocket *client_sock, int errnum);
443 : : static CAC_state canAcceptConnections(BackendType backend_type);
444 : : static void signal_child(PMChild *pmchild, int signal);
445 : : static bool SignalChildren(int signal, BackendTypeMask targetMask);
446 : : static void TerminateChildren(int signal);
447 : : static int CountChildren(BackendTypeMask targetMask);
448 : : static void LaunchMissingBackgroundProcesses(void);
449 : : static void maybe_start_bgworkers(void);
450 : : static bool maybe_reap_io_worker(int pid);
451 : : static void maybe_start_io_workers(void);
452 : : static TimestampTz maybe_start_io_workers_scheduled_at(void);
453 : : static bool CreateOptsFile(int argc, char *argv[], char *fullprogname);
454 : : static PMChild *StartChildProcess(BackendType type);
455 : : static void StartSysLogger(void);
456 : : static void StartAutovacuumWorker(void);
457 : : static bool StartBackgroundWorker(RegisteredBgWorker *rw);
458 : : static void InitPostmasterDeathWatchHandle(void);
459 : :
460 : : #ifdef WIN32
461 : : #define WNOHANG 0 /* ignored, so any integer value will do */
462 : :
463 : : static pid_t waitpid(pid_t pid, int *exitstatus, int options);
464 : : static void WINAPI pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired);
465 : :
466 : : static HANDLE win32ChildQueue;
467 : :
468 : : typedef struct
469 : : {
470 : : HANDLE waitHandle;
471 : : HANDLE procHandle;
472 : : DWORD procId;
473 : : } win32_deadchild_waitinfo;
474 : : #endif /* WIN32 */
475 : :
476 : : /* Macros to check exit status of a child process */
477 : : #define EXIT_STATUS_0(st) ((st) == 0)
478 : : #define EXIT_STATUS_1(st) (WIFEXITED(st) && WEXITSTATUS(st) == 1)
479 : : #define EXIT_STATUS_3(st) (WIFEXITED(st) && WEXITSTATUS(st) == 3)
480 : :
481 : : #ifndef WIN32
482 : : /*
483 : : * File descriptors for pipe used to monitor if postmaster is alive.
484 : : * First is POSTMASTER_FD_WATCH, second is POSTMASTER_FD_OWN.
485 : : */
486 : : int postmaster_alive_fds[2] = {-1, -1};
487 : : #else
488 : : /* Process handle of postmaster used for the same purpose on Windows */
489 : : HANDLE PostmasterHandle;
490 : : #endif
491 : :
492 : : /*
493 : : * Postmaster main entry point
494 : : */
495 : : void
496 : 1070 : PostmasterMain(int argc, char *argv[])
497 : : {
498 : : pg_getopt_ctx optctx;
499 : : int opt;
500 : : int status;
501 : 1070 : char *userDoption = NULL;
502 : 1070 : bool listen_addr_saved = false;
503 : 1070 : char *output_config_variable = NULL;
504 : :
505 : 1070 : InitProcessGlobals();
506 : :
507 : 1070 : PostmasterPid = MyProcPid;
508 : :
509 : 1070 : IsPostmasterEnvironment = true;
510 : :
511 : : /*
512 : : * Start our win32 signal implementation
513 : : */
514 : : #ifdef WIN32
515 : : pgwin32_signal_initialize();
516 : : #endif
517 : :
518 : : /*
519 : : * We should not be creating any files or directories before we check the
520 : : * data directory (see checkDataDir()), but just in case set the umask to
521 : : * the most restrictive (owner-only) permissions.
522 : : *
523 : : * checkDataDir() will reset the umask based on the data directory
524 : : * permissions.
525 : : */
526 : 1070 : umask(PG_MODE_MASK_OWNER);
527 : :
528 : : /*
529 : : * By default, palloc() requests in the postmaster will be allocated in
530 : : * the PostmasterContext, which is space that can be recycled by backends.
531 : : * Allocated data that needs to be available to backends should be
532 : : * allocated in TopMemoryContext.
533 : : */
534 : 1070 : PostmasterContext = AllocSetContextCreate(TopMemoryContext,
535 : : "Postmaster",
536 : : ALLOCSET_DEFAULT_SIZES);
537 : 1070 : MemoryContextSwitchTo(PostmasterContext);
538 : :
539 : : /* Initialize paths to installation files */
540 : 1070 : getInstallationPaths(argv[0]);
541 : :
542 : : /*
543 : : * Set up signal handlers for the postmaster process.
544 : : *
545 : : * CAUTION: when changing this list, check for side-effects on the signal
546 : : * handling setup of child processes. See tcop/postgres.c,
547 : : * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/walwriter.c,
548 : : * postmaster/autovacuum.c, postmaster/pgarch.c, postmaster/syslogger.c,
549 : : * postmaster/bgworker.c and postmaster/checkpointer.c.
550 : : */
551 : 1070 : pqinitmask();
552 : 1070 : sigprocmask(SIG_SETMASK, &BlockSig, NULL);
553 : :
554 : 1070 : pqsignal(SIGHUP, handle_pm_reload_request_signal);
555 : 1070 : pqsignal(SIGINT, handle_pm_shutdown_request_signal);
556 : 1070 : pqsignal(SIGQUIT, handle_pm_shutdown_request_signal);
557 : 1070 : pqsignal(SIGTERM, handle_pm_shutdown_request_signal);
558 : 1070 : pqsignal(SIGALRM, PG_SIG_IGN); /* ignored */
559 : 1070 : pqsignal(SIGPIPE, PG_SIG_IGN); /* ignored */
560 : 1070 : pqsignal(SIGUSR1, handle_pm_pmsignal_signal);
561 : 1070 : pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
562 : 1070 : pqsignal(SIGCHLD, handle_pm_child_exit_signal);
563 : :
564 : : /* This may configure SIGURG, depending on platform. */
565 : 1070 : InitializeWaitEventSupport();
566 : 1070 : InitProcessLocalLatch();
567 : :
568 : : /*
569 : : * No other place in Postgres should touch SIGTTIN/SIGTTOU handling. We
570 : : * ignore those signals in a postmaster environment, so that there is no
571 : : * risk of a child process freezing up due to writing to stderr. But for
572 : : * a standalone backend, their default handling is reasonable. Hence, all
573 : : * child processes should just allow the inherited settings to stand.
574 : : */
575 : : #ifdef SIGTTIN
576 : 1070 : pqsignal(SIGTTIN, PG_SIG_IGN); /* ignored */
577 : : #endif
578 : : #ifdef SIGTTOU
579 : 1070 : pqsignal(SIGTTOU, PG_SIG_IGN); /* ignored */
580 : : #endif
581 : :
582 : : /* ignore SIGXFSZ, so that ulimit violations work like disk full */
583 : : #ifdef SIGXFSZ
584 : 1070 : pqsignal(SIGXFSZ, PG_SIG_IGN); /* ignored */
585 : : #endif
586 : :
587 : : /* Begin accepting signals. */
588 : 1070 : sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
589 : :
590 : : /*
591 : : * Options setup
592 : : */
593 : 1070 : InitializeGUCOptions();
594 : :
595 : : /*
596 : : * Parse command-line options. CAUTION: keep this in sync with
597 : : * tcop/postgres.c (the option sets should not conflict) and with the
598 : : * common help() function in main/main.c.
599 : : */
600 : 1070 : pg_getopt_start(&optctx, argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:OPp:r:S:sTt:W:-:");
601 : 1070 : optctx.opterr = 1;
602 [ + + ]: 3830 : while ((opt = pg_getopt_next(&optctx)) != -1)
603 : : {
604 [ - + + + : 2764 : switch (opt)
+ + - - -
+ - - - -
+ - - - -
+ - - - -
- - - ]
605 : : {
606 : 0 : case 'B':
607 : 0 : SetConfigOption("shared_buffers", optctx.optarg, PGC_POSTMASTER, PGC_S_ARGV);
608 : 0 : break;
609 : :
610 : 60 : case 'b':
611 : : /* Undocumented flag used for binary upgrades */
612 : 60 : IsBinaryUpgrade = true;
613 : 60 : break;
614 : :
615 : 5 : case 'C':
616 : 5 : output_config_variable = strdup(optctx.optarg);
617 : 5 : break;
618 : :
619 : 871 : case '-':
620 : :
621 : : /*
622 : : * Error if the user misplaced a special must-be-first option
623 : : * for dispatching to a subprogram. parse_dispatch_option()
624 : : * returns DISPATCH_POSTMASTER if it doesn't find a match, so
625 : : * error for anything else.
626 : : */
627 [ - + ]: 871 : if (parse_dispatch_option(optctx.optarg) != DISPATCH_POSTMASTER)
628 [ # # ]: 0 : ereport(ERROR,
629 : : (errcode(ERRCODE_SYNTAX_ERROR),
630 : : errmsg("--%s must be first argument", optctx.optarg)));
631 : :
632 : : pg_fallthrough;
633 : : case 'c':
634 : : {
635 : : char *name,
636 : : *value;
637 : :
638 : 1347 : ParseLongOption(optctx.optarg, &name, &value);
639 [ + + ]: 1347 : if (!value)
640 : : {
641 [ + - ]: 1 : if (opt == '-')
642 [ + - ]: 1 : ereport(ERROR,
643 : : (errcode(ERRCODE_SYNTAX_ERROR),
644 : : errmsg("--%s requires a value",
645 : : optctx.optarg)));
646 : : else
647 [ # # ]: 0 : ereport(ERROR,
648 : : (errcode(ERRCODE_SYNTAX_ERROR),
649 : : errmsg("-c %s requires a value",
650 : : optctx.optarg)));
651 : : }
652 : :
653 : 1346 : SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
654 : 1343 : pfree(name);
655 : 1343 : pfree(value);
656 : 1343 : break;
657 : : }
658 : :
659 : 1066 : case 'D':
660 : 1066 : userDoption = strdup(optctx.optarg);
661 : 1066 : break;
662 : :
663 : 0 : case 'd':
664 : 0 : set_debug_options(atoi(optctx.optarg), PGC_POSTMASTER, PGC_S_ARGV);
665 : 0 : break;
666 : :
667 : 0 : case 'E':
668 : 0 : SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
669 : 0 : break;
670 : :
671 : 0 : case 'e':
672 : 0 : SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
673 : 0 : break;
674 : :
675 : 107 : case 'F':
676 : 107 : SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
677 : 107 : break;
678 : :
679 : 0 : case 'f':
680 [ # # ]: 0 : if (!set_plan_disabling_options(optctx.optarg, PGC_POSTMASTER, PGC_S_ARGV))
681 : : {
682 : 0 : write_stderr("%s: invalid argument for option -f: \"%s\"\n",
683 : : progname, optctx.optarg);
684 : 0 : ExitPostmaster(1);
685 : : }
686 : 0 : break;
687 : :
688 : 0 : case 'h':
689 : 0 : SetConfigOption("listen_addresses", optctx.optarg, PGC_POSTMASTER, PGC_S_ARGV);
690 : 0 : break;
691 : :
692 : 0 : case 'i':
693 : 0 : SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
694 : 0 : break;
695 : :
696 : 0 : case 'j':
697 : : /* only used by interactive backend */
698 : 0 : break;
699 : :
700 : 107 : case 'k':
701 : 107 : SetConfigOption("unix_socket_directories", optctx.optarg, PGC_POSTMASTER, PGC_S_ARGV);
702 : 107 : break;
703 : :
704 : 0 : case 'l':
705 : 0 : SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
706 : 0 : break;
707 : :
708 : 0 : case 'N':
709 : 0 : SetConfigOption("max_connections", optctx.optarg, PGC_POSTMASTER, PGC_S_ARGV);
710 : 0 : break;
711 : :
712 : 0 : case 'O':
713 : 0 : SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
714 : 0 : break;
715 : :
716 : 0 : case 'P':
717 : 0 : SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
718 : 0 : break;
719 : :
720 : 72 : case 'p':
721 : 72 : SetConfigOption("port", optctx.optarg, PGC_POSTMASTER, PGC_S_ARGV);
722 : 72 : break;
723 : :
724 : 0 : case 'r':
725 : : /* only used by single-user backend */
726 : 0 : break;
727 : :
728 : 0 : case 'S':
729 : 0 : SetConfigOption("work_mem", optctx.optarg, PGC_POSTMASTER, PGC_S_ARGV);
730 : 0 : break;
731 : :
732 : 0 : case 's':
733 : 0 : SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
734 : 0 : break;
735 : :
736 : 0 : case 'T':
737 : :
738 : : /*
739 : : * This option used to be defined as sending SIGSTOP after a
740 : : * backend crash, but sending SIGABRT seems more useful.
741 : : */
742 : 0 : SetConfigOption("send_abort_for_crash", "true", PGC_POSTMASTER, PGC_S_ARGV);
743 : 0 : break;
744 : :
745 : 0 : case 't':
746 : : {
747 : 0 : const char *tmp = get_stats_option_name(optctx.optarg);
748 : :
749 [ # # ]: 0 : if (tmp)
750 : : {
751 : 0 : SetConfigOption(tmp, "true", PGC_POSTMASTER, PGC_S_ARGV);
752 : : }
753 : : else
754 : : {
755 : 0 : write_stderr("%s: invalid argument for option -t: \"%s\"\n",
756 : : progname, optctx.optarg);
757 : 0 : ExitPostmaster(1);
758 : : }
759 : 0 : break;
760 : : }
761 : :
762 : 0 : case 'W':
763 : 0 : SetConfigOption("post_auth_delay", optctx.optarg, PGC_POSTMASTER, PGC_S_ARGV);
764 : 0 : break;
765 : :
766 : 0 : default:
767 : 0 : write_stderr("Try \"%s --help\" for more information.\n",
768 : : progname);
769 : 0 : ExitPostmaster(1);
770 : : }
771 : : }
772 : :
773 : : /*
774 : : * Postmaster accepts no non-option switch arguments.
775 : : */
776 [ - + ]: 1066 : if (optctx.optind < argc)
777 : : {
778 : 0 : write_stderr("%s: invalid argument: \"%s\"\n",
779 : 0 : progname, argv[optctx.optind]);
780 : 0 : write_stderr("Try \"%s --help\" for more information.\n",
781 : : progname);
782 : 0 : ExitPostmaster(1);
783 : : }
784 : :
785 : : /*
786 : : * Locate the proper configuration files and data directory, and read
787 : : * postgresql.conf for the first time.
788 : : */
789 [ - + ]: 1066 : if (!SelectConfigFiles(userDoption, progname))
790 : 0 : ExitPostmaster(2);
791 : :
792 [ + + ]: 1066 : if (output_config_variable != NULL)
793 : : {
794 : : /*
795 : : * If this is a runtime-computed GUC, it hasn't yet been initialized,
796 : : * and the present value is not useful. However, this is a convenient
797 : : * place to print the value for most GUCs because it is safe to run
798 : : * postmaster startup to this point even if the server is already
799 : : * running. For the handful of runtime-computed GUCs that we cannot
800 : : * provide meaningful values for yet, we wait until later in
801 : : * postmaster startup to print the value. We won't be able to use -C
802 : : * on running servers for those GUCs, but using this option now would
803 : : * lead to incorrect results for them.
804 : : */
805 : 2 : int flags = GetConfigOptionFlags(output_config_variable, true);
806 : :
807 [ + + ]: 2 : if ((flags & GUC_RUNTIME_COMPUTED) == 0)
808 : : {
809 : : /*
810 : : * "-C guc" was specified, so print GUC's value and exit. No
811 : : * extra permission check is needed because the user is reading
812 : : * inside the data dir.
813 : : */
814 : 1 : const char *config_val = GetConfigOption(output_config_variable,
815 : : false, false);
816 : :
817 [ + - ]: 1 : puts(config_val ? config_val : "");
818 : 1 : ExitPostmaster(0);
819 : : }
820 : :
821 : : /*
822 : : * A runtime-computed GUC will be printed later on. As we initialize
823 : : * a server startup sequence, silence any log messages that may show
824 : : * up in the output generated. FATAL and more severe messages are
825 : : * useful to show, even if one would only expect at least PANIC. LOG
826 : : * entries are hidden.
827 : : */
828 : 1 : SetConfigOption("log_min_messages", "FATAL", PGC_SUSET,
829 : : PGC_S_OVERRIDE);
830 : : }
831 : :
832 : : /* Verify that DataDir looks reasonable */
833 : 1065 : checkDataDir();
834 : :
835 : : /* Check that pg_control exists */
836 : 1065 : checkControlFile();
837 : :
838 : : /* And switch working directory into it */
839 : 1065 : ChangeToDataDir();
840 : :
841 : : /*
842 : : * Check for invalid combinations of GUC settings.
843 : : */
844 [ - + ]: 1065 : if (SuperuserReservedConnections + ReservedConnections >= MaxConnections)
845 : : {
846 : 0 : write_stderr("%s: \"superuser_reserved_connections\" (%d) plus \"reserved_connections\" (%d) must be less than \"max_connections\" (%d)\n",
847 : : progname,
848 : : SuperuserReservedConnections, ReservedConnections,
849 : : MaxConnections);
850 : 0 : ExitPostmaster(1);
851 : : }
852 [ + + - + ]: 1065 : if (XLogArchiveMode > ARCHIVE_MODE_OFF && wal_level == WAL_LEVEL_MINIMAL)
853 [ # # ]: 0 : ereport(ERROR,
854 : : (errmsg("WAL archival cannot be enabled when \"wal_level\" is \"minimal\"")));
855 [ + + - + ]: 1065 : if (max_wal_senders > 0 && wal_level == WAL_LEVEL_MINIMAL)
856 [ # # ]: 0 : ereport(ERROR,
857 : : (errmsg("WAL streaming (\"max_wal_senders\" > 0) requires \"wal_level\" to be \"replica\" or \"logical\"")));
858 [ + + - + ]: 1065 : if (summarize_wal && wal_level == WAL_LEVEL_MINIMAL)
859 [ # # ]: 0 : ereport(ERROR,
860 : : (errmsg("WAL cannot be summarized when \"wal_level\" is \"minimal\"")));
861 [ + + - + ]: 1065 : if (sync_replication_slots && wal_level == WAL_LEVEL_MINIMAL)
862 [ # # ]: 0 : ereport(ERROR,
863 : : (errmsg("replication slot synchronization (\"sync_replication_slots\" = on) requires \"wal_level\" to be \"replica\" or \"logical\"")));
864 : :
865 : : /*
866 : : * Other one-time internal sanity checks can go here, if they are fast.
867 : : * (Put any slow processing further down, after postmaster.pid creation.)
868 : : */
869 [ - + ]: 1065 : if (!CheckDateTokenTables())
870 : : {
871 : 0 : write_stderr("%s: invalid datetoken tables, please fix\n", progname);
872 : 0 : ExitPostmaster(1);
873 : : }
874 : :
875 : : /* For debugging: display postmaster environment */
876 [ + + ]: 1065 : if (message_level_is_interesting(DEBUG3))
877 : : {
878 : : #if !defined(WIN32)
879 : : extern char **environ;
880 : : #endif
881 : : char **p;
882 : : StringInfoData si;
883 : :
884 : 7 : initStringInfo(&si);
885 : :
886 : 7 : appendStringInfoString(&si, "initial environment dump:");
887 [ + + ]: 296 : for (p = environ; *p; ++p)
888 : 289 : appendStringInfo(&si, "\n%s", *p);
889 : :
890 [ + - ]: 7 : ereport(DEBUG3, errmsg_internal("%s", si.data));
891 : 7 : pfree(si.data);
892 : : }
893 : :
894 : : /*
895 : : * Create lockfile for data directory.
896 : : *
897 : : * We want to do this before we try to grab the input sockets, because the
898 : : * data directory interlock is more reliable than the socket-file
899 : : * interlock (thanks to whoever decided to put socket files in /tmp :-().
900 : : * For the same reason, it's best to grab the TCP socket(s) before the
901 : : * Unix socket(s).
902 : : *
903 : : * Also note that this internally sets up the on_proc_exit function that
904 : : * is responsible for removing both data directory and socket lockfiles;
905 : : * so it must happen before opening sockets so that at exit, the socket
906 : : * lockfiles go away after CloseServerPorts runs.
907 : : */
908 : 1065 : CreateDataDirLockFile(true);
909 : :
910 : : /*
911 : : * Read the control file (for error checking and config info).
912 : : *
913 : : * Since we verify the control file's CRC, this has a useful side effect
914 : : * on machines where we need a run-time test for CRC support instructions.
915 : : * The postmaster will do the test once at startup, and then its child
916 : : * processes will inherit the correct function pointer and not need to
917 : : * repeat the test.
918 : : */
919 : 1062 : LocalProcessControlFile(false);
920 : :
921 : : /*
922 : : * Register the apply launcher. It's probably a good idea to call this
923 : : * before any modules had a chance to take the background worker slots.
924 : : */
925 : 1062 : ApplyLauncherRegister();
926 : :
927 : : /*
928 : : * Register the shared memory needs of all core subsystems.
929 : : */
930 : 1062 : RegisterBuiltinShmemCallbacks();
931 : :
932 : : /*
933 : : * process any libraries that should be preloaded at postmaster start
934 : : */
935 : 1062 : process_shared_preload_libraries();
936 : :
937 : : /*
938 : : * Initialize SSL library, if specified.
939 : : */
940 : : #ifdef USE_SSL
941 [ + + ]: 1062 : if (EnableSSL)
942 : : {
943 : 51 : (void) secure_initialize(true);
944 : 38 : LoadedSSL = true;
945 : : }
946 : : #endif
947 : :
948 : : /*
949 : : * Now that loadable modules have had their chance to alter any GUCs,
950 : : * calculate MaxBackends and initialize the machinery to track child
951 : : * processes.
952 : : */
953 : 1049 : InitializeMaxBackends();
954 : 1049 : InitPostmasterChildSlots();
955 : :
956 : : /*
957 : : * Calculate the size of the PGPROC fast-path lock arrays.
958 : : */
959 : 1049 : InitializeFastPathLocks();
960 : :
961 : : /*
962 : : * Also call any legacy shmem request hooks that might've been installed
963 : : * by preloaded libraries.
964 : : *
965 : : * Note: this must be done before ShmemCallRequestCallbacks(), because the
966 : : * hooks may request LWLocks with RequestNamedLWLockTranche(), which in
967 : : * turn affects the size of the LWLock array calculated in lwlock.c.
968 : : */
969 : 1049 : process_shmem_requests();
970 : :
971 : : /*
972 : : * Ask all subsystems, including preloaded libraries, to register their
973 : : * shared memory needs.
974 : : */
975 : 1049 : ShmemCallRequestCallbacks();
976 : :
977 : : /*
978 : : * Now that loadable modules have had their chance to request additional
979 : : * shared memory, determine the value of any runtime-computed GUCs that
980 : : * depend on the amount of shared memory required.
981 : : */
982 : 1049 : InitializeShmemGUCs();
983 : :
984 : : /*
985 : : * Now that modules have been loaded, we can process any custom resource
986 : : * managers specified in the wal_consistency_checking GUC.
987 : : */
988 : 1049 : InitializeWalConsistencyChecking();
989 : :
990 : : /*
991 : : * If -C was specified with a runtime-computed GUC, we held off printing
992 : : * the value earlier, as the GUC was not yet initialized. We handle -C
993 : : * for most GUCs before we lock the data directory so that the option may
994 : : * be used on a running server. However, a handful of GUCs are runtime-
995 : : * computed and do not have meaningful values until after locking the data
996 : : * directory, and we cannot safely calculate their values earlier on a
997 : : * running server. At this point, such GUCs should be properly
998 : : * initialized, and we haven't yet set up shared memory, so this is a good
999 : : * time to handle the -C option for these special GUCs.
1000 : : */
1001 [ + + ]: 1049 : if (output_config_variable != NULL)
1002 : : {
1003 : 1 : const char *config_val = GetConfigOption(output_config_variable,
1004 : : false, false);
1005 : :
1006 [ + - ]: 1 : puts(config_val ? config_val : "");
1007 : 1 : ExitPostmaster(0);
1008 : : }
1009 : :
1010 : : /*
1011 : : * Set up shared memory and semaphores.
1012 : : *
1013 : : * Note: if using SysV shmem and/or semas, each postmaster startup will
1014 : : * normally choose the same IPC keys. This helps ensure that we will
1015 : : * clean up dead IPC objects if the postmaster crashes and is restarted.
1016 : : */
1017 : 1048 : CreateSharedMemoryAndSemaphores();
1018 : :
1019 : : /*
1020 : : * Estimate number of openable files. This must happen after setting up
1021 : : * semaphores, because on some platforms semaphores count as open files.
1022 : : */
1023 : 1047 : set_max_safe_fds();
1024 : :
1025 : : /*
1026 : : * Initialize pipe (or process handle on Windows) that allows children to
1027 : : * wake up from sleep on postmaster death.
1028 : : */
1029 : 1047 : InitPostmasterDeathWatchHandle();
1030 : :
1031 : : #ifdef WIN32
1032 : :
1033 : : /*
1034 : : * Initialize I/O completion port used to deliver list of dead children.
1035 : : */
1036 : : win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
1037 : : if (win32ChildQueue == NULL)
1038 : : ereport(FATAL,
1039 : : (errmsg("could not create I/O completion port for child queue")));
1040 : : #endif
1041 : :
1042 : : #ifdef EXEC_BACKEND
1043 : : /* Write out nondefault GUC settings for child processes to use */
1044 : : write_nondefault_variables(PGC_POSTMASTER);
1045 : :
1046 : : /*
1047 : : * Clean out the temp directory used to transmit parameters to child
1048 : : * processes (see internal_forkexec). We must do this before launching
1049 : : * any child processes, else we have a race condition: we could remove a
1050 : : * parameter file before the child can read it. It should be safe to do
1051 : : * so now, because we verified earlier that there are no conflicting
1052 : : * Postgres processes in this data directory.
1053 : : */
1054 : : RemovePgTempFilesInDir(PG_TEMP_FILES_DIR, true, false);
1055 : : #endif
1056 : :
1057 : : /*
1058 : : * Forcibly remove the files signaling a standby promotion request.
1059 : : * Otherwise, the existence of those files triggers a promotion too early,
1060 : : * whether a user wants that or not.
1061 : : *
1062 : : * This removal of files is usually unnecessary because they can exist
1063 : : * only during a few moments during a standby promotion. However there is
1064 : : * a race condition: if pg_ctl promote is executed and creates the files
1065 : : * during a promotion, the files can stay around even after the server is
1066 : : * brought up to be the primary. Then, if a new standby starts by using
1067 : : * the backup taken from the new primary, the files can exist at server
1068 : : * startup and must be removed in order to avoid an unexpected promotion.
1069 : : *
1070 : : * Note that promotion signal files need to be removed before the startup
1071 : : * process is invoked. Because, after that, they can be used by
1072 : : * postmaster's SIGUSR1 signal handler.
1073 : : */
1074 : 1047 : RemovePromoteSignalFiles();
1075 : :
1076 : : /* Do the same for logrotate signal file */
1077 : 1047 : RemoveLogrotateSignalFiles();
1078 : :
1079 : : /* Remove any outdated file holding the current log filenames. */
1080 [ + - - + ]: 1047 : if (unlink(LOG_METAINFO_DATAFILE) < 0 && errno != ENOENT)
1081 [ # # ]: 0 : ereport(LOG,
1082 : : (errcode_for_file_access(),
1083 : : errmsg("could not remove file \"%s\": %m",
1084 : : LOG_METAINFO_DATAFILE)));
1085 : :
1086 : : /*
1087 : : * If enabled, start up syslogger collection subprocess
1088 : : */
1089 [ + + ]: 1047 : if (Logging_collector)
1090 : 1 : StartSysLogger();
1091 : :
1092 : : /*
1093 : : * Reset whereToSendOutput from DestDebug (its starting state) to
1094 : : * DestNone. This stops ereport from sending log messages to stderr unless
1095 : : * Log_destination permits. We don't do this until the postmaster is
1096 : : * fully launched, since startup failures may as well be reported to
1097 : : * stderr.
1098 : : *
1099 : : * If we are in fact disabling logging to stderr, first emit a log message
1100 : : * saying so, to provide a breadcrumb trail for users who may not remember
1101 : : * that their logging is configured to go somewhere else.
1102 : : */
1103 [ - + ]: 1047 : if (!(Log_destination & LOG_DESTINATION_STDERR))
1104 [ # # ]: 0 : ereport(LOG,
1105 : : (errmsg("ending log output to stderr"),
1106 : : errhint("Future log output will go to log destination \"%s\".",
1107 : : Log_destination_string)));
1108 : :
1109 : 1047 : whereToSendOutput = DestNone;
1110 : :
1111 : : /*
1112 : : * Report server startup in log. While we could emit this much earlier,
1113 : : * it seems best to do so after starting the log collector, if we intend
1114 : : * to use one.
1115 : : */
1116 [ + - ]: 1047 : ereport(LOG,
1117 : : (errmsg("starting %s", PG_VERSION_STR)));
1118 : :
1119 : : /*
1120 : : * Establish input sockets.
1121 : : *
1122 : : * First set up an on_proc_exit function that's charged with closing the
1123 : : * sockets again at postmaster shutdown.
1124 : : */
1125 : 1047 : ListenSockets = palloc_array(pgsocket, MAXLISTEN);
1126 : 1047 : on_proc_exit(CloseServerPorts, 0);
1127 : :
1128 [ + - ]: 1047 : if (ListenAddresses)
1129 : : {
1130 : : char *rawstring;
1131 : : List *elemlist;
1132 : : ListCell *l;
1133 : 1047 : int success = 0;
1134 : :
1135 : : /* Need a modifiable copy of ListenAddresses */
1136 : 1047 : rawstring = pstrdup(ListenAddresses);
1137 : :
1138 : : /* Parse string into list of hostnames */
1139 [ - + ]: 1047 : if (!SplitGUCList(rawstring, ',', &elemlist))
1140 : : {
1141 : : /* syntax error in list */
1142 [ # # ]: 0 : ereport(FATAL,
1143 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1144 : : errmsg("invalid list syntax in parameter \"%s\"",
1145 : : "listen_addresses")));
1146 : : }
1147 : :
1148 [ + + + + : 1088 : foreach(l, elemlist)
+ + ]
1149 : : {
1150 : 41 : char *curhost = (char *) lfirst(l);
1151 : :
1152 [ - + ]: 41 : if (strcmp(curhost, "*") == 0)
1153 : 0 : status = ListenServerPort(AF_UNSPEC, NULL,
1154 : 0 : (unsigned short) PostPortNumber,
1155 : : NULL,
1156 : : ListenSockets,
1157 : : &NumListenSockets,
1158 : : MAXLISTEN);
1159 : : else
1160 : 41 : status = ListenServerPort(AF_UNSPEC, curhost,
1161 : 41 : (unsigned short) PostPortNumber,
1162 : : NULL,
1163 : : ListenSockets,
1164 : : &NumListenSockets,
1165 : : MAXLISTEN);
1166 : :
1167 [ + - ]: 41 : if (status == STATUS_OK)
1168 : : {
1169 : 41 : success++;
1170 : : /* record the first successful host addr in lockfile */
1171 [ + - ]: 41 : if (!listen_addr_saved)
1172 : : {
1173 : 41 : AddToDataDirLockFile(LOCK_FILE_LINE_LISTEN_ADDR, curhost);
1174 : 41 : listen_addr_saved = true;
1175 : : }
1176 : : }
1177 : : else
1178 [ # # ]: 0 : ereport(WARNING,
1179 : : (errmsg("could not create listen socket for \"%s\"",
1180 : : curhost)));
1181 : : }
1182 : :
1183 [ + + - + ]: 1047 : if (!success && elemlist != NIL)
1184 [ # # ]: 0 : ereport(FATAL,
1185 : : (errmsg("could not create any TCP/IP sockets")));
1186 : :
1187 : 1047 : list_free(elemlist);
1188 : 1047 : pfree(rawstring);
1189 : : }
1190 : :
1191 : : #ifdef USE_BONJOUR
1192 : : /* Register for Bonjour only if we opened TCP socket(s) */
1193 : : if (enable_bonjour && NumListenSockets > 0)
1194 : : {
1195 : : DNSServiceErrorType err;
1196 : :
1197 : : /*
1198 : : * We pass 0 for interface_index, which will result in registering on
1199 : : * all "applicable" interfaces. It's not entirely clear from the
1200 : : * DNS-SD docs whether this would be appropriate if we have bound to
1201 : : * just a subset of the available network interfaces.
1202 : : */
1203 : : err = DNSServiceRegister(&bonjour_sdref,
1204 : : 0,
1205 : : 0,
1206 : : bonjour_name,
1207 : : "_postgresql._tcp.",
1208 : : NULL,
1209 : : NULL,
1210 : : pg_hton16(PostPortNumber),
1211 : : 0,
1212 : : NULL,
1213 : : NULL,
1214 : : NULL);
1215 : : if (err != kDNSServiceErr_NoError)
1216 : : ereport(LOG,
1217 : : (errmsg("DNSServiceRegister() failed: error code %ld",
1218 : : (long) err)));
1219 : :
1220 : : /*
1221 : : * We don't bother to read the mDNS daemon's reply, and we expect that
1222 : : * it will automatically terminate our registration when the socket is
1223 : : * closed at postmaster termination. So there's nothing more to be
1224 : : * done here. However, the bonjour_sdref is kept around so that
1225 : : * forked children can close their copies of the socket.
1226 : : */
1227 : : }
1228 : : #endif
1229 : :
1230 [ + - ]: 1047 : if (Unix_socket_directories)
1231 : : {
1232 : : char *rawstring;
1233 : : List *elemlist;
1234 : : ListCell *l;
1235 : 1047 : int success = 0;
1236 : :
1237 : : /* Need a modifiable copy of Unix_socket_directories */
1238 : 1047 : rawstring = pstrdup(Unix_socket_directories);
1239 : :
1240 : : /* Parse string into list of directories */
1241 [ - + ]: 1047 : if (!SplitDirectoriesString(rawstring, ',', &elemlist))
1242 : : {
1243 : : /* syntax error in list */
1244 [ # # ]: 0 : ereport(FATAL,
1245 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1246 : : errmsg("invalid list syntax in parameter \"%s\"",
1247 : : "unix_socket_directories")));
1248 : : }
1249 : :
1250 [ + + + + : 2093 : foreach(l, elemlist)
+ + ]
1251 : : {
1252 : 1046 : char *socketdir = (char *) lfirst(l);
1253 : :
1254 : 1046 : status = ListenServerPort(AF_UNIX, NULL,
1255 : 1046 : (unsigned short) PostPortNumber,
1256 : : socketdir,
1257 : : ListenSockets,
1258 : : &NumListenSockets,
1259 : : MAXLISTEN);
1260 : :
1261 [ + - ]: 1046 : if (status == STATUS_OK)
1262 : : {
1263 : 1046 : success++;
1264 : : /* record the first successful Unix socket in lockfile */
1265 [ + - ]: 1046 : if (success == 1)
1266 : 1046 : AddToDataDirLockFile(LOCK_FILE_LINE_SOCKET_DIR, socketdir);
1267 : : }
1268 : : else
1269 [ # # ]: 0 : ereport(WARNING,
1270 : : (errmsg("could not create Unix-domain socket in directory \"%s\"",
1271 : : socketdir)));
1272 : : }
1273 : :
1274 [ + + - + ]: 1047 : if (!success && elemlist != NIL)
1275 [ # # ]: 0 : ereport(FATAL,
1276 : : (errmsg("could not create any Unix-domain sockets")));
1277 : :
1278 : 1047 : list_free_deep(elemlist);
1279 : 1047 : pfree(rawstring);
1280 : : }
1281 : :
1282 : : /*
1283 : : * check that we have some socket to listen on
1284 : : */
1285 [ - + ]: 1047 : if (NumListenSockets == 0)
1286 [ # # ]: 0 : ereport(FATAL,
1287 : : (errmsg("no socket created for listening")));
1288 : :
1289 : : /*
1290 : : * If no valid TCP ports, write an empty line for listen address,
1291 : : * indicating the Unix socket must be used. Note that this line is not
1292 : : * added to the lock file until there is a socket backing it.
1293 : : */
1294 [ + + ]: 1047 : if (!listen_addr_saved)
1295 : 1006 : AddToDataDirLockFile(LOCK_FILE_LINE_LISTEN_ADDR, "");
1296 : :
1297 : : /*
1298 : : * Record postmaster options. We delay this till now to avoid recording
1299 : : * bogus options (eg, unusable port number).
1300 : : */
1301 [ - + ]: 1047 : if (!CreateOptsFile(argc, argv, my_exec_path))
1302 : 0 : ExitPostmaster(1);
1303 : :
1304 : : /*
1305 : : * Write the external PID file if requested
1306 : : */
1307 [ - + ]: 1047 : if (external_pid_file)
1308 : : {
1309 : 0 : FILE *fpidfile = fopen(external_pid_file, "w");
1310 : :
1311 [ # # ]: 0 : if (fpidfile)
1312 : : {
1313 : 0 : fprintf(fpidfile, "%d\n", MyProcPid);
1314 : 0 : fclose(fpidfile);
1315 : :
1316 : : /* Make PID file world readable */
1317 [ # # ]: 0 : if (chmod(external_pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) != 0)
1318 : 0 : write_stderr("%s: could not change permissions of external PID file \"%s\": %m\n",
1319 : : progname, external_pid_file);
1320 : : }
1321 : : else
1322 : 0 : write_stderr("%s: could not write external PID file \"%s\": %m\n",
1323 : : progname, external_pid_file);
1324 : :
1325 : 0 : on_proc_exit(unlink_external_pid_file, 0);
1326 : : }
1327 : :
1328 : : /*
1329 : : * Remove old temporary files. At this point there can be no other
1330 : : * Postgres processes running in this directory, so this should be safe.
1331 : : */
1332 : 1047 : RemovePgTempFiles();
1333 : :
1334 : : /*
1335 : : * Initialize the autovacuum subsystem (again, no process start yet)
1336 : : */
1337 : 1047 : autovac_init();
1338 : :
1339 : : /*
1340 : : * Load configuration files for client authentication.
1341 : : */
1342 [ - + ]: 1047 : if (!load_hba())
1343 : : {
1344 : : /*
1345 : : * It makes no sense to continue if we fail to load the HBA file,
1346 : : * since there is no way to connect to the database in this case.
1347 : : */
1348 [ # # ]: 0 : ereport(FATAL,
1349 : : /* translator: %s is a configuration file */
1350 : : (errmsg("could not load %s", HbaFileName)));
1351 : : }
1352 : 1047 : if (!load_ident())
1353 : : {
1354 : : /*
1355 : : * We can start up without the IDENT file, although it means that you
1356 : : * cannot log in using any of the authentication methods that need a
1357 : : * user name mapping. load_ident() already logged the details of error
1358 : : * to the log.
1359 : : */
1360 : : }
1361 : :
1362 : : #ifdef HAVE_PTHREAD_IS_THREADED_NP
1363 : :
1364 : : /*
1365 : : * On macOS, libintl replaces setlocale() with a version that calls
1366 : : * CFLocaleCopyCurrent() when its second argument is "" and every relevant
1367 : : * environment variable is unset or empty. CFLocaleCopyCurrent() makes
1368 : : * the process multithreaded. The postmaster calls sigprocmask() and
1369 : : * calls fork() without an immediate exec(), both of which have undefined
1370 : : * behavior in a multithreaded program. A multithreaded postmaster is the
1371 : : * normal case on Windows, which offers neither fork() nor sigprocmask().
1372 : : * Currently, macOS is the only platform having pthread_is_threaded_np(),
1373 : : * so we need not worry whether this HINT is appropriate elsewhere.
1374 : : */
1375 : : if (pthread_is_threaded_np() != 0)
1376 : : ereport(FATAL,
1377 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1378 : : errmsg("postmaster became multithreaded during startup"),
1379 : : errhint("Set the LC_ALL environment variable to a valid locale.")));
1380 : : #endif
1381 : :
1382 : : /*
1383 : : * Remember postmaster startup time
1384 : : */
1385 : 1047 : PgStartTime = GetCurrentTimestamp();
1386 : :
1387 : : /*
1388 : : * Report postmaster status in the postmaster.pid file, to allow pg_ctl to
1389 : : * see what's happening.
1390 : : */
1391 : 1047 : AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_STARTING);
1392 : :
1393 : 1047 : UpdatePMState(PM_STARTUP);
1394 : :
1395 : : /* Make sure we can perform I/O while starting up. */
1396 : 1047 : maybe_start_io_workers();
1397 : :
1398 : : /* Start bgwriter and checkpointer so they can help with recovery */
1399 [ + - ]: 1047 : if (CheckpointerPMChild == NULL)
1400 : 1047 : CheckpointerPMChild = StartChildProcess(B_CHECKPOINTER);
1401 [ + - ]: 1047 : if (BgWriterPMChild == NULL)
1402 : 1047 : BgWriterPMChild = StartChildProcess(B_BG_WRITER);
1403 : :
1404 : : /*
1405 : : * We're ready to rock and roll...
1406 : : */
1407 : 1047 : StartupPMChild = StartChildProcess(B_STARTUP);
1408 : : Assert(StartupPMChild != NULL);
1409 : 1047 : StartupStatus = STARTUP_RUNNING;
1410 : :
1411 : : /* Some workers may be scheduled to start now */
1412 : 1047 : maybe_start_bgworkers();
1413 : :
1414 : 1047 : status = ServerLoop();
1415 : :
1416 : : /*
1417 : : * ServerLoop probably shouldn't ever return, but if it does, close down.
1418 : : */
1419 : 0 : ExitPostmaster(status != STATUS_OK);
1420 : :
1421 : : abort(); /* not reached */
1422 : : }
1423 : :
1424 : :
1425 : : /*
1426 : : * on_proc_exit callback to close server's listen sockets
1427 : : */
1428 : : static void
1429 : 1047 : CloseServerPorts(int status, Datum arg)
1430 : : {
1431 : : int i;
1432 : :
1433 : : /*
1434 : : * First, explicitly close all the socket FDs. We used to just let this
1435 : : * happen implicitly at postmaster exit, but it's better to close them
1436 : : * before we remove the postmaster.pid lockfile; otherwise there's a race
1437 : : * condition if a new postmaster wants to re-use the TCP port number.
1438 : : */
1439 [ + + ]: 2135 : for (i = 0; i < NumListenSockets; i++)
1440 : : {
1441 [ - + ]: 1088 : if (closesocket(ListenSockets[i]) != 0)
1442 [ # # ]: 0 : elog(LOG, "could not close listen socket: %m");
1443 : : }
1444 : 1047 : NumListenSockets = 0;
1445 : :
1446 : : /*
1447 : : * Next, remove any filesystem entries for Unix sockets. To avoid race
1448 : : * conditions against incoming postmasters, this must happen after closing
1449 : : * the sockets and before removing lock files.
1450 : : */
1451 : 1047 : RemoveSocketFiles();
1452 : :
1453 : : /*
1454 : : * We don't do anything about socket lock files here; those will be
1455 : : * removed in a later on_proc_exit callback.
1456 : : */
1457 : 1047 : }
1458 : :
1459 : : /*
1460 : : * on_proc_exit callback to delete external_pid_file
1461 : : */
1462 : : static void
1463 : 0 : unlink_external_pid_file(int status, Datum arg)
1464 : : {
1465 [ # # ]: 0 : if (external_pid_file)
1466 : 0 : unlink(external_pid_file);
1467 : 0 : }
1468 : :
1469 : :
1470 : : /*
1471 : : * Compute and check the directory paths to files that are part of the
1472 : : * installation (as deduced from the postgres executable's own location)
1473 : : */
1474 : : static void
1475 : 1070 : getInstallationPaths(const char *argv0)
1476 : : {
1477 : : DIR *pdir;
1478 : :
1479 : : /* Locate the postgres executable itself */
1480 [ - + ]: 1070 : if (find_my_exec(argv0, my_exec_path) < 0)
1481 [ # # ]: 0 : ereport(FATAL,
1482 : : (errmsg("%s: could not locate my own executable path", argv0)));
1483 : :
1484 : : #ifdef EXEC_BACKEND
1485 : : /* Locate executable backend before we change working directory */
1486 : : if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1487 : : postgres_exec_path) < 0)
1488 : : ereport(FATAL,
1489 : : (errmsg("%s: could not locate matching postgres executable",
1490 : : argv0)));
1491 : : #endif
1492 : :
1493 : : /*
1494 : : * Locate the pkglib directory --- this has to be set early in case we try
1495 : : * to load any modules from it in response to postgresql.conf entries.
1496 : : */
1497 : 1070 : get_pkglib_path(my_exec_path, pkglib_path);
1498 : :
1499 : : /*
1500 : : * Verify that there's a readable directory there; otherwise the Postgres
1501 : : * installation is incomplete or corrupt. (A typical cause of this
1502 : : * failure is that the postgres executable has been moved or hardlinked to
1503 : : * some directory that's not a sibling of the installation lib/
1504 : : * directory.)
1505 : : */
1506 : 1070 : pdir = AllocateDir(pkglib_path);
1507 [ - + ]: 1070 : if (pdir == NULL)
1508 [ # # ]: 0 : ereport(ERROR,
1509 : : (errcode_for_file_access(),
1510 : : errmsg("could not open directory \"%s\": %m",
1511 : : pkglib_path),
1512 : : errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1513 : : my_exec_path)));
1514 : 1070 : FreeDir(pdir);
1515 : :
1516 : : /*
1517 : : * It's not worth checking the share/ directory. If the lib/ directory is
1518 : : * there, then share/ probably is too.
1519 : : */
1520 : 1070 : }
1521 : :
1522 : : /*
1523 : : * Check that pg_control exists in the correct location in the data directory.
1524 : : *
1525 : : * No attempt is made to validate the contents of pg_control here. This is
1526 : : * just a sanity check to see if we are looking at a real data directory.
1527 : : */
1528 : : static void
1529 : 1065 : checkControlFile(void)
1530 : : {
1531 : : char path[MAXPGPATH];
1532 : : FILE *fp;
1533 : :
1534 : 1065 : snprintf(path, sizeof(path), "%s/%s", DataDir, XLOG_CONTROL_FILE);
1535 : :
1536 : 1065 : fp = AllocateFile(path, PG_BINARY_R);
1537 [ - + ]: 1065 : if (fp == NULL)
1538 : : {
1539 : 0 : write_stderr("%s: could not find the database system\n"
1540 : : "Expected to find it in the directory \"%s\",\n"
1541 : : "but could not open file \"%s\": %m\n",
1542 : : progname, DataDir, path);
1543 : 0 : ExitPostmaster(2);
1544 : : }
1545 : 1065 : FreeFile(fp);
1546 : 1065 : }
1547 : :
1548 : : /*
1549 : : * Determine how long should we let ServerLoop sleep, in milliseconds.
1550 : : *
1551 : : * In normal conditions we wait at most one minute, to ensure that the other
1552 : : * background tasks handled by ServerLoop get done even when no requests are
1553 : : * arriving. However, if there are background workers waiting to be started,
1554 : : * we don't actually sleep so that they are quickly serviced. Other exception
1555 : : * cases are as shown in the code.
1556 : : */
1557 : : static int
1558 : 154666 : DetermineSleepTime(void)
1559 : : {
1560 : : TimestampTz next_wakeup;
1561 : :
1562 : : /*
1563 : : * If in ImmediateShutdown with a SIGKILL timeout, ignore everything else
1564 : : * and wait for that.
1565 : : *
1566 : : * XXX Shouldn't this also test FatalError?
1567 : : */
1568 [ + + ]: 154666 : if (Shutdown >= ImmediateShutdown)
1569 : : {
1570 [ + - ]: 1593 : if (AbortStartTime != 0)
1571 : : {
1572 : 1593 : time_t curtime = time(NULL);
1573 : : int seconds;
1574 : :
1575 : : /*
1576 : : * time left to abort; clamp to 0 if it already expired, or if
1577 : : * time goes backwards
1578 : : */
1579 [ + - ]: 1593 : if (curtime < AbortStartTime ||
1580 [ - + ]: 1593 : curtime - AbortStartTime >= SIGKILL_CHILDREN_AFTER_SECS)
1581 : 0 : seconds = 0;
1582 : : else
1583 : 1593 : seconds = SIGKILL_CHILDREN_AFTER_SECS -
1584 : : (curtime - AbortStartTime);
1585 : :
1586 : 1593 : return seconds * 1000;
1587 : : }
1588 : : }
1589 : :
1590 : : /* Time of next maybe_start_io_workers() call, or 0 for none. */
1591 : 153073 : next_wakeup = maybe_start_io_workers_scheduled_at();
1592 : :
1593 : : /* Ignore bgworkers during shutdown. */
1594 [ - + - - ]: 153073 : if (StartWorkerNeeded && Shutdown == NoShutdown)
1595 : 0 : return 0;
1596 : :
1597 [ + + - + ]: 153073 : if (HaveCrashedWorker && Shutdown == NoShutdown)
1598 : : {
1599 : : dlist_mutable_iter iter;
1600 : :
1601 : : /*
1602 : : * When there are crashed bgworkers, we sleep just long enough that
1603 : : * they are restarted when they request to be. Scan the list to
1604 : : * determine the minimum of all wakeup times according to most recent
1605 : : * crash time and requested restart interval.
1606 : : */
1607 [ # # # # ]: 0 : dlist_foreach_modify(iter, &BackgroundWorkerList)
1608 : : {
1609 : : RegisteredBgWorker *rw;
1610 : : TimestampTz this_wakeup;
1611 : :
1612 : 0 : rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
1613 : :
1614 [ # # ]: 0 : if (rw->rw_crashed_at == 0)
1615 : 0 : continue;
1616 : :
1617 [ # # ]: 0 : if (rw->rw_worker.bgw_restart_time == BGW_NEVER_RESTART
1618 [ # # ]: 0 : || rw->rw_terminate)
1619 : : {
1620 : 0 : ForgetBackgroundWorker(rw);
1621 : 0 : continue;
1622 : : }
1623 : :
1624 : 0 : this_wakeup = TimestampTzPlusMilliseconds(rw->rw_crashed_at,
1625 : : 1000L * rw->rw_worker.bgw_restart_time);
1626 [ # # # # ]: 0 : if (next_wakeup == 0 || this_wakeup < next_wakeup)
1627 : 0 : next_wakeup = this_wakeup;
1628 : : }
1629 : : }
1630 : :
1631 [ + + ]: 153073 : if (next_wakeup != 0)
1632 : : {
1633 : : int ms;
1634 : :
1635 : : /* result of TimestampDifferenceMilliseconds is in [0, INT_MAX] */
1636 : 47 : ms = (int) TimestampDifferenceMilliseconds(GetCurrentTimestamp(),
1637 : : next_wakeup);
1638 : 47 : return Min(60 * 1000, ms);
1639 : : }
1640 : :
1641 : 153026 : return 60 * 1000;
1642 : : }
1643 : :
1644 : : /*
1645 : : * Activate or deactivate notifications of server socket events. Since we
1646 : : * don't currently have a way to remove events from an existing WaitEventSet,
1647 : : * we'll just destroy and recreate the whole thing. This is called during
1648 : : * shutdown so we can wait for backends to exit without accepting new
1649 : : * connections, and during crash reinitialization when we need to start
1650 : : * listening for new connections again. The WaitEventSet will be freed in fork
1651 : : * children by ClosePostmasterPorts().
1652 : : */
1653 : : static void
1654 : 2104 : ConfigurePostmasterWaitSet(bool accept_connections)
1655 : : {
1656 [ + + ]: 2104 : if (pm_wait_set)
1657 : 1057 : FreeWaitEventSet(pm_wait_set);
1658 : 2104 : pm_wait_set = NULL;
1659 : :
1660 : 4208 : pm_wait_set = CreateWaitEventSet(NULL,
1661 : 2104 : accept_connections ? (1 + NumListenSockets) : 1);
1662 : 2104 : AddWaitEventToSet(pm_wait_set, WL_LATCH_SET, PGINVALID_SOCKET, MyLatch,
1663 : : NULL);
1664 : :
1665 [ + + ]: 2104 : if (accept_connections)
1666 : : {
1667 [ + + ]: 2145 : for (int i = 0; i < NumListenSockets; i++)
1668 : 1093 : AddWaitEventToSet(pm_wait_set, WL_SOCKET_ACCEPT, ListenSockets[i],
1669 : : NULL, NULL);
1670 : : }
1671 : 2104 : }
1672 : :
1673 : : /*
1674 : : * Main idle loop of postmaster
1675 : : */
1676 : : static int
1677 : 1047 : ServerLoop(void)
1678 : : {
1679 : : time_t last_lockfile_recheck_time,
1680 : : last_touch_time;
1681 : : WaitEvent events[MAXLISTEN];
1682 : : int nevents;
1683 : :
1684 : 1047 : ConfigurePostmasterWaitSet(true);
1685 : 1047 : last_lockfile_recheck_time = last_touch_time = time(NULL);
1686 : :
1687 : : for (;;)
1688 : 153619 : {
1689 : : time_t now;
1690 : :
1691 : 154666 : nevents = WaitEventSetWait(pm_wait_set,
1692 : 154666 : DetermineSleepTime(),
1693 : : events,
1694 : : lengthof(events),
1695 : : 0 /* postmaster posts no wait_events */ );
1696 : :
1697 : : /*
1698 : : * Latch set by signal handler, or new connection pending on any of
1699 : : * our sockets? If the latter, fork a child process to deal with it.
1700 : : */
1701 [ + + ]: 308272 : for (int i = 0; i < nevents; i++)
1702 : : {
1703 [ + + ]: 154653 : if (events[i].events & WL_LATCH_SET)
1704 : 138593 : ResetLatch(MyLatch);
1705 : :
1706 : : /*
1707 : : * The following requests are handled unconditionally, even if we
1708 : : * didn't see WL_LATCH_SET. This gives high priority to shutdown
1709 : : * and reload requests where the latch happens to appear later in
1710 : : * events[] or will be reported by a later call to
1711 : : * WaitEventSetWait().
1712 : : */
1713 [ + + ]: 154653 : if (pending_pm_shutdown_request)
1714 : 1036 : process_pm_shutdown_request();
1715 [ + + ]: 154653 : if (pending_pm_reload_request)
1716 : 175 : process_pm_reload_request();
1717 [ + + ]: 154653 : if (pending_pm_child_exit)
1718 : 26589 : process_pm_child_exit();
1719 [ + + ]: 153606 : if (pending_pm_pmsignal)
1720 : 110900 : process_pm_pmsignal();
1721 : :
1722 [ + + ]: 153606 : if (events[i].events & WL_SOCKET_ACCEPT)
1723 : : {
1724 : : ClientSocket s;
1725 : :
1726 [ + - ]: 16060 : if (AcceptConnection(events[i].fd, &s) == STATUS_OK)
1727 : 16060 : BackendStartup(&s);
1728 : :
1729 : : /* We no longer need the open socket in this process */
1730 [ + - ]: 16060 : if (s.sock != PGINVALID_SOCKET)
1731 : : {
1732 [ - + ]: 16060 : if (closesocket(s.sock) != 0)
1733 [ # # ]: 0 : elog(LOG, "could not close client socket: %m");
1734 : : }
1735 : : }
1736 : : }
1737 : :
1738 : : /*
1739 : : * If we need to launch any background processes after changing state
1740 : : * or because some exited, do so now.
1741 : : */
1742 : 153619 : LaunchMissingBackgroundProcesses();
1743 : :
1744 : : /* If we need to signal the autovacuum launcher, do so now */
1745 [ - + ]: 153619 : if (avlauncher_needs_signal)
1746 : : {
1747 : 0 : avlauncher_needs_signal = false;
1748 [ # # ]: 0 : if (AutoVacLauncherPMChild != NULL)
1749 : 0 : signal_child(AutoVacLauncherPMChild, SIGUSR2);
1750 : : }
1751 : :
1752 : : #ifdef HAVE_PTHREAD_IS_THREADED_NP
1753 : :
1754 : : /*
1755 : : * With assertions enabled, check regularly for appearance of
1756 : : * additional threads. All builds check at start and exit.
1757 : : */
1758 : : Assert(pthread_is_threaded_np() == 0);
1759 : : #endif
1760 : :
1761 : : /*
1762 : : * Lastly, check to see if it's time to do some things that we don't
1763 : : * want to do every single time through the loop, because they're a
1764 : : * bit expensive. Note that there's up to a minute of slop in when
1765 : : * these tasks will be performed, since DetermineSleepTime() will let
1766 : : * us sleep at most that long; except for SIGKILL timeout which has
1767 : : * special-case logic there.
1768 : : */
1769 : 153619 : now = time(NULL);
1770 : :
1771 : : /*
1772 : : * If we already sent SIGQUIT to children and they are slow to shut
1773 : : * down, it's time to send them SIGKILL (or SIGABRT if requested).
1774 : : * This doesn't happen normally, but under certain conditions backends
1775 : : * can get stuck while shutting down. This is a last measure to get
1776 : : * them unwedged.
1777 : : *
1778 : : * Note we also do this during recovery from a process crash.
1779 : : */
1780 [ + + + + ]: 153619 : if ((Shutdown >= ImmediateShutdown || FatalError) &&
1781 [ + + ]: 1651 : AbortStartTime != 0 &&
1782 [ - + ]: 1645 : (now - AbortStartTime) >= SIGKILL_CHILDREN_AFTER_SECS)
1783 : : {
1784 : : /* We were gentle with them before. Not anymore */
1785 [ # # # # ]: 0 : ereport(LOG,
1786 : : /* translator: %s is SIGKILL or SIGABRT */
1787 : : (errmsg("issuing %s to recalcitrant children",
1788 : : send_abort_for_kill ? "SIGABRT" : "SIGKILL")));
1789 [ # # ]: 0 : TerminateChildren(send_abort_for_kill ? SIGABRT : SIGKILL);
1790 : : /* reset flag so we don't SIGKILL again */
1791 : 0 : AbortStartTime = 0;
1792 : : }
1793 : :
1794 : : /*
1795 : : * Once a minute, verify that postmaster.pid hasn't been removed or
1796 : : * overwritten. If it has, we force a shutdown. This avoids having
1797 : : * postmasters and child processes hanging around after their database
1798 : : * is gone, and maybe causing problems if a new database cluster is
1799 : : * created in the same place. It also provides some protection
1800 : : * against a DBA foolishly removing postmaster.pid and manually
1801 : : * starting a new postmaster. Data corruption is likely to ensue from
1802 : : * that anyway, but we can minimize the damage by aborting ASAP.
1803 : : */
1804 [ + + ]: 153619 : if (now - last_lockfile_recheck_time >= 1 * SECS_PER_MINUTE)
1805 : : {
1806 [ - + ]: 22 : if (!RecheckDataDirLockFile())
1807 : : {
1808 [ # # ]: 0 : ereport(LOG,
1809 : : (errmsg("performing immediate shutdown because data directory lock file is invalid")));
1810 : 0 : kill(MyProcPid, SIGQUIT);
1811 : : }
1812 : 22 : last_lockfile_recheck_time = now;
1813 : : }
1814 : :
1815 : : /*
1816 : : * Touch Unix socket and lock files every 58 minutes, to ensure that
1817 : : * they are not removed by overzealous /tmp-cleaning tasks. We assume
1818 : : * no one runs cleaners with cutoff times of less than an hour ...
1819 : : */
1820 [ - + ]: 153619 : if (now - last_touch_time >= 58 * SECS_PER_MINUTE)
1821 : : {
1822 : 0 : TouchSocketFiles();
1823 : 0 : TouchSocketLockFiles();
1824 : 0 : last_touch_time = now;
1825 : : }
1826 : : }
1827 : : }
1828 : :
1829 : : /*
1830 : : * canAcceptConnections --- check to see if database state allows connections
1831 : : * of the specified type. backend_type can be B_BACKEND or B_AUTOVAC_WORKER.
1832 : : * (Note that we don't yet know whether a normal B_BACKEND connection might
1833 : : * turn into a walsender.)
1834 : : */
1835 : : static CAC_state
1836 : 17714 : canAcceptConnections(BackendType backend_type)
1837 : : {
1838 : 17714 : CAC_state result = CAC_OK;
1839 : :
1840 : : Assert(backend_type == B_BACKEND || backend_type == B_AUTOVAC_WORKER);
1841 : :
1842 : : /*
1843 : : * Can't start backends when in startup/shutdown/inconsistent recovery
1844 : : * state. We treat autovac workers the same as user backends for this
1845 : : * purpose.
1846 : : */
1847 [ + + + + ]: 17714 : if (pmState != PM_RUN && pmState != PM_HOT_STANDBY)
1848 : : {
1849 [ + + ]: 246 : if (Shutdown > NoShutdown)
1850 : 51 : return CAC_SHUTDOWN; /* shutdown is pending */
1851 [ + + + + ]: 195 : else if (!FatalError && pmState == PM_STARTUP)
1852 : 186 : return CAC_STARTUP; /* normal startup */
1853 [ + + + - ]: 9 : else if (!FatalError && pmState == PM_RECOVERY)
1854 : 8 : return CAC_NOTHOTSTANDBY; /* not yet ready for hot standby */
1855 : : else
1856 : 1 : return CAC_RECOVERY; /* else must be crash recovery */
1857 : : }
1858 : :
1859 : : /*
1860 : : * "Smart shutdown" restrictions are applied only to normal connections,
1861 : : * not to autovac workers.
1862 : : */
1863 [ - + - - ]: 17468 : if (!connsAllowed && backend_type == B_BACKEND)
1864 : 0 : return CAC_SHUTDOWN; /* shutdown is pending */
1865 : :
1866 : 17468 : return result;
1867 : : }
1868 : :
1869 : : /*
1870 : : * ClosePostmasterPorts -- close all the postmaster's open sockets
1871 : : *
1872 : : * This is called during child process startup to release file descriptors
1873 : : * that are not needed by that child process. The postmaster still has
1874 : : * them open, of course.
1875 : : *
1876 : : * Note: we pass am_syslogger as a boolean because we don't want to set
1877 : : * the global variable yet when this is called.
1878 : : */
1879 : : void
1880 : 25928 : ClosePostmasterPorts(bool am_syslogger)
1881 : : {
1882 : : /* Release resources held by the postmaster's WaitEventSet. */
1883 [ + + ]: 25928 : if (pm_wait_set)
1884 : : {
1885 : 22257 : FreeWaitEventSetAfterFork(pm_wait_set);
1886 : 22257 : pm_wait_set = NULL;
1887 : : }
1888 : :
1889 : : #ifndef WIN32
1890 : :
1891 : : /*
1892 : : * Close the write end of postmaster death watch pipe. It's important to
1893 : : * do this as early as possible, so that if postmaster dies, others won't
1894 : : * think that it's still running because we're holding the pipe open.
1895 : : */
1896 [ - + ]: 25928 : if (close(postmaster_alive_fds[POSTMASTER_FD_OWN]) != 0)
1897 [ # # ]: 0 : ereport(FATAL,
1898 : : (errcode_for_file_access(),
1899 : : errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
1900 : 25928 : postmaster_alive_fds[POSTMASTER_FD_OWN] = -1;
1901 : : /* Notify fd.c that we released one pipe FD. */
1902 : 25928 : ReleaseExternalFD();
1903 : : #endif
1904 : :
1905 : : /*
1906 : : * Close the postmaster's listen sockets. These aren't tracked by fd.c,
1907 : : * so we don't call ReleaseExternalFD() here.
1908 : : *
1909 : : * The listen sockets are marked as FD_CLOEXEC, so this isn't needed in
1910 : : * EXEC_BACKEND mode.
1911 : : */
1912 : : #ifndef EXEC_BACKEND
1913 [ + + ]: 25928 : if (ListenSockets)
1914 : : {
1915 [ + + ]: 52506 : for (int i = 0; i < NumListenSockets; i++)
1916 : : {
1917 [ - + ]: 26579 : if (closesocket(ListenSockets[i]) != 0)
1918 [ # # ]: 0 : elog(LOG, "could not close listen socket: %m");
1919 : : }
1920 : 25927 : pfree(ListenSockets);
1921 : : }
1922 : 25928 : NumListenSockets = 0;
1923 : 25928 : ListenSockets = NULL;
1924 : : #endif
1925 : :
1926 : : /*
1927 : : * If using syslogger, close the read side of the pipe. We don't bother
1928 : : * tracking this in fd.c, either.
1929 : : */
1930 [ + + ]: 25928 : if (!am_syslogger)
1931 : : {
1932 : : #ifndef WIN32
1933 [ + + ]: 25927 : if (syslogPipe[0] >= 0)
1934 : 16 : close(syslogPipe[0]);
1935 : 25927 : syslogPipe[0] = -1;
1936 : : #else
1937 : : if (syslogPipe[0])
1938 : : CloseHandle(syslogPipe[0]);
1939 : : syslogPipe[0] = 0;
1940 : : #endif
1941 : : }
1942 : :
1943 : : #ifdef USE_BONJOUR
1944 : : /* If using Bonjour, close the connection to the mDNS daemon */
1945 : : if (bonjour_sdref)
1946 : : close(DNSServiceRefSockFD(bonjour_sdref));
1947 : : #endif
1948 : 25928 : }
1949 : :
1950 : :
1951 : : /*
1952 : : * InitProcessGlobals -- set MyStartTime[stamp], random seeds
1953 : : *
1954 : : * Called early in the postmaster and every backend.
1955 : : */
1956 : : void
1957 : 27281 : InitProcessGlobals(void)
1958 : : {
1959 : 27281 : MyStartTimestamp = GetCurrentTimestamp();
1960 : 27281 : MyStartTime = timestamptz_to_time_t(MyStartTimestamp);
1961 : :
1962 : : /* initialize timing infrastructure (required for INSTR_* calls) */
1963 : 27281 : pg_initialize_timing();
1964 : :
1965 : : /*
1966 : : * Set a different global seed in every process. We want something
1967 : : * unpredictable, so if possible, use high-quality random bits for the
1968 : : * seed. Otherwise, fall back to a seed based on timestamp and PID.
1969 : : */
1970 [ + - - + ]: 27281 : if (unlikely(!pg_prng_strong_seed(&pg_global_prng_state)))
1971 : : {
1972 : : uint64 rseed;
1973 : :
1974 : : /*
1975 : : * Since PIDs and timestamps tend to change more frequently in their
1976 : : * least significant bits, shift the timestamp left to allow a larger
1977 : : * total number of seeds in a given time period. Since that would
1978 : : * leave only 20 bits of the timestamp that cycle every ~1 second,
1979 : : * also mix in some higher bits.
1980 : : */
1981 : 0 : rseed = ((uint64) MyProcPid) ^
1982 : 0 : ((uint64) MyStartTimestamp << 12) ^
1983 : 0 : ((uint64) MyStartTimestamp >> 20);
1984 : :
1985 : 0 : pg_prng_seed(&pg_global_prng_state, rseed);
1986 : : }
1987 : :
1988 : : /*
1989 : : * Also make sure that we've set a good seed for random(3). Use of that
1990 : : * is deprecated in core Postgres, but extensions might use it.
1991 : : */
1992 : : #ifndef WIN32
1993 : 27281 : srandom(pg_prng_uint32(&pg_global_prng_state));
1994 : : #endif
1995 : 27281 : }
1996 : :
1997 : : /*
1998 : : * Child processes use SIGUSR1 to notify us of 'pmsignals'. pg_ctl uses
1999 : : * SIGUSR1 to ask postmaster to check for logrotate and promote files.
2000 : : */
2001 : : static void
2002 : 111184 : handle_pm_pmsignal_signal(SIGNAL_ARGS)
2003 : : {
2004 : 111184 : pending_pm_pmsignal = true;
2005 : 111184 : SetLatch(MyLatch);
2006 : 111184 : }
2007 : :
2008 : : /*
2009 : : * pg_ctl uses SIGHUP to request a reload of the configuration files.
2010 : : */
2011 : : static void
2012 : 175 : handle_pm_reload_request_signal(SIGNAL_ARGS)
2013 : : {
2014 : 175 : pending_pm_reload_request = true;
2015 : 175 : SetLatch(MyLatch);
2016 : 175 : }
2017 : :
2018 : : /*
2019 : : * Re-read config files, and tell children to do same.
2020 : : */
2021 : : static void
2022 : 175 : process_pm_reload_request(void)
2023 : : {
2024 : 175 : pending_pm_reload_request = false;
2025 : :
2026 [ + + ]: 175 : ereport(DEBUG2,
2027 : : (errmsg_internal("postmaster received reload request signal")));
2028 : :
2029 [ + - ]: 175 : if (Shutdown <= SmartShutdown)
2030 : : {
2031 [ + - ]: 175 : ereport(LOG,
2032 : : (errmsg("received SIGHUP, reloading configuration files")));
2033 : 175 : ProcessConfigFile(PGC_SIGHUP);
2034 : 175 : SignalChildren(SIGHUP, btmask_all_except(B_DEAD_END_BACKEND));
2035 : :
2036 : : /* Reload authentication config files too */
2037 [ - + ]: 175 : if (!load_hba())
2038 [ # # ]: 0 : ereport(LOG,
2039 : : /* translator: %s is a configuration file */
2040 : : (errmsg("%s was not reloaded", HbaFileName)));
2041 : :
2042 [ - + ]: 175 : if (!load_ident())
2043 [ # # ]: 0 : ereport(LOG,
2044 : : (errmsg("%s was not reloaded", IdentFileName)));
2045 : :
2046 : : #ifdef USE_SSL
2047 : : /* Reload SSL configuration as well */
2048 [ + + ]: 175 : if (EnableSSL)
2049 : : {
2050 [ + + ]: 13 : if (secure_initialize(false) == 0)
2051 : 11 : LoadedSSL = true;
2052 : : else
2053 [ + - ]: 2 : ereport(LOG,
2054 : : (errmsg("SSL configuration was not reloaded")));
2055 : : }
2056 : : else
2057 : : {
2058 : 162 : secure_destroy();
2059 : 162 : LoadedSSL = false;
2060 : : }
2061 : : #endif
2062 : :
2063 : : #ifdef EXEC_BACKEND
2064 : : /* Update the starting-point file for future children */
2065 : : write_nondefault_variables(PGC_SIGHUP);
2066 : : #endif
2067 : : }
2068 : 175 : }
2069 : :
2070 : : /*
2071 : : * pg_ctl uses SIGTERM, SIGINT and SIGQUIT to request different types of
2072 : : * shutdown.
2073 : : */
2074 : : static void
2075 : 1036 : handle_pm_shutdown_request_signal(SIGNAL_ARGS)
2076 : : {
2077 [ + + + - ]: 1036 : switch (postgres_signal_arg)
2078 : : {
2079 : 50 : case SIGTERM:
2080 : : /* smart is implied if the other two flags aren't set */
2081 : 50 : pending_pm_shutdown_request = true;
2082 : 50 : break;
2083 : 619 : case SIGINT:
2084 : 619 : pending_pm_fast_shutdown_request = true;
2085 : 619 : pending_pm_shutdown_request = true;
2086 : 619 : break;
2087 : 367 : case SIGQUIT:
2088 : 367 : pending_pm_immediate_shutdown_request = true;
2089 : 367 : pending_pm_shutdown_request = true;
2090 : 367 : break;
2091 : : }
2092 : 1036 : SetLatch(MyLatch);
2093 : 1036 : }
2094 : :
2095 : : /*
2096 : : * Process shutdown request.
2097 : : */
2098 : : static void
2099 : 1036 : process_pm_shutdown_request(void)
2100 : : {
2101 : : int mode;
2102 : :
2103 [ + + ]: 1036 : ereport(DEBUG2,
2104 : : (errmsg_internal("postmaster received shutdown request signal")));
2105 : :
2106 : 1036 : pending_pm_shutdown_request = false;
2107 : :
2108 : : /*
2109 : : * If more than one shutdown request signal arrived since the last server
2110 : : * loop, take the one that is the most immediate. That matches the
2111 : : * priority that would apply if we processed them one by one in any order.
2112 : : */
2113 [ + + ]: 1036 : if (pending_pm_immediate_shutdown_request)
2114 : : {
2115 : 367 : pending_pm_immediate_shutdown_request = false;
2116 : 367 : pending_pm_fast_shutdown_request = false;
2117 : 367 : mode = ImmediateShutdown;
2118 : : }
2119 [ + + ]: 669 : else if (pending_pm_fast_shutdown_request)
2120 : : {
2121 : 619 : pending_pm_fast_shutdown_request = false;
2122 : 619 : mode = FastShutdown;
2123 : : }
2124 : : else
2125 : 50 : mode = SmartShutdown;
2126 : :
2127 [ + + + - ]: 1036 : switch (mode)
2128 : : {
2129 : 50 : case SmartShutdown:
2130 : :
2131 : : /*
2132 : : * Smart Shutdown:
2133 : : *
2134 : : * Wait for children to end their work, then shut down.
2135 : : */
2136 [ - + ]: 50 : if (Shutdown >= SmartShutdown)
2137 : 0 : break;
2138 : 50 : Shutdown = SmartShutdown;
2139 [ + - ]: 50 : ereport(LOG,
2140 : : (errmsg("received smart shutdown request")));
2141 : :
2142 : : /* Report status */
2143 : 50 : AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_STOPPING);
2144 : : #ifdef USE_SYSTEMD
2145 : : sd_notify(0, "STOPPING=1");
2146 : : #endif
2147 : :
2148 : : /*
2149 : : * If we reached normal running, we go straight to waiting for
2150 : : * client backends to exit. If already in PM_STOP_BACKENDS or a
2151 : : * later state, do not change it.
2152 : : */
2153 [ - + - - ]: 50 : if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
2154 : 50 : connsAllowed = false;
2155 [ # # # # ]: 0 : else if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2156 : : {
2157 : : /* There should be no clients, so proceed to stop children */
2158 : 0 : UpdatePMState(PM_STOP_BACKENDS);
2159 : : }
2160 : :
2161 : : /*
2162 : : * Now wait for online backup mode to end and backends to exit. If
2163 : : * that is already the case, PostmasterStateMachine will take the
2164 : : * next step.
2165 : : */
2166 : 50 : PostmasterStateMachine();
2167 : 50 : break;
2168 : :
2169 : 619 : case FastShutdown:
2170 : :
2171 : : /*
2172 : : * Fast Shutdown:
2173 : : *
2174 : : * Abort all children with SIGTERM (rollback active transactions
2175 : : * and exit) and shut down when they are gone.
2176 : : */
2177 [ - + ]: 619 : if (Shutdown >= FastShutdown)
2178 : 0 : break;
2179 : 619 : Shutdown = FastShutdown;
2180 [ + - ]: 619 : ereport(LOG,
2181 : : (errmsg("received fast shutdown request")));
2182 : :
2183 : : /* Report status */
2184 : 619 : AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_STOPPING);
2185 : : #ifdef USE_SYSTEMD
2186 : : sd_notify(0, "STOPPING=1");
2187 : : #endif
2188 : :
2189 [ + - - + ]: 619 : if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2190 : : {
2191 : : /* Just shut down background processes silently */
2192 : 0 : UpdatePMState(PM_STOP_BACKENDS);
2193 : : }
2194 [ + + ]: 619 : else if (pmState == PM_RUN ||
2195 [ + - ]: 70 : pmState == PM_HOT_STANDBY)
2196 : : {
2197 : : /* Report that we're about to zap live client sessions */
2198 [ + - ]: 619 : ereport(LOG,
2199 : : (errmsg("aborting any active transactions")));
2200 : 619 : UpdatePMState(PM_STOP_BACKENDS);
2201 : : }
2202 : :
2203 : : /*
2204 : : * PostmasterStateMachine will issue any necessary signals, or
2205 : : * take the next step if no child processes need to be killed.
2206 : : */
2207 : 619 : PostmasterStateMachine();
2208 : 619 : break;
2209 : :
2210 : 367 : case ImmediateShutdown:
2211 : :
2212 : : /*
2213 : : * Immediate Shutdown:
2214 : : *
2215 : : * abort all children with SIGQUIT, wait for them to exit,
2216 : : * terminate remaining ones with SIGKILL, then exit without
2217 : : * attempt to properly shut down the data base system.
2218 : : */
2219 [ - + ]: 367 : if (Shutdown >= ImmediateShutdown)
2220 : 0 : break;
2221 : 367 : Shutdown = ImmediateShutdown;
2222 [ + - ]: 367 : ereport(LOG,
2223 : : (errmsg("received immediate shutdown request")));
2224 : :
2225 : : /* Report status */
2226 : 367 : AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_STOPPING);
2227 : : #ifdef USE_SYSTEMD
2228 : : sd_notify(0, "STOPPING=1");
2229 : : #endif
2230 : :
2231 : : /* tell children to shut down ASAP */
2232 : : /* (note we don't apply send_abort_for_crash here) */
2233 : 367 : SetQuitSignalReason(PMQUIT_FOR_STOP);
2234 : 367 : TerminateChildren(SIGQUIT);
2235 : 367 : UpdatePMState(PM_WAIT_BACKENDS);
2236 : :
2237 : : /* set stopwatch for them to die */
2238 : 367 : AbortStartTime = time(NULL);
2239 : :
2240 : : /*
2241 : : * Now wait for backends to exit. If there are none,
2242 : : * PostmasterStateMachine will take the next step.
2243 : : */
2244 : 367 : PostmasterStateMachine();
2245 : 367 : break;
2246 : : }
2247 : 1036 : }
2248 : :
2249 : : static void
2250 : 26692 : handle_pm_child_exit_signal(SIGNAL_ARGS)
2251 : : {
2252 : 26692 : pending_pm_child_exit = true;
2253 : 26692 : SetLatch(MyLatch);
2254 : 26692 : }
2255 : :
2256 : : /*
2257 : : * Cleanup after a child process dies.
2258 : : */
2259 : : static void
2260 : 26589 : process_pm_child_exit(void)
2261 : : {
2262 : : int pid; /* process id of dead child process */
2263 : : int exitstatus; /* its exit status */
2264 : :
2265 : 26589 : pending_pm_child_exit = false;
2266 : :
2267 [ - + ]: 26589 : ereport(DEBUG4,
2268 : : (errmsg_internal("reaping dead processes")));
2269 : :
2270 [ + + ]: 55296 : while ((pid = waitpid(-1, &exitstatus, WNOHANG)) > 0)
2271 : : {
2272 : : PMChild *pmchild;
2273 : :
2274 : : /*
2275 : : * Check if this child was a startup process.
2276 : : */
2277 [ + + + + ]: 28707 : if (StartupPMChild && pid == StartupPMChild->pid)
2278 : : {
2279 : 1052 : ReleasePostmasterChildSlot(StartupPMChild);
2280 : 1052 : StartupPMChild = NULL;
2281 : :
2282 : : /*
2283 : : * Startup process exited in response to a shutdown request (or it
2284 : : * completed normally regardless of the shutdown request).
2285 : : */
2286 [ + + ]: 1052 : if (Shutdown > NoShutdown &&
2287 [ + + + - : 124 : (EXIT_STATUS_0(exitstatus) || EXIT_STATUS_1(exitstatus)))
+ + ]
2288 : : {
2289 : 70 : StartupStatus = STARTUP_NOT_RUNNING;
2290 : 70 : UpdatePMState(PM_WAIT_BACKENDS);
2291 : : /* PostmasterStateMachine logic does the rest */
2292 : 70 : continue;
2293 : : }
2294 : :
2295 [ + - - + ]: 982 : if (EXIT_STATUS_3(exitstatus))
2296 : : {
2297 [ # # ]: 0 : ereport(LOG,
2298 : : (errmsg("shutdown at recovery target")));
2299 : 0 : StartupStatus = STARTUP_NOT_RUNNING;
2300 : 0 : Shutdown = Max(Shutdown, SmartShutdown);
2301 : 0 : TerminateChildren(SIGTERM);
2302 : 0 : UpdatePMState(PM_WAIT_BACKENDS);
2303 : : /* PostmasterStateMachine logic does the rest */
2304 : 0 : continue;
2305 : : }
2306 : :
2307 : : /*
2308 : : * Any unexpected exit (including FATAL exit) of the startup
2309 : : * process is catastrophic, so kill other children, and set
2310 : : * StartupStatus so we don't try to reinitialize after they're
2311 : : * gone. Exception: if StartupStatus is STARTUP_SIGNALED, then we
2312 : : * previously sent the startup process a SIGQUIT; so that's
2313 : : * probably the reason it died, and we do want to try to restart
2314 : : * in that case.
2315 : : *
2316 : : * This stanza also handles the case where we sent a SIGQUIT
2317 : : * during PM_STARTUP due to some dead-end child crashing: in that
2318 : : * situation, if the startup process dies on the SIGQUIT, we need
2319 : : * to transition to PM_WAIT_BACKENDS state which will allow
2320 : : * PostmasterStateMachine to restart the startup process. (On the
2321 : : * other hand, the startup process might complete normally, if we
2322 : : * were too late with the SIGQUIT. In that case we'll fall
2323 : : * through and commence normal operations.)
2324 : : */
2325 [ + + ]: 982 : if (!EXIT_STATUS_0(exitstatus))
2326 : : {
2327 [ + + ]: 65 : if (StartupStatus == STARTUP_SIGNALED)
2328 : : {
2329 : 54 : StartupStatus = STARTUP_NOT_RUNNING;
2330 [ - + ]: 54 : if (pmState == PM_STARTUP)
2331 : 0 : UpdatePMState(PM_WAIT_BACKENDS);
2332 : : }
2333 : : else
2334 : 11 : StartupStatus = STARTUP_CRASHED;
2335 : :
2336 : : /*
2337 : : * If FatalError is already set, we are reinitializing after a
2338 : : * previous crash, and HandleChildCrash() would do nothing,
2339 : : * leaving the state machine stuck at PM_STARTUP. Give up,
2340 : : * signal the remaining children and head for PM_NO_CHILDREN,
2341 : : * where STARTUP_CRASHED makes us exit.
2342 : : */
2343 [ + + - + ]: 65 : if (StartupStatus == STARTUP_CRASHED &&
2344 [ # # ]: 0 : FatalError && Shutdown != ImmediateShutdown)
2345 : : {
2346 : 0 : LogChildExit(LOG, _("startup process"), pid, exitstatus);
2347 [ # # ]: 0 : ereport(LOG,
2348 : : (errmsg("aborting startup due to startup process failure")));
2349 : 0 : HandleFatalError(PMQUIT_FOR_CRASH, true);
2350 : : }
2351 : : else
2352 : 65 : HandleChildCrash(pid, exitstatus,
2353 : 65 : _("startup process"));
2354 : 65 : continue;
2355 : : }
2356 : :
2357 : : /*
2358 : : * Startup succeeded, commence normal operations
2359 : : */
2360 : 917 : StartupStatus = STARTUP_NOT_RUNNING;
2361 : 917 : FatalError = false;
2362 : 917 : AbortStartTime = 0;
2363 : 917 : UpdatePMState(PM_RUN);
2364 : 917 : connsAllowed = true;
2365 : :
2366 : : /*
2367 : : * At the next iteration of the postmaster's main loop, we will
2368 : : * crank up the background tasks like the autovacuum launcher and
2369 : : * background workers that were not started earlier already.
2370 : : */
2371 : 917 : StartWorkerNeeded = true;
2372 : :
2373 : : /* at this point we are really open for business */
2374 [ + - ]: 917 : ereport(LOG,
2375 : : (errmsg("database system is ready to accept connections")));
2376 : :
2377 : : /* Report status */
2378 : 917 : AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_READY);
2379 : : #ifdef USE_SYSTEMD
2380 : : sd_notify(0, "READY=1");
2381 : : #endif
2382 : :
2383 : 917 : continue;
2384 : : }
2385 : :
2386 : : /*
2387 : : * Was it the bgwriter? Normal exit can be ignored; we'll start a new
2388 : : * one at the next iteration of the postmaster's main loop, if
2389 : : * necessary. Any other exit condition is treated as a crash.
2390 : : */
2391 [ + + + + ]: 27655 : if (BgWriterPMChild && pid == BgWriterPMChild->pid)
2392 : : {
2393 : 1052 : ReleasePostmasterChildSlot(BgWriterPMChild);
2394 : 1052 : BgWriterPMChild = NULL;
2395 [ + + ]: 1052 : if (!EXIT_STATUS_0(exitstatus))
2396 : 383 : HandleChildCrash(pid, exitstatus,
2397 : 383 : _("background writer process"));
2398 : 1052 : continue;
2399 : : }
2400 : :
2401 : : /*
2402 : : * Was it the checkpointer?
2403 : : */
2404 [ + + + + ]: 26603 : if (CheckpointerPMChild && pid == CheckpointerPMChild->pid)
2405 : : {
2406 : 1052 : ReleasePostmasterChildSlot(CheckpointerPMChild);
2407 : 1052 : CheckpointerPMChild = NULL;
2408 [ + + + - ]: 1052 : if (EXIT_STATUS_0(exitstatus) && pmState == PM_WAIT_CHECKPOINTER)
2409 : 669 : {
2410 : : /*
2411 : : * OK, we saw normal exit of the checkpointer after it's been
2412 : : * told to shut down. We know checkpointer wrote a shutdown
2413 : : * checkpoint, otherwise we'd still be in
2414 : : * PM_WAIT_XLOG_SHUTDOWN state.
2415 : : *
2416 : : * At this point only dead-end children and logger should be
2417 : : * left.
2418 : : */
2419 : 669 : UpdatePMState(PM_WAIT_DEAD_END);
2420 : 669 : ConfigurePostmasterWaitSet(false);
2421 : 669 : SignalChildren(SIGTERM, btmask_all_except(B_LOGGER));
2422 : : }
2423 : : else
2424 : : {
2425 : : /*
2426 : : * Any unexpected exit of the checkpointer (including FATAL
2427 : : * exit) is treated as a crash.
2428 : : */
2429 : 383 : HandleChildCrash(pid, exitstatus,
2430 : 383 : _("checkpointer process"));
2431 : : }
2432 : :
2433 : 1052 : continue;
2434 : : }
2435 : :
2436 : : /*
2437 : : * Was it the wal writer? Normal exit can be ignored; we'll start a
2438 : : * new one at the next iteration of the postmaster's main loop, if
2439 : : * necessary. Any other exit condition is treated as a crash.
2440 : : */
2441 [ + + + + ]: 25551 : if (WalWriterPMChild && pid == WalWriterPMChild->pid)
2442 : : {
2443 : 917 : ReleasePostmasterChildSlot(WalWriterPMChild);
2444 : 917 : WalWriterPMChild = NULL;
2445 [ + + ]: 917 : if (!EXIT_STATUS_0(exitstatus))
2446 : 318 : HandleChildCrash(pid, exitstatus,
2447 : 318 : _("WAL writer process"));
2448 : 917 : continue;
2449 : : }
2450 : :
2451 : : /*
2452 : : * Was it the wal receiver? If exit status is zero (normal) or one
2453 : : * (FATAL exit), we assume everything is all right just like normal
2454 : : * backends. (If we need a new wal receiver, we'll start one at the
2455 : : * next iteration of the postmaster's main loop.)
2456 : : */
2457 [ + + + + ]: 24634 : if (WalReceiverPMChild && pid == WalReceiverPMChild->pid)
2458 : : {
2459 : 299 : ReleasePostmasterChildSlot(WalReceiverPMChild);
2460 : 299 : WalReceiverPMChild = NULL;
2461 [ + - + - : 299 : if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
+ + ]
2462 : 23 : HandleChildCrash(pid, exitstatus,
2463 : 23 : _("WAL receiver process"));
2464 : 299 : continue;
2465 : : }
2466 : :
2467 : : /*
2468 : : * Was it the wal summarizer? Normal exit can be ignored; we'll start
2469 : : * a new one at the next iteration of the postmaster's main loop, if
2470 : : * necessary. Any other exit condition is treated as a crash.
2471 : : */
2472 [ + + + + ]: 24335 : if (WalSummarizerPMChild && pid == WalSummarizerPMChild->pid)
2473 : : {
2474 : 24 : ReleasePostmasterChildSlot(WalSummarizerPMChild);
2475 : 24 : WalSummarizerPMChild = NULL;
2476 [ + + ]: 24 : if (!EXIT_STATUS_0(exitstatus))
2477 : 19 : HandleChildCrash(pid, exitstatus,
2478 : 19 : _("WAL summarizer process"));
2479 : 24 : continue;
2480 : : }
2481 : :
2482 : : /*
2483 : : * Was it the autovacuum launcher? Normal exit can be ignored; we'll
2484 : : * start a new one at the next iteration of the postmaster's main
2485 : : * loop, if necessary. Any other exit condition is treated as a
2486 : : * crash.
2487 : : */
2488 [ + + + + ]: 24311 : if (AutoVacLauncherPMChild && pid == AutoVacLauncherPMChild->pid)
2489 : : {
2490 : 756 : ReleasePostmasterChildSlot(AutoVacLauncherPMChild);
2491 : 756 : AutoVacLauncherPMChild = NULL;
2492 [ + + ]: 756 : if (!EXIT_STATUS_0(exitstatus))
2493 : 267 : HandleChildCrash(pid, exitstatus,
2494 : 267 : _("autovacuum launcher process"));
2495 : 756 : continue;
2496 : : }
2497 : :
2498 : : /*
2499 : : * Was it the archiver? If exit status is zero (normal) or one (FATAL
2500 : : * exit), we assume everything is all right just like normal backends
2501 : : * and just try to start a new one on the next cycle of the
2502 : : * postmaster's main loop, to retry archiving remaining files.
2503 : : */
2504 [ + + + + ]: 23555 : if (PgArchPMChild && pid == PgArchPMChild->pid)
2505 : : {
2506 : 63 : ReleasePostmasterChildSlot(PgArchPMChild);
2507 : 63 : PgArchPMChild = NULL;
2508 [ + + + - : 63 : if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
+ - ]
2509 : 44 : HandleChildCrash(pid, exitstatus,
2510 : 44 : _("archiver process"));
2511 : 63 : continue;
2512 : : }
2513 : :
2514 : : /* Was it the system logger? If so, try to start a new one */
2515 [ + + - + ]: 23492 : if (SysLoggerPMChild && pid == SysLoggerPMChild->pid)
2516 : : {
2517 : 0 : ReleasePostmasterChildSlot(SysLoggerPMChild);
2518 : 0 : SysLoggerPMChild = NULL;
2519 : :
2520 : : /* for safety's sake, launch new logger *first* */
2521 [ # # ]: 0 : if (Logging_collector)
2522 : 0 : StartSysLogger();
2523 : :
2524 [ # # ]: 0 : if (!EXIT_STATUS_0(exitstatus))
2525 : 0 : LogChildExit(LOG, _("system logger process"),
2526 : : pid, exitstatus);
2527 : 0 : continue;
2528 : : }
2529 : :
2530 : : /*
2531 : : * Was it the slot sync worker? Normal exit or FATAL exit can be
2532 : : * ignored (FATAL can be caused by libpqwalreceiver on receiving
2533 : : * shutdown request by the startup process during promotion); we'll
2534 : : * start a new one at the next iteration of the postmaster's main
2535 : : * loop, if necessary. Any other exit condition is treated as a crash.
2536 : : */
2537 [ + + + + ]: 23492 : if (SlotSyncWorkerPMChild && pid == SlotSyncWorkerPMChild->pid)
2538 : : {
2539 : 6 : ReleasePostmasterChildSlot(SlotSyncWorkerPMChild);
2540 : 6 : SlotSyncWorkerPMChild = NULL;
2541 [ + + + - : 6 : if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
- + ]
2542 : 0 : HandleChildCrash(pid, exitstatus,
2543 : 0 : _("slot sync worker process"));
2544 : 6 : continue;
2545 : : }
2546 : :
2547 : : /* Was it an IO worker? */
2548 [ + + ]: 23486 : if (maybe_reap_io_worker(pid))
2549 : : {
2550 [ + + + - : 2153 : if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
+ + ]
2551 : 772 : HandleChildCrash(pid, exitstatus, _("io worker"));
2552 : :
2553 : : /*
2554 : : * A worker that exited with an error might have brought the pool
2555 : : * size below io_min_workers, or allowed the queue to grow to the
2556 : : * point where another worker called for growth.
2557 : : *
2558 : : * In the common case that a worker timed out due to idleness, no
2559 : : * replacement needs to be started. maybe_start_io_workers() will
2560 : : * figure that out.
2561 : : */
2562 : 2153 : maybe_start_io_workers();
2563 : :
2564 : 2153 : continue;
2565 : : }
2566 : :
2567 : : /*
2568 : : * Was it a backend or a background worker?
2569 : : */
2570 : 21333 : pmchild = FindPostmasterChildByPid(pid);
2571 [ + - ]: 21333 : if (pmchild)
2572 : : {
2573 : 21333 : CleanupBackend(pmchild, exitstatus);
2574 : : }
2575 : :
2576 : : /*
2577 : : * We don't know anything about this child process. That's highly
2578 : : * unexpected, as we do track all the child processes that we fork.
2579 : : */
2580 : : else
2581 : : {
2582 [ # # # # : 0 : if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
# # ]
2583 : 0 : HandleChildCrash(pid, exitstatus, _("untracked child process"));
2584 : : else
2585 : 0 : LogChildExit(LOG, _("untracked child process"), pid, exitstatus);
2586 : : }
2587 : : } /* loop over pending child-death reports */
2588 : :
2589 : : /*
2590 : : * After cleaning out the SIGCHLD queue, see if we have any state changes
2591 : : * or actions to make.
2592 : : */
2593 : 26589 : PostmasterStateMachine();
2594 : 25542 : }
2595 : :
2596 : : /*
2597 : : * CleanupBackend -- cleanup after terminated backend or background worker.
2598 : : *
2599 : : * Remove all local state associated with the child process and release its
2600 : : * PMChild slot.
2601 : : */
2602 : : static void
2603 : 21333 : CleanupBackend(PMChild *bp,
2604 : : int exitstatus) /* child's exit status. */
2605 : : {
2606 : : char namebuf[MAXPGPATH];
2607 : : const char *procname;
2608 : 21333 : bool crashed = false;
2609 : 21333 : bool logged = false;
2610 : : pid_t bp_pid;
2611 : : bool bp_bgworker_notify;
2612 : : BackendType bp_bkend_type;
2613 : : RegisteredBgWorker *rw;
2614 : :
2615 : : /* Construct a process name for the log message */
2616 [ + + ]: 21333 : if (bp->bkend_type == B_BG_WORKER)
2617 : : {
2618 : 3619 : snprintf(namebuf, MAXPGPATH, _("background worker \"%s\""),
2619 : 3619 : bp->rw->rw_worker.bgw_type);
2620 : 3619 : procname = namebuf;
2621 : : }
2622 : : else
2623 : 17714 : procname = _(GetBackendTypeDesc(bp->bkend_type));
2624 : :
2625 : : /*
2626 : : * If a backend dies in an ugly way then we must signal all other backends
2627 : : * to quickdie. If exit status is zero (normal) or one (FATAL exit), we
2628 : : * assume everything is all right and proceed to remove the backend from
2629 : : * the active child list.
2630 : : */
2631 [ + + + + : 21333 : if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
+ + ]
2632 : 653 : crashed = true;
2633 : :
2634 : : #ifdef WIN32
2635 : :
2636 : : /*
2637 : : * On win32, also treat ERROR_WAIT_NO_CHILDREN (128) as nonfatal case,
2638 : : * since that sometimes happens under load when the process fails to start
2639 : : * properly (long before it starts using shared memory). Microsoft reports
2640 : : * it is related to mutex failure:
2641 : : * http://archives.postgresql.org/pgsql-hackers/2010-09/msg00790.php
2642 : : */
2643 : : if (exitstatus == ERROR_WAIT_NO_CHILDREN)
2644 : : {
2645 : : LogChildExit(LOG, procname, bp->pid, exitstatus);
2646 : : logged = true;
2647 : : crashed = false;
2648 : : }
2649 : : #endif
2650 : :
2651 : : /*
2652 : : * Release the PMChild entry.
2653 : : *
2654 : : * If the process attached to shared memory, this also checks that it
2655 : : * detached cleanly.
2656 : : */
2657 : 21333 : bp_pid = bp->pid;
2658 : 21333 : bp_bgworker_notify = bp->bgworker_notify;
2659 : 21333 : bp_bkend_type = bp->bkend_type;
2660 : 21333 : rw = bp->rw;
2661 [ + + ]: 21333 : if (!ReleasePostmasterChildSlot(bp))
2662 : : {
2663 : : /*
2664 : : * Uh-oh, the child failed to clean itself up. Treat as a crash after
2665 : : * all.
2666 : : */
2667 : 408 : crashed = true;
2668 : : }
2669 : 21333 : bp = NULL;
2670 : :
2671 : : /*
2672 : : * In a crash case, exit immediately without resetting background worker
2673 : : * state. However, if restart_after_crash is enabled, the background
2674 : : * worker state (e.g., rw_pid) still needs be reset so the worker can
2675 : : * restart after crash recovery. This reset is handled in
2676 : : * ResetBackgroundWorkerCrashTimes(), not here.
2677 : : */
2678 [ + + ]: 21333 : if (crashed)
2679 : : {
2680 : 653 : HandleChildCrash(bp_pid, exitstatus, procname);
2681 : 653 : return;
2682 : : }
2683 : :
2684 : : /*
2685 : : * This backend may have been slated to receive SIGUSR1 when some
2686 : : * background worker started or stopped. Cancel those notifications, as
2687 : : * we don't want to signal PIDs that are not PostgreSQL backends. This
2688 : : * gets skipped in the (probably very common) case where the backend has
2689 : : * never requested any such notifications.
2690 : : */
2691 [ + + ]: 20680 : if (bp_bgworker_notify)
2692 : 367 : BackgroundWorkerStopNotifications(bp_pid);
2693 : :
2694 : : /*
2695 : : * If it was an autovacuum worker, wake up the launcher so that it can
2696 : : * immediately launch a new worker or rebalance to cost limit setting of
2697 : : * the remaining workers.
2698 : : */
2699 [ + + + + ]: 20680 : if (bp_bkend_type == B_AUTOVAC_WORKER && AutoVacLauncherPMChild != NULL)
2700 : 1650 : signal_child(AutoVacLauncherPMChild, SIGUSR2);
2701 : :
2702 : : /*
2703 : : * If it was a background worker, also update its RegisteredBgWorker
2704 : : * entry.
2705 : : */
2706 [ + + ]: 20680 : if (bp_bkend_type == B_BG_WORKER)
2707 : : {
2708 [ + + ]: 3275 : if (!EXIT_STATUS_0(exitstatus))
2709 : : {
2710 : : /* Record timestamp, so we know when to restart the worker. */
2711 : 874 : rw->rw_crashed_at = GetCurrentTimestamp();
2712 : : }
2713 : : else
2714 : : {
2715 : : /* Zero exit status means terminate */
2716 : 2401 : rw->rw_crashed_at = 0;
2717 : 2401 : rw->rw_terminate = true;
2718 : : }
2719 : :
2720 : 3275 : rw->rw_pid = 0;
2721 : 3275 : ReportBackgroundWorkerExit(rw); /* report child death */
2722 : :
2723 [ + - ]: 3275 : if (!logged)
2724 : : {
2725 [ + + ]: 3275 : LogChildExit(EXIT_STATUS_0(exitstatus) ? DEBUG1 : LOG,
2726 : : procname, bp_pid, exitstatus);
2727 : 3275 : logged = true;
2728 : : }
2729 : :
2730 : : /* have it be restarted */
2731 : 3275 : HaveCrashedWorker = true;
2732 : : }
2733 : :
2734 [ + + ]: 20680 : if (!logged)
2735 : 17405 : LogChildExit(DEBUG2, procname, bp_pid, exitstatus);
2736 : : }
2737 : :
2738 : : /*
2739 : : * Transition into FatalError state, in response to something bad having
2740 : : * happened. Commonly the caller will have logged the reason for entering
2741 : : * FatalError state.
2742 : : *
2743 : : * This should only be called when not already in ImmediateShutdown state.
2744 : : */
2745 : : static void
2746 : 16 : HandleFatalError(QuitSignalReason reason, bool consider_sigabrt)
2747 : : {
2748 : : int sigtosend;
2749 : :
2750 : : Assert(Shutdown != ImmediateShutdown);
2751 : :
2752 : 16 : SetQuitSignalReason(reason);
2753 : :
2754 [ + - - + ]: 16 : if (consider_sigabrt && send_abort_for_crash)
2755 : 0 : sigtosend = SIGABRT;
2756 : : else
2757 : 16 : sigtosend = SIGQUIT;
2758 : :
2759 : : /*
2760 : : * Signal all other child processes to exit.
2761 : : *
2762 : : * We could exclude dead-end children here, but at least when sending
2763 : : * SIGABRT it seems better to include them.
2764 : : */
2765 : 16 : TerminateChildren(sigtosend);
2766 : :
2767 : 16 : FatalError = true;
2768 : :
2769 : : /*
2770 : : * Choose the appropriate new state to react to the fatal error. Unless we
2771 : : * were already in the process of shutting down, we go through
2772 : : * PM_WAIT_BACKENDS. For errors during the shutdown sequence, we directly
2773 : : * switch to PM_WAIT_DEAD_END.
2774 : : */
2775 [ - + - - : 16 : switch (pmState)
- - ]
2776 : : {
2777 : 0 : case PM_INIT:
2778 : : /* shouldn't have any children */
2779 : : Assert(false);
2780 : 0 : break;
2781 : :
2782 : : /* wait for children to die */
2783 : 16 : case PM_STARTUP:
2784 : : case PM_RECOVERY:
2785 : : case PM_HOT_STANDBY:
2786 : : case PM_RUN:
2787 : : case PM_STOP_BACKENDS:
2788 : 16 : UpdatePMState(PM_WAIT_BACKENDS);
2789 : 16 : break;
2790 : :
2791 : 0 : case PM_WAIT_BACKENDS:
2792 : : /* there might be more backends to wait for */
2793 : 0 : break;
2794 : :
2795 : 0 : case PM_WAIT_XLOG_SHUTDOWN:
2796 : : case PM_WAIT_XLOG_ARCHIVAL:
2797 : : case PM_WAIT_CHECKPOINTER:
2798 : : case PM_WAIT_IO_WORKERS:
2799 : :
2800 : : /*
2801 : : * NB: Similar code exists in PostmasterStateMachine()'s handling
2802 : : * of FatalError in PM_STOP_BACKENDS/PM_WAIT_BACKENDS states.
2803 : : */
2804 : 0 : ConfigurePostmasterWaitSet(false);
2805 : 0 : UpdatePMState(PM_WAIT_DEAD_END);
2806 : 0 : break;
2807 : :
2808 : 0 : case PM_WAIT_DEAD_END:
2809 : : case PM_NO_CHILDREN:
2810 : 0 : break;
2811 : : }
2812 : :
2813 : : /*
2814 : : * .. and if this doesn't happen quickly enough, now the clock is ticking
2815 : : * for us to kill them without mercy.
2816 : : */
2817 [ + - ]: 16 : if (AbortStartTime == 0)
2818 : 16 : AbortStartTime = time(NULL);
2819 : 16 : }
2820 : :
2821 : : /*
2822 : : * HandleChildCrash -- cleanup after failed backend, bgwriter, checkpointer,
2823 : : * walwriter, autovacuum, archiver, slot sync worker, or background worker.
2824 : : *
2825 : : * The objectives here are to clean up our local state about the child
2826 : : * process, and to signal all other remaining children to quickdie.
2827 : : *
2828 : : * The caller has already released its PMChild slot.
2829 : : */
2830 : : static void
2831 : 2927 : HandleChildCrash(int pid, int exitstatus, const char *procname)
2832 : : {
2833 : : /*
2834 : : * We only log messages and send signals if this is the first process
2835 : : * crash and we're not doing an immediate shutdown; otherwise, we're only
2836 : : * here to update postmaster's idea of live processes. If we have already
2837 : : * signaled children, nonzero exit status is to be expected, so don't
2838 : : * clutter log.
2839 : : */
2840 [ + + + + ]: 2927 : if (FatalError || Shutdown == ImmediateShutdown)
2841 : 2911 : return;
2842 : :
2843 : 16 : LogChildExit(LOG, procname, pid, exitstatus);
2844 [ + - ]: 16 : ereport(LOG,
2845 : : (errmsg("terminating any other active server processes")));
2846 : :
2847 : : /*
2848 : : * Switch into error state. The crashed process has already been removed
2849 : : * from ActiveChildList.
2850 : : */
2851 : 16 : HandleFatalError(PMQUIT_FOR_CRASH, true);
2852 : : }
2853 : :
2854 : : /*
2855 : : * Log the death of a child process.
2856 : : */
2857 : : static void
2858 : 20696 : LogChildExit(int lev, const char *procname, int pid, int exitstatus)
2859 : : {
2860 : : /*
2861 : : * size of activity_buffer is arbitrary, but set equal to default
2862 : : * track_activity_query_size
2863 : : */
2864 : : char activity_buffer[1024];
2865 : 20696 : const char *activity = NULL;
2866 : :
2867 [ + + ]: 20696 : if (!EXIT_STATUS_0(exitstatus))
2868 : 1292 : activity = pgstat_get_crashed_backend_activity(pid,
2869 : : activity_buffer,
2870 : : sizeof(activity_buffer));
2871 : :
2872 [ + + ]: 20696 : if (WIFEXITED(exitstatus))
2873 [ + + + + ]: 20692 : ereport(lev,
2874 : :
2875 : : /*------
2876 : : translator: %s is a noun phrase describing a child process, such as
2877 : : "server process" */
2878 : : (errmsg("%s (PID %d) exited with exit code %d",
2879 : : procname, pid, WEXITSTATUS(exitstatus)),
2880 : : activity ? errdetail("Failed process was running: %s", activity) : 0));
2881 [ + - ]: 4 : else if (WIFSIGNALED(exitstatus))
2882 : : {
2883 : : #if defined(WIN32)
2884 : : ereport(lev,
2885 : :
2886 : : /*------
2887 : : translator: %s is a noun phrase describing a child process, such as
2888 : : "server process" */
2889 : : (errmsg("%s (PID %d) was terminated by exception 0x%X",
2890 : : procname, pid, WTERMSIG(exitstatus)),
2891 : : errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
2892 : : activity ? errdetail("Failed process was running: %s", activity) : 0));
2893 : : #else
2894 [ + - + - ]: 4 : ereport(lev,
2895 : :
2896 : : /*------
2897 : : translator: %s is a noun phrase describing a child process, such as
2898 : : "server process" */
2899 : : (errmsg("%s (PID %d) was terminated by signal %d: %s",
2900 : : procname, pid, WTERMSIG(exitstatus),
2901 : : pg_strsignal(WTERMSIG(exitstatus))),
2902 : : activity ? errdetail("Failed process was running: %s", activity) : 0));
2903 : : #endif
2904 : : }
2905 : : else
2906 [ # # # # ]: 0 : ereport(lev,
2907 : :
2908 : : /*------
2909 : : translator: %s is a noun phrase describing a child process, such as
2910 : : "server process" */
2911 : : (errmsg("%s (PID %d) exited with unrecognized status %d",
2912 : : procname, pid, exitstatus),
2913 : : activity ? errdetail("Failed process was running: %s", activity) : 0));
2914 : 20696 : }
2915 : :
2916 : : /*
2917 : : * Advance the postmaster's state machine and take actions as appropriate
2918 : : *
2919 : : * This is common code for process_pm_shutdown_request(),
2920 : : * process_pm_child_exit() and process_pm_pmsignal(), which process the signals
2921 : : * that might mean we need to change state.
2922 : : */
2923 : : static void
2924 : 29726 : PostmasterStateMachine(void)
2925 : : {
2926 : : /* If we're doing a smart shutdown, try to advance that state. */
2927 [ + + + + ]: 29726 : if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
2928 : : {
2929 [ + + ]: 21460 : if (!connsAllowed)
2930 : : {
2931 : : /*
2932 : : * This state ends when we have no normal client backends running.
2933 : : * Then we're ready to stop other children.
2934 : : */
2935 [ + + ]: 129 : if (CountChildren(btmask(B_BACKEND)) == 0)
2936 : 50 : UpdatePMState(PM_STOP_BACKENDS);
2937 : : }
2938 : : }
2939 : :
2940 : : /*
2941 : : * In the PM_WAIT_BACKENDS state, wait for all the regular backends and
2942 : : * processes like autovacuum and background workers that are comparable to
2943 : : * backends to exit.
2944 : : *
2945 : : * PM_STOP_BACKENDS is a transient state that means the same as
2946 : : * PM_WAIT_BACKENDS, but we signal the processes first, before waiting for
2947 : : * them. Treating it as a distinct pmState allows us to share this code
2948 : : * across multiple shutdown code paths.
2949 : : */
2950 [ + + + + ]: 29726 : if (pmState == PM_STOP_BACKENDS || pmState == PM_WAIT_BACKENDS)
2951 : : {
2952 : 5515 : BackendTypeMask targetMask = BTYPE_MASK_NONE;
2953 : :
2954 : : /*
2955 : : * PM_WAIT_BACKENDS state ends when we have no regular backends, no
2956 : : * autovac launcher or workers, and no bgworkers (including
2957 : : * unconnected ones).
2958 : : */
2959 : 5515 : targetMask = btmask_add(targetMask,
2960 : : B_BACKEND,
2961 : : B_AUTOVAC_LAUNCHER,
2962 : : B_AUTOVAC_WORKER,
2963 : : B_BG_WORKER);
2964 : :
2965 : : /*
2966 : : * No walwriter, bgwriter, slot sync worker, or WAL summarizer either.
2967 : : */
2968 : 5515 : targetMask = btmask_add(targetMask,
2969 : : B_WAL_WRITER,
2970 : : B_BG_WRITER,
2971 : : B_SLOTSYNC_WORKER,
2972 : : B_WAL_SUMMARIZER);
2973 : :
2974 : : /* If we're in recovery, also stop startup and walreceiver procs */
2975 : 5515 : targetMask = btmask_add(targetMask,
2976 : : B_STARTUP,
2977 : : B_WAL_RECEIVER);
2978 : :
2979 : : /*
2980 : : * If we are doing crash recovery or an immediate shutdown then we
2981 : : * expect archiver, checkpointer, io workers and walsender to exit as
2982 : : * well, otherwise not.
2983 : : */
2984 [ + + + + ]: 5515 : if (FatalError || Shutdown >= ImmediateShutdown)
2985 : 2034 : targetMask = btmask_add(targetMask,
2986 : : B_CHECKPOINTER,
2987 : : B_ARCHIVER,
2988 : : B_IO_WORKER,
2989 : : B_WAL_SENDER);
2990 : :
2991 : : /*
2992 : : * Normally archiver, checkpointer, IO workers and walsenders will
2993 : : * continue running; they will be terminated later after writing the
2994 : : * checkpoint record. We also let dead-end children to keep running
2995 : : * for now. The syslogger process exits last.
2996 : : *
2997 : : * This assertion checks that we have covered all backend types,
2998 : : * either by including them in targetMask, or by noting here that they
2999 : : * are allowed to continue running.
3000 : : */
3001 : : #ifdef USE_ASSERT_CHECKING
3002 : : {
3003 : : BackendTypeMask remainMask = BTYPE_MASK_NONE;
3004 : :
3005 : : remainMask = btmask_add(remainMask,
3006 : : B_DEAD_END_BACKEND,
3007 : : B_LOGGER);
3008 : :
3009 : : /*
3010 : : * Archiver, checkpointer, IO workers, and walsender may or may
3011 : : * not be in targetMask already.
3012 : : */
3013 : : remainMask = btmask_add(remainMask,
3014 : : B_ARCHIVER,
3015 : : B_CHECKPOINTER,
3016 : : B_IO_WORKER,
3017 : : B_WAL_SENDER);
3018 : :
3019 : : /* these are not real postmaster children */
3020 : : remainMask = btmask_add(remainMask,
3021 : : B_INVALID,
3022 : : B_STANDALONE_BACKEND);
3023 : :
3024 : : /* also add data checksums processes */
3025 : : remainMask = btmask_add(remainMask,
3026 : : B_DATACHECKSUMSWORKER_LAUNCHER,
3027 : : B_DATACHECKSUMSWORKER_WORKER);
3028 : :
3029 : : /* All types should be included in targetMask or remainMask */
3030 : : Assert((remainMask.mask | targetMask.mask) == BTYPE_MASK_ALL.mask);
3031 : : }
3032 : : #endif
3033 : :
3034 : : /* If we had not yet signaled the processes to exit, do so now */
3035 [ + + ]: 5515 : if (pmState == PM_STOP_BACKENDS)
3036 : : {
3037 : : /*
3038 : : * Forget any pending requests for background workers, since we're
3039 : : * no longer willing to launch any new workers. (If additional
3040 : : * requests arrive, BackgroundWorkerStateChange will reject them.)
3041 : : */
3042 : 669 : ForgetUnstartedBackgroundWorkers();
3043 : :
3044 : 669 : SignalChildren(SIGTERM, targetMask);
3045 : :
3046 : 669 : UpdatePMState(PM_WAIT_BACKENDS);
3047 : : }
3048 : :
3049 : : /* Are any of the target processes still running? */
3050 [ + + ]: 5515 : if (CountChildren(targetMask) == 0)
3051 : : {
3052 [ + + + + ]: 1052 : if (Shutdown >= ImmediateShutdown || FatalError)
3053 : : {
3054 : : /*
3055 : : * Stop any dead-end children and stop creating new ones.
3056 : : *
3057 : : * NB: Similar code exists in HandleFatalError(), when the
3058 : : * error happens in pmState > PM_WAIT_BACKENDS.
3059 : : */
3060 : 383 : UpdatePMState(PM_WAIT_DEAD_END);
3061 : 383 : ConfigurePostmasterWaitSet(false);
3062 : 383 : SignalChildren(SIGQUIT, btmask(B_DEAD_END_BACKEND));
3063 : :
3064 : : /*
3065 : : * We already SIGQUIT'd auxiliary processes (other than
3066 : : * logger), if any, when we started immediate shutdown or
3067 : : * entered FatalError state.
3068 : : */
3069 : : }
3070 : : else
3071 : : {
3072 : : /*
3073 : : * If we get here, we are proceeding with normal shutdown. All
3074 : : * the regular children are gone, and it's time to tell the
3075 : : * checkpointer to do a shutdown checkpoint.
3076 : : */
3077 : : Assert(Shutdown > NoShutdown);
3078 : : /* Start the checkpointer if not running */
3079 [ - + ]: 669 : if (CheckpointerPMChild == NULL)
3080 : 0 : CheckpointerPMChild = StartChildProcess(B_CHECKPOINTER);
3081 : : /* And tell it to write the shutdown checkpoint */
3082 [ + - ]: 669 : if (CheckpointerPMChild != NULL)
3083 : : {
3084 : 669 : signal_child(CheckpointerPMChild, SIGINT);
3085 : 669 : UpdatePMState(PM_WAIT_XLOG_SHUTDOWN);
3086 : : }
3087 : : else
3088 : : {
3089 : : /*
3090 : : * If we failed to fork a checkpointer, just shut down.
3091 : : * Any required cleanup will happen at next restart. We
3092 : : * set FatalError so that an "abnormal shutdown" message
3093 : : * gets logged when we exit.
3094 : : *
3095 : : * We don't consult send_abort_for_crash here, as it's
3096 : : * unlikely that dumping cores would illuminate the reason
3097 : : * for checkpointer fork failure.
3098 : : *
3099 : : * XXX: It may be worth to introduce a different PMQUIT
3100 : : * value that signals that the cluster is in a bad state,
3101 : : * without a process having crashed. But right now this
3102 : : * path is very unlikely to be reached, so it isn't
3103 : : * obviously worthwhile adding a distinct error message in
3104 : : * quickdie().
3105 : : */
3106 : 0 : HandleFatalError(PMQUIT_FOR_CRASH, false);
3107 : : }
3108 : : }
3109 : : }
3110 : : }
3111 : :
3112 : : /*
3113 : : * The state transition from PM_WAIT_XLOG_SHUTDOWN to
3114 : : * PM_WAIT_XLOG_ARCHIVAL is in process_pm_pmsignal(), in response to
3115 : : * PMSIGNAL_XLOG_IS_SHUTDOWN.
3116 : : */
3117 : :
3118 [ + + ]: 29726 : if (pmState == PM_WAIT_XLOG_ARCHIVAL)
3119 : : {
3120 : : /*
3121 : : * PM_WAIT_XLOG_ARCHIVAL state ends when there are no children other
3122 : : * than checkpointer, io workers and dead-end children left. There
3123 : : * shouldn't be any regular backends left by now anyway; what we're
3124 : : * really waiting for is for walsenders and archiver to exit.
3125 : : */
3126 [ + + ]: 740 : if (CountChildren(btmask_all_except(B_CHECKPOINTER, B_IO_WORKER,
3127 : : B_LOGGER, B_DEAD_END_BACKEND)) == 0)
3128 : : {
3129 : 669 : UpdatePMState(PM_WAIT_IO_WORKERS);
3130 : 669 : SignalChildren(SIGUSR2, btmask(B_IO_WORKER));
3131 : : }
3132 : : }
3133 : :
3134 [ + + ]: 29726 : if (pmState == PM_WAIT_IO_WORKERS)
3135 : : {
3136 : : /*
3137 : : * PM_WAIT_IO_WORKERS state ends when there's only checkpointer and
3138 : : * dead-end children left.
3139 : : */
3140 [ + + ]: 1964 : if (io_worker_count == 0)
3141 : : {
3142 : 669 : UpdatePMState(PM_WAIT_CHECKPOINTER);
3143 : :
3144 : : /*
3145 : : * Now that the processes mentioned above are gone, tell
3146 : : * checkpointer to shut down too. That allows checkpointer to
3147 : : * perform some last bits of cleanup without other processes
3148 : : * interfering.
3149 : : */
3150 [ + - ]: 669 : if (CheckpointerPMChild != NULL)
3151 : 669 : signal_child(CheckpointerPMChild, SIGUSR2);
3152 : : }
3153 : : }
3154 : :
3155 : : /*
3156 : : * The state transition from PM_WAIT_CHECKPOINTER to PM_WAIT_DEAD_END is
3157 : : * in process_pm_child_exit().
3158 : : */
3159 : :
3160 [ + + ]: 29726 : if (pmState == PM_WAIT_DEAD_END)
3161 : : {
3162 : : /*
3163 : : * PM_WAIT_DEAD_END state ends when all other children are gone except
3164 : : * for the logger. During normal shutdown, all that remains are
3165 : : * dead-end backends, but in FatalError processing we jump straight
3166 : : * here with more processes remaining. Note that they have already
3167 : : * been sent appropriate shutdown signals, either during a normal
3168 : : * state transition leading up to PM_WAIT_DEAD_END, or during
3169 : : * FatalError processing.
3170 : : *
3171 : : * The reason we wait is to protect against a new postmaster starting
3172 : : * conflicting subprocesses; this isn't an ironclad protection, but it
3173 : : * at least helps in the shutdown-and-immediately-restart scenario.
3174 : : */
3175 [ + + ]: 1076 : if (CountChildren(btmask_all_except(B_LOGGER)) == 0)
3176 : : {
3177 : : /* These other guys should be dead already */
3178 : : Assert(StartupPMChild == NULL);
3179 : : Assert(WalReceiverPMChild == NULL);
3180 : : Assert(WalSummarizerPMChild == NULL);
3181 : : Assert(BgWriterPMChild == NULL);
3182 : : Assert(CheckpointerPMChild == NULL);
3183 : : Assert(WalWriterPMChild == NULL);
3184 : : Assert(AutoVacLauncherPMChild == NULL);
3185 : : Assert(SlotSyncWorkerPMChild == NULL);
3186 : : /* syslogger is not considered here */
3187 : 1052 : UpdatePMState(PM_NO_CHILDREN);
3188 : : }
3189 : : }
3190 : :
3191 : : /*
3192 : : * If we've been told to shut down, we exit as soon as there are no
3193 : : * remaining children. If there was a crash, cleanup will occur at the
3194 : : * next startup. (Before PostgreSQL 8.3, we tried to recover from the
3195 : : * crash before exiting, but that seems unwise if we are quitting because
3196 : : * we got SIGTERM from init --- there may well not be time for recovery
3197 : : * before init decides to SIGKILL us.)
3198 : : *
3199 : : * Note that the syslogger continues to run. It will exit when it sees
3200 : : * EOF on its input pipe, which happens when there are no more upstream
3201 : : * processes.
3202 : : */
3203 [ + + + + ]: 29726 : if (Shutdown > NoShutdown && pmState == PM_NO_CHILDREN)
3204 : : {
3205 [ - + ]: 1036 : if (FatalError)
3206 : : {
3207 [ # # ]: 0 : ereport(LOG, (errmsg("abnormal database system shutdown")));
3208 : 0 : ExitPostmaster(1);
3209 : : }
3210 : : else
3211 : : {
3212 : : /*
3213 : : * Normal exit from the postmaster is here. We don't need to log
3214 : : * anything here, since the UnlinkLockFiles proc_exit callback
3215 : : * will do so, and that should be the last user-visible action.
3216 : : */
3217 : 1036 : ExitPostmaster(0);
3218 : : }
3219 : : }
3220 : :
3221 : : /*
3222 : : * If the startup process failed, or the user does not want an automatic
3223 : : * restart after backend crashes, wait for all non-syslogger children to
3224 : : * exit, and then exit postmaster. We don't try to reinitialize when the
3225 : : * startup process fails, because more than likely it will just fail again
3226 : : * and we will keep trying forever.
3227 : : */
3228 [ + + ]: 28690 : if (pmState == PM_NO_CHILDREN)
3229 : : {
3230 [ + + ]: 16 : if (StartupStatus == STARTUP_CRASHED)
3231 : : {
3232 [ + - ]: 11 : ereport(LOG,
3233 : : (errmsg("shutting down due to startup process failure")));
3234 : 11 : ExitPostmaster(1);
3235 : : }
3236 [ - + ]: 5 : if (!restart_after_crash)
3237 : : {
3238 [ # # ]: 0 : ereport(LOG,
3239 : : (errmsg("shutting down because \"restart_after_crash\" is off")));
3240 : 0 : ExitPostmaster(1);
3241 : : }
3242 : : }
3243 : :
3244 : : /*
3245 : : * If we need to recover from a crash, wait for all non-syslogger children
3246 : : * to exit, then reset shmem and start the startup process.
3247 : : */
3248 [ + + + + ]: 28679 : if (FatalError && pmState == PM_NO_CHILDREN)
3249 : : {
3250 [ + - ]: 5 : ereport(LOG,
3251 : : (errmsg("all server processes terminated; reinitializing")));
3252 : :
3253 : : /* remove leftover temporary files after a crash */
3254 [ + + ]: 5 : if (remove_temp_files_after_crash)
3255 : 4 : RemovePgTempFiles();
3256 : :
3257 : : /* allow background workers to immediately restart */
3258 : 5 : ResetBackgroundWorkerCrashTimes();
3259 : :
3260 : 5 : shmem_exit(1);
3261 : :
3262 : : /* re-read control file into local memory */
3263 : 5 : LocalProcessControlFile(true);
3264 : :
3265 : : /*
3266 : : * Re-initialize shared memory and semaphores. Note: We don't call
3267 : : * RegisterBuiltinShmemCallbacks(), we keep the old registrations. In
3268 : : * order to re-register structs in extensions, we'd need to reload
3269 : : * shared preload libraries, and we don't want to do that.
3270 : : */
3271 : 5 : ResetShmemAllocator();
3272 : 5 : ShmemCallRequestCallbacks();
3273 : 5 : CreateSharedMemoryAndSemaphores();
3274 : :
3275 : 5 : UpdatePMState(PM_STARTUP);
3276 : :
3277 : : /* Make sure we can perform I/O while starting up. */
3278 : 5 : maybe_start_io_workers();
3279 : :
3280 : 5 : StartupPMChild = StartChildProcess(B_STARTUP);
3281 : : Assert(StartupPMChild != NULL);
3282 : 5 : StartupStatus = STARTUP_RUNNING;
3283 : : /* crash recovery started, reset SIGKILL flag */
3284 : 5 : AbortStartTime = 0;
3285 : :
3286 : : /* start accepting server socket connection events again */
3287 : 5 : ConfigurePostmasterWaitSet(true);
3288 : : }
3289 : 28679 : }
3290 : :
3291 : : static const char *
3292 : 1568 : pmstate_name(PMState state)
3293 : : {
3294 : : #define PM_TOSTR_CASE(sym) case sym: return #sym
3295 [ + + + + : 1568 : switch (state)
+ + + + +
+ + + +
- ]
3296 : : {
3297 : 84 : PM_TOSTR_CASE(PM_INIT);
3298 : 168 : PM_TOSTR_CASE(PM_STARTUP);
3299 : 30 : PM_TOSTR_CASE(PM_RECOVERY);
3300 : 28 : PM_TOSTR_CASE(PM_HOT_STANDBY);
3301 : 155 : PM_TOSTR_CASE(PM_RUN);
3302 : 132 : PM_TOSTR_CASE(PM_STOP_BACKENDS);
3303 : 182 : PM_TOSTR_CASE(PM_WAIT_BACKENDS);
3304 : 132 : PM_TOSTR_CASE(PM_WAIT_XLOG_SHUTDOWN);
3305 : 132 : PM_TOSTR_CASE(PM_WAIT_XLOG_ARCHIVAL);
3306 : 132 : PM_TOSTR_CASE(PM_WAIT_IO_WORKERS);
3307 : 174 : PM_TOSTR_CASE(PM_WAIT_DEAD_END);
3308 : 132 : PM_TOSTR_CASE(PM_WAIT_CHECKPOINTER);
3309 : 87 : PM_TOSTR_CASE(PM_NO_CHILDREN);
3310 : : }
3311 : : #undef PM_TOSTR_CASE
3312 : :
3313 : 0 : pg_unreachable();
3314 : : return ""; /* silence compiler */
3315 : : }
3316 : :
3317 : : /*
3318 : : * Simple wrapper for updating pmState. The main reason to have this wrapper
3319 : : * is that it makes it easy to log all state transitions.
3320 : : */
3321 : : static void
3322 : 9020 : UpdatePMState(PMState newState)
3323 : : {
3324 [ + + ]: 9020 : elog(DEBUG1, "updating PMState from %s to %s",
3325 : : pmstate_name(pmState), pmstate_name(newState));
3326 : 9020 : pmState = newState;
3327 : 9020 : }
3328 : :
3329 : : /*
3330 : : * Launch background processes after state change, or relaunch after an
3331 : : * existing process has exited.
3332 : : *
3333 : : * Check the current pmState and the status of any background processes. If
3334 : : * there are any background processes missing that should be running in the
3335 : : * current state, but are not, launch them.
3336 : : */
3337 : : static void
3338 : 153619 : LaunchMissingBackgroundProcesses(void)
3339 : : {
3340 : : /* Syslogger is active in all states */
3341 [ + + - + ]: 153619 : if (SysLoggerPMChild == NULL && Logging_collector)
3342 : 0 : StartSysLogger();
3343 : :
3344 : : /*
3345 : : * The number of configured workers might have changed, or a prior start
3346 : : * of a worker might have failed. Check if we need to start/stop any
3347 : : * workers.
3348 : : *
3349 : : * A config file change will always lead to this function being called, so
3350 : : * we always will process the config change in a timely manner.
3351 : : */
3352 : 153619 : maybe_start_io_workers();
3353 : :
3354 : : /*
3355 : : * The checkpointer and the background writer are active from the start,
3356 : : * until shutdown is initiated.
3357 : : *
3358 : : * (If the checkpointer is not running when we enter the
3359 : : * PM_WAIT_XLOG_SHUTDOWN state, it is launched one more time to perform
3360 : : * the shutdown checkpoint. That's done in PostmasterStateMachine(), not
3361 : : * here.)
3362 : : */
3363 [ + + + + ]: 153619 : if (pmState == PM_RUN || pmState == PM_RECOVERY ||
3364 [ + + + + ]: 10234 : pmState == PM_HOT_STANDBY || pmState == PM_STARTUP)
3365 : : {
3366 [ + + ]: 146359 : if (CheckpointerPMChild == NULL)
3367 : 5 : CheckpointerPMChild = StartChildProcess(B_CHECKPOINTER);
3368 [ + + ]: 146359 : if (BgWriterPMChild == NULL)
3369 : 5 : BgWriterPMChild = StartChildProcess(B_BG_WRITER);
3370 : : }
3371 : :
3372 : : /*
3373 : : * WAL writer is needed only in normal operation (else we cannot be
3374 : : * writing any new WAL).
3375 : : */
3376 [ + + + + ]: 153619 : if (WalWriterPMChild == NULL && pmState == PM_RUN)
3377 : 917 : WalWriterPMChild = StartChildProcess(B_WAL_WRITER);
3378 : :
3379 : : /*
3380 : : * We don't want autovacuum to run in binary upgrade mode because
3381 : : * autovacuum might update relfrozenxid for empty tables before the
3382 : : * physical files are put in place.
3383 : : */
3384 [ + + + + : 165377 : if (!IsBinaryUpgrade && AutoVacLauncherPMChild == NULL &&
+ + ]
3385 [ - + ]: 16961 : (AutoVacuumingActive() || start_autovac_launcher) &&
3386 [ + + ]: 6555 : pmState == PM_RUN)
3387 : : {
3388 : 756 : AutoVacLauncherPMChild = StartChildProcess(B_AUTOVAC_LAUNCHER);
3389 [ + - ]: 756 : if (AutoVacLauncherPMChild != NULL)
3390 : 756 : start_autovac_launcher = false; /* signal processed */
3391 : : }
3392 : :
3393 : : /*
3394 : : * If WAL archiving is enabled always, we are allowed to start archiver
3395 : : * even during recovery.
3396 : : */
3397 [ + + ]: 153619 : if (PgArchPMChild == NULL &&
3398 [ + + + + ]: 152361 : ((XLogArchivingActive() && pmState == PM_RUN) ||
3399 [ + + + - : 152361 : (XLogArchivingAlways() && (pmState == PM_RECOVERY || pmState == PM_HOT_STANDBY))) &&
- + + - ]
3400 : 58 : PgArchCanRestart())
3401 : 58 : PgArchPMChild = StartChildProcess(B_ARCHIVER);
3402 : :
3403 : : /*
3404 : : * If we need to start a slot sync worker, try to do that now
3405 : : *
3406 : : * We allow to start the slot sync worker when we are on a hot standby,
3407 : : * fast or immediate shutdown is not in progress, slot sync parameters are
3408 : : * configured correctly, and it is the first time of worker's launch, or
3409 : : * enough time has passed since the worker was launched last.
3410 : : */
3411 [ + + + + ]: 153619 : if (SlotSyncWorkerPMChild == NULL && pmState == PM_HOT_STANDBY &&
3412 [ + - + + : 2729 : Shutdown <= SmartShutdown && sync_replication_slots &&
+ + ]
3413 [ + + ]: 37 : ValidateSlotSyncParams(LOG) && SlotSyncWorkerCanRestart())
3414 : 6 : SlotSyncWorkerPMChild = StartChildProcess(B_SLOTSYNC_WORKER);
3415 : :
3416 : : /*
3417 : : * If we need to start a WAL receiver, try to do that now
3418 : : *
3419 : : * Note: if a walreceiver process is already running, it might seem that
3420 : : * we should clear WalReceiverRequested. However, there's a race
3421 : : * condition if the walreceiver terminates and the startup process
3422 : : * immediately requests a new one: it's quite possible to get the signal
3423 : : * for the request before reaping the dead walreceiver process. Better to
3424 : : * risk launching an extra walreceiver than to miss launching one we need.
3425 : : * (The walreceiver code has logic to recognize that it should go away if
3426 : : * not needed.)
3427 : : */
3428 [ + + ]: 153619 : if (WalReceiverRequested)
3429 : : {
3430 [ + + ]: 439 : if (WalReceiverPMChild == NULL &&
3431 [ + + + + ]: 315 : (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
3432 [ + + ]: 312 : pmState == PM_HOT_STANDBY) &&
3433 [ + - ]: 299 : Shutdown <= SmartShutdown)
3434 : : {
3435 : 299 : WalReceiverPMChild = StartChildProcess(B_WAL_RECEIVER);
3436 [ + - ]: 299 : if (WalReceiverPMChild != NULL)
3437 : 299 : WalReceiverRequested = false;
3438 : : /* else leave the flag set, so we'll try again later */
3439 : : }
3440 : : }
3441 : :
3442 : : /* If we need to start a WAL summarizer, try to do that now */
3443 [ + + + + ]: 153619 : if (summarize_wal && WalSummarizerPMChild == NULL &&
3444 [ + + + + ]: 117 : (pmState == PM_RUN || pmState == PM_HOT_STANDBY) &&
3445 [ + - ]: 24 : Shutdown <= SmartShutdown)
3446 : 24 : WalSummarizerPMChild = StartChildProcess(B_WAL_SUMMARIZER);
3447 : :
3448 : : /* Get other worker processes running, if needed */
3449 [ + + + + ]: 153619 : if (StartWorkerNeeded || HaveCrashedWorker)
3450 : 8417 : maybe_start_bgworkers();
3451 : 153619 : }
3452 : :
3453 : : /*
3454 : : * Return string representation of signal.
3455 : : *
3456 : : * Because this is only implemented for signals we already rely on in this
3457 : : * file we don't need to deal with unimplemented or same-numeric-value signals
3458 : : * (as we'd e.g. have to for EWOULDBLOCK / EAGAIN).
3459 : : */
3460 : : static const char *
3461 : 60 : pm_signame(int signal)
3462 : : {
3463 : : #define PM_TOSTR_CASE(sym) case sym: return #sym
3464 [ - - - + : 60 : switch (signal)
- - + - +
- ]
3465 : : {
3466 : 0 : PM_TOSTR_CASE(SIGABRT);
3467 : 0 : PM_TOSTR_CASE(SIGCHLD);
3468 : 0 : PM_TOSTR_CASE(SIGHUP);
3469 : 7 : PM_TOSTR_CASE(SIGINT);
3470 : 0 : PM_TOSTR_CASE(SIGKILL);
3471 : 0 : PM_TOSTR_CASE(SIGQUIT);
3472 : 38 : PM_TOSTR_CASE(SIGTERM);
3473 : 0 : PM_TOSTR_CASE(SIGUSR1);
3474 : 15 : PM_TOSTR_CASE(SIGUSR2);
3475 : 0 : default:
3476 : : /* all signals sent by postmaster should be listed here */
3477 : : Assert(false);
3478 : 0 : return "(unknown)";
3479 : : }
3480 : : #undef PM_TOSTR_CASE
3481 : :
3482 : : return ""; /* silence compiler */
3483 : : }
3484 : :
3485 : : /*
3486 : : * Send a signal to a postmaster child process
3487 : : *
3488 : : * On systems that have setsid(), each child process sets itself up as a
3489 : : * process group leader. For signals that are generally interpreted in the
3490 : : * appropriate fashion, we signal the entire process group not just the
3491 : : * direct child process. This allows us to, for example, SIGQUIT a blocked
3492 : : * archive_recovery script, or SIGINT a script being run by a backend via
3493 : : * system().
3494 : : *
3495 : : * There is a race condition for recently-forked children: they might not
3496 : : * have executed setsid() yet. So we signal the child directly as well as
3497 : : * the group. We assume such a child will handle the signal before trying
3498 : : * to spawn any grandchild processes. We also assume that signaling the
3499 : : * child twice will not cause any problems.
3500 : : */
3501 : : static void
3502 : 11943 : signal_child(PMChild *pmchild, int signal)
3503 : : {
3504 : 11943 : pid_t pid = pmchild->pid;
3505 : :
3506 [ + + ]: 11943 : ereport(DEBUG3,
3507 : : (errmsg_internal("sending signal %d/%s to %s process with pid %d",
3508 : : signal, pm_signame(signal),
3509 : : GetBackendTypeDesc(pmchild->bkend_type),
3510 : : (int) pmchild->pid)));
3511 : :
3512 [ - + ]: 11943 : if (kill(pid, signal) < 0)
3513 [ # # ]: 0 : elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
3514 : : #ifdef HAVE_SETSID
3515 [ + + ]: 11943 : switch (signal)
3516 : : {
3517 : 6661 : case SIGINT:
3518 : : case SIGTERM:
3519 : : case SIGQUIT:
3520 : : case SIGKILL:
3521 : : case SIGABRT:
3522 [ + + ]: 6661 : if (kill(-pid, signal) < 0)
3523 [ - + ]: 3 : elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) (-pid), signal);
3524 : 6661 : break;
3525 : 5282 : default:
3526 : 5282 : break;
3527 : : }
3528 : : #endif
3529 : 11943 : }
3530 : :
3531 : : /*
3532 : : * Send a signal to the targeted children.
3533 : : */
3534 : : static bool
3535 : 3617 : SignalChildren(int signal, BackendTypeMask targetMask)
3536 : : {
3537 : : dlist_iter iter;
3538 : 3617 : bool signaled = false;
3539 : :
3540 [ + - + + ]: 17334 : dlist_foreach(iter, &ActiveChildList)
3541 : : {
3542 : 13717 : PMChild *bp = dlist_container(PMChild, elem, iter.cur);
3543 : :
3544 : : /*
3545 : : * If we need to distinguish between B_BACKEND and B_WAL_SENDER, check
3546 : : * if any B_BACKEND backends have recently announced that they are
3547 : : * actually WAL senders.
3548 : : */
3549 [ + + ]: 13717 : if (btmask_contains(targetMask, B_WAL_SENDER) != btmask_contains(targetMask, B_BACKEND) &&
3550 [ + + ]: 7242 : bp->bkend_type == B_BACKEND)
3551 : : {
3552 [ + + ]: 603 : if (IsPostmasterChildWalSender(bp->child_slot))
3553 : 52 : bp->bkend_type = B_WAL_SENDER;
3554 : : }
3555 : :
3556 [ + + ]: 13717 : if (!btmask_contains(targetMask, bp->bkend_type))
3557 : 4840 : continue;
3558 : :
3559 : 8877 : signal_child(bp, signal);
3560 : 8877 : signaled = true;
3561 : : }
3562 : 3617 : return signaled;
3563 : : }
3564 : :
3565 : : /*
3566 : : * Send a termination signal to children. This considers all of our children
3567 : : * processes, except syslogger.
3568 : : */
3569 : : static void
3570 : 383 : TerminateChildren(int signal)
3571 : : {
3572 : 383 : SignalChildren(signal, btmask_all_except(B_LOGGER));
3573 [ + + ]: 383 : if (StartupPMChild != NULL)
3574 : : {
3575 [ - + - - : 54 : if (signal == SIGQUIT || signal == SIGKILL || signal == SIGABRT)
- - ]
3576 : 54 : StartupStatus = STARTUP_SIGNALED;
3577 : : }
3578 : 383 : }
3579 : :
3580 : : /*
3581 : : * BackendStartup -- start backend process
3582 : : *
3583 : : * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
3584 : : *
3585 : : * Note: if you change this code, also consider StartAutovacuumWorker and
3586 : : * StartBackgroundWorker.
3587 : : */
3588 : : static int
3589 : 16060 : BackendStartup(ClientSocket *client_sock)
3590 : : {
3591 : 16060 : PMChild *bn = NULL;
3592 : : pid_t pid;
3593 : : BackendStartupData startup_data;
3594 : : CAC_state cac;
3595 : :
3596 : : /*
3597 : : * Capture time that Postmaster got a socket from accept (for logging
3598 : : * connection establishment and setup total duration).
3599 : : */
3600 : 16060 : startup_data.socket_created = GetCurrentTimestamp();
3601 : :
3602 : : /*
3603 : : * Allocate and assign the child slot. Note we must do this before
3604 : : * forking, so that we can handle failures (out of memory or child-process
3605 : : * slots) cleanly.
3606 : : */
3607 : 16060 : cac = canAcceptConnections(B_BACKEND);
3608 [ + + ]: 16060 : if (cac == CAC_OK)
3609 : : {
3610 : : /* Can change later to B_WAL_SENDER */
3611 : 15814 : bn = AssignPostmasterChildSlot(B_BACKEND);
3612 [ + + ]: 15814 : if (!bn)
3613 : : {
3614 : : /*
3615 : : * Too many regular child processes; launch a dead-end child
3616 : : * process instead.
3617 : : */
3618 : 28 : cac = CAC_TOOMANY;
3619 : : }
3620 : : }
3621 [ + + ]: 16060 : if (!bn)
3622 : : {
3623 : 274 : bn = AllocDeadEndChild();
3624 [ - + ]: 274 : if (!bn)
3625 : : {
3626 [ # # ]: 0 : ereport(LOG,
3627 : : (errcode(ERRCODE_OUT_OF_MEMORY),
3628 : : errmsg("out of memory")));
3629 : 0 : return STATUS_ERROR;
3630 : : }
3631 : : }
3632 : :
3633 : : /* Pass down canAcceptConnections state */
3634 : 16060 : startup_data.canAcceptConnections = cac;
3635 : 16060 : bn->rw = NULL;
3636 : :
3637 : : /* Hasn't asked to be notified about any bgworkers yet */
3638 : 16060 : bn->bgworker_notify = false;
3639 : :
3640 : 16060 : pid = postmaster_child_launch(bn->bkend_type, bn->child_slot,
3641 : : &startup_data, sizeof(startup_data),
3642 : : client_sock);
3643 [ - + ]: 16060 : if (pid < 0)
3644 : : {
3645 : : /* in parent, fork failed */
3646 : 0 : int save_errno = errno;
3647 : :
3648 : 0 : (void) ReleasePostmasterChildSlot(bn);
3649 : 0 : errno = save_errno;
3650 [ # # ]: 0 : ereport(LOG,
3651 : : (errmsg("could not fork new process for connection: %m")));
3652 : 0 : report_fork_failure_to_client(client_sock, save_errno);
3653 : 0 : return STATUS_ERROR;
3654 : : }
3655 : :
3656 : : /* in parent, successful fork */
3657 [ + + ]: 16060 : ereport(DEBUG2,
3658 : : (errmsg_internal("forked new %s, pid=%d socket=%d",
3659 : : GetBackendTypeDesc(bn->bkend_type),
3660 : : (int) pid, (int) client_sock->sock)));
3661 : :
3662 : : /*
3663 : : * Everything's been successful, it's safe to add this backend to our list
3664 : : * of backends.
3665 : : */
3666 : 16060 : bn->pid = pid;
3667 : 16060 : return STATUS_OK;
3668 : : }
3669 : :
3670 : : /*
3671 : : * Try to report backend fork() failure to client before we close the
3672 : : * connection. Since we do not care to risk blocking the postmaster on
3673 : : * this connection, we set the connection to non-blocking and try only once.
3674 : : *
3675 : : * This is grungy special-purpose code; we cannot use backend libpq since
3676 : : * it's not up and running.
3677 : : */
3678 : : static void
3679 : 0 : report_fork_failure_to_client(ClientSocket *client_sock, int errnum)
3680 : : {
3681 : : char buffer[1000];
3682 : : int rc;
3683 : :
3684 : : /* Format the error message packet (always V2 protocol) */
3685 : 0 : snprintf(buffer, sizeof(buffer), "E%s%s\n",
3686 : : _("could not fork new process for connection: "),
3687 : : strerror(errnum));
3688 : :
3689 : : /* Set port to non-blocking. Don't do send() if this fails */
3690 [ # # ]: 0 : if (!pg_set_noblock(client_sock->sock))
3691 : 0 : return;
3692 : :
3693 : : /* We'll retry after EINTR, but ignore all other failures */
3694 : : do
3695 : : {
3696 : 0 : rc = send(client_sock->sock, buffer, strlen(buffer) + 1, 0);
3697 [ # # # # ]: 0 : } while (rc < 0 && errno == EINTR);
3698 : : }
3699 : :
3700 : : /*
3701 : : * ExitPostmaster -- cleanup
3702 : : *
3703 : : * Do NOT call exit() directly --- always go through here!
3704 : : */
3705 : : static void
3706 : 1049 : ExitPostmaster(int status)
3707 : : {
3708 : : #ifdef HAVE_PTHREAD_IS_THREADED_NP
3709 : :
3710 : : /*
3711 : : * There is no known cause for a postmaster to become multithreaded after
3712 : : * startup. However, we might reach here via an error exit before
3713 : : * reaching the test in PostmasterMain, so provide the same hint as there.
3714 : : * This message uses LOG level, because an unclean shutdown at this point
3715 : : * would usually not look much different from a clean shutdown.
3716 : : */
3717 : : if (pthread_is_threaded_np() != 0)
3718 : : ereport(LOG,
3719 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3720 : : errmsg("postmaster became multithreaded"),
3721 : : errhint("Set the LC_ALL environment variable to a valid locale.")));
3722 : : #endif
3723 : :
3724 : : /* should cleanup shared memory and kill all backends */
3725 : :
3726 : : /*
3727 : : * Not sure of the semantics here. When the Postmaster dies, should the
3728 : : * backends all be killed? probably not.
3729 : : *
3730 : : * MUST -- vadim 05-10-1999
3731 : : */
3732 : :
3733 : 1049 : proc_exit(status);
3734 : : }
3735 : :
3736 : : /*
3737 : : * Handle pmsignal conditions representing requests from backends,
3738 : : * and check for promote and logrotate requests from pg_ctl.
3739 : : */
3740 : : static void
3741 : 110900 : process_pm_pmsignal(void)
3742 : : {
3743 : 110900 : bool request_state_update = false;
3744 : :
3745 : 110900 : pending_pm_pmsignal = false;
3746 : :
3747 [ + + ]: 110900 : ereport(DEBUG2,
3748 : : (errmsg_internal("postmaster received pmsignal signal")));
3749 : :
3750 : : /*
3751 : : * RECOVERY_STARTED and BEGIN_HOT_STANDBY signals are ignored in
3752 : : * unexpected states. If the startup process quickly starts up, completes
3753 : : * recovery, exits, we might process the death of the startup process
3754 : : * first. We don't want to go back to recovery in that case.
3755 : : */
3756 [ + + ]: 110900 : if (CheckPostmasterSignal(PMSIGNAL_RECOVERY_STARTED) &&
3757 [ + - + - ]: 291 : pmState == PM_STARTUP && Shutdown == NoShutdown)
3758 : : {
3759 : : /* WAL redo has started. We're out of reinitialization. */
3760 : 291 : FatalError = false;
3761 : 291 : AbortStartTime = 0;
3762 : 291 : reachedConsistency = false;
3763 : :
3764 : : /*
3765 : : * Start the archiver if we're responsible for (re-)archiving received
3766 : : * files.
3767 : : */
3768 : : Assert(PgArchPMChild == NULL);
3769 [ + + ]: 291 : if (XLogArchivingAlways())
3770 : 5 : PgArchPMChild = StartChildProcess(B_ARCHIVER);
3771 : :
3772 : : /*
3773 : : * If we aren't planning to enter hot standby mode later, treat
3774 : : * RECOVERY_STARTED as meaning we're out of startup, and report status
3775 : : * accordingly.
3776 : : */
3777 [ + + ]: 291 : if (!EnableHotStandby)
3778 : : {
3779 : 2 : AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_STANDBY);
3780 : : #ifdef USE_SYSTEMD
3781 : : sd_notify(0, "READY=1");
3782 : : #endif
3783 : : }
3784 : :
3785 : 291 : UpdatePMState(PM_RECOVERY);
3786 : : }
3787 : :
3788 [ + + ]: 110900 : if (CheckPostmasterSignal(PMSIGNAL_RECOVERY_CONSISTENT) &&
3789 [ + - + - ]: 199 : pmState == PM_RECOVERY && Shutdown == NoShutdown)
3790 : : {
3791 : 199 : reachedConsistency = true;
3792 : : }
3793 : :
3794 [ + + ]: 110900 : if (CheckPostmasterSignal(PMSIGNAL_BEGIN_HOT_STANDBY) &&
3795 [ + - + - ]: 189 : (pmState == PM_RECOVERY && Shutdown == NoShutdown))
3796 : : {
3797 [ + - ]: 189 : ereport(LOG,
3798 : : (errmsg("database system is ready to accept read-only connections")));
3799 : :
3800 : : /* Report status */
3801 : 189 : AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_READY);
3802 : : #ifdef USE_SYSTEMD
3803 : : sd_notify(0, "READY=1");
3804 : : #endif
3805 : :
3806 : 189 : UpdatePMState(PM_HOT_STANDBY);
3807 : 189 : connsAllowed = true;
3808 : :
3809 : : /* Some workers may be scheduled to start now */
3810 : 189 : StartWorkerNeeded = true;
3811 : : }
3812 : :
3813 : : /* Process IO worker start requests. */
3814 : 110900 : if (CheckPostmasterSignal(PMSIGNAL_IO_WORKER_GROW))
3815 : : {
3816 : : /*
3817 : : * No local flag, as the state is exposed through pgaio_worker_*()
3818 : : * functions. This signal is received on potentially actionable level
3819 : : * changes, so that maybe_start_io_workers() will run.
3820 : : */
3821 : : }
3822 : :
3823 : : /* Process background worker state changes. */
3824 [ + + ]: 110900 : if (CheckPostmasterSignal(PMSIGNAL_BACKGROUND_WORKER_CHANGE))
3825 : : {
3826 : : /* Accept new worker requests only if not stopping. */
3827 : 1770 : BackgroundWorkerStateChange(pmState < PM_STOP_BACKENDS);
3828 : 1770 : StartWorkerNeeded = true;
3829 : : }
3830 : :
3831 : : /* Tell syslogger to rotate logfile if requested */
3832 [ + + ]: 110900 : if (SysLoggerPMChild != NULL)
3833 : : {
3834 [ + + ]: 2 : if (CheckLogrotateSignal())
3835 : : {
3836 : 1 : signal_child(SysLoggerPMChild, SIGUSR1);
3837 : 1 : RemoveLogrotateSignalFiles();
3838 : : }
3839 [ - + ]: 1 : else if (CheckPostmasterSignal(PMSIGNAL_ROTATE_LOGFILE))
3840 : : {
3841 : 0 : signal_child(SysLoggerPMChild, SIGUSR1);
3842 : : }
3843 : : }
3844 : :
3845 [ + + ]: 110900 : if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER) &&
3846 [ + - + - ]: 104992 : Shutdown <= SmartShutdown && pmState < PM_STOP_BACKENDS)
3847 : : {
3848 : : /*
3849 : : * Start one iteration of the autovacuum daemon, even if autovacuuming
3850 : : * is nominally not enabled. This is so we can have an active defense
3851 : : * against transaction ID wraparound. We set a flag for the main loop
3852 : : * to do it rather than trying to do it here --- this is because the
3853 : : * autovac process itself may send the signal, and we want to handle
3854 : : * that by launching another iteration as soon as the current one
3855 : : * completes.
3856 : : */
3857 : 104992 : start_autovac_launcher = true;
3858 : : }
3859 : :
3860 [ + + ]: 110900 : if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER) &&
3861 [ + - + - ]: 1654 : Shutdown <= SmartShutdown && pmState < PM_STOP_BACKENDS)
3862 : : {
3863 : : /* The autovacuum launcher wants us to start a worker process. */
3864 : 1654 : StartAutovacuumWorker();
3865 : : }
3866 : :
3867 [ + + ]: 110900 : if (CheckPostmasterSignal(PMSIGNAL_START_WALRECEIVER))
3868 : : {
3869 : : /* Startup Process wants us to start the walreceiver process. */
3870 : 305 : WalReceiverRequested = true;
3871 : : }
3872 : :
3873 [ + + ]: 110900 : if (CheckPostmasterSignal(PMSIGNAL_XLOG_IS_SHUTDOWN))
3874 : : {
3875 : : /* Checkpointer completed the shutdown checkpoint */
3876 [ + - ]: 669 : if (pmState == PM_WAIT_XLOG_SHUTDOWN)
3877 : : {
3878 : : /*
3879 : : * If we have an archiver subprocess, tell it to do a last archive
3880 : : * cycle and quit. Likewise, if we have walsender processes, tell
3881 : : * them to send any remaining WAL and quit.
3882 : : */
3883 : : Assert(Shutdown > NoShutdown);
3884 : :
3885 : : /* Waken archiver for the last time */
3886 [ + + ]: 669 : if (PgArchPMChild != NULL)
3887 : 19 : signal_child(PgArchPMChild, SIGUSR2);
3888 : :
3889 : : /*
3890 : : * Waken walsenders for the last time. No regular backends should
3891 : : * be around anymore.
3892 : : */
3893 : 669 : SignalChildren(SIGUSR2, btmask(B_WAL_SENDER));
3894 : :
3895 : 669 : UpdatePMState(PM_WAIT_XLOG_ARCHIVAL);
3896 : : }
3897 [ # # # # ]: 0 : else if (!FatalError && Shutdown != ImmediateShutdown)
3898 : : {
3899 : : /*
3900 : : * Checkpointer only ought to perform the shutdown checkpoint
3901 : : * during shutdown. If somehow checkpointer did so in another
3902 : : * situation, we have no choice but to crash-restart.
3903 : : *
3904 : : * It's possible however that we get PMSIGNAL_XLOG_IS_SHUTDOWN
3905 : : * outside of PM_WAIT_XLOG_SHUTDOWN if an orderly shutdown was
3906 : : * "interrupted" by a crash or an immediate shutdown.
3907 : : */
3908 [ # # ]: 0 : ereport(LOG,
3909 : : (errmsg("WAL was shut down unexpectedly")));
3910 : :
3911 : : /*
3912 : : * Doesn't seem likely to help to take send_abort_for_crash into
3913 : : * account here.
3914 : : */
3915 : 0 : HandleFatalError(PMQUIT_FOR_CRASH, false);
3916 : : }
3917 : :
3918 : : /*
3919 : : * Need to run PostmasterStateMachine() to check if we already can go
3920 : : * to the next state.
3921 : : */
3922 : 669 : request_state_update = true;
3923 : : }
3924 : :
3925 : : /*
3926 : : * Try to advance postmaster's state machine, if a child requests it.
3927 : : */
3928 [ + + ]: 110900 : if (CheckPostmasterSignal(PMSIGNAL_ADVANCE_STATE_MACHINE))
3929 : : {
3930 : 1432 : request_state_update = true;
3931 : : }
3932 : :
3933 : : /*
3934 : : * Be careful about the order of this action relative to this function's
3935 : : * other actions. Generally, this should be after other actions, in case
3936 : : * they have effects PostmasterStateMachine would need to know about.
3937 : : * However, we should do it before the CheckPromoteSignal step, which
3938 : : * cannot have any (immediate) effect on the state machine, but does
3939 : : * depend on what state we're in now.
3940 : : */
3941 [ + + ]: 110900 : if (request_state_update)
3942 : : {
3943 : 2101 : PostmasterStateMachine();
3944 : : }
3945 : :
3946 [ + + ]: 110900 : if (StartupPMChild != NULL &&
3947 [ + + + + ]: 749 : (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
3948 [ + + + + ]: 1279 : pmState == PM_HOT_STANDBY) &&
3949 : 748 : CheckPromoteSignal())
3950 : : {
3951 : : /*
3952 : : * Tell startup process to finish recovery.
3953 : : *
3954 : : * Leave the promote signal file in place and let the Startup process
3955 : : * do the unlink.
3956 : : */
3957 : 58 : signal_child(StartupPMChild, SIGUSR2);
3958 : : }
3959 : 110900 : }
3960 : :
3961 : : /*
3962 : : * Dummy signal handler
3963 : : *
3964 : : * We use this for signals that we don't actually use in the postmaster,
3965 : : * but we do use in backends. If we were to PG_SIG_IGN such signals in the
3966 : : * postmaster, then a newly started backend might drop a signal that arrives
3967 : : * before it's able to reconfigure its signal processing. (See notes in
3968 : : * tcop/postgres.c.)
3969 : : */
3970 : : static void
3971 : 0 : dummy_handler(SIGNAL_ARGS)
3972 : : {
3973 : 0 : }
3974 : :
3975 : : /*
3976 : : * Count up number of child processes of specified types.
3977 : : */
3978 : : static int
3979 : 7460 : CountChildren(BackendTypeMask targetMask)
3980 : : {
3981 : : dlist_iter iter;
3982 : 7460 : int cnt = 0;
3983 : :
3984 [ + - + + ]: 37750 : dlist_foreach(iter, &ActiveChildList)
3985 : : {
3986 : 30290 : PMChild *bp = dlist_container(PMChild, elem, iter.cur);
3987 : :
3988 : : /*
3989 : : * If we need to distinguish between B_BACKEND and B_WAL_SENDER, check
3990 : : * if any B_BACKEND backends have recently announced that they are
3991 : : * actually WAL senders.
3992 : : */
3993 [ + + ]: 30290 : if (btmask_contains(targetMask, B_WAL_SENDER) != btmask_contains(targetMask, B_BACKEND) &&
3994 [ + + ]: 20175 : bp->bkend_type == B_BACKEND)
3995 : : {
3996 [ - + ]: 976 : if (IsPostmasterChildWalSender(bp->child_slot))
3997 : 0 : bp->bkend_type = B_WAL_SENDER;
3998 : : }
3999 : :
4000 [ + + ]: 30290 : if (!btmask_contains(targetMask, bp->bkend_type))
4001 : 13932 : continue;
4002 : :
4003 [ - + ]: 16358 : ereport(DEBUG4,
4004 : : (errmsg_internal("%s process %d is still running",
4005 : : GetBackendTypeDesc(bp->bkend_type), (int) bp->pid)));
4006 : :
4007 : 16358 : cnt++;
4008 : : }
4009 : 7460 : return cnt;
4010 : : }
4011 : :
4012 : :
4013 : : /*
4014 : : * StartChildProcess -- start an auxiliary process for the postmaster
4015 : : *
4016 : : * "type" determines what kind of child will be started. All child types
4017 : : * initially go to AuxiliaryProcessMain, which will handle common setup.
4018 : : *
4019 : : * Return value of StartChildProcess is subprocess' PMChild entry, or NULL on
4020 : : * failure.
4021 : : */
4022 : : static PMChild *
4023 : 9028 : StartChildProcess(BackendType type)
4024 : : {
4025 : : PMChild *pmchild;
4026 : : pid_t pid;
4027 : :
4028 : 9028 : pmchild = AssignPostmasterChildSlot(type);
4029 [ - + ]: 9028 : if (!pmchild)
4030 : : {
4031 [ # # ]: 0 : if (type == B_AUTOVAC_WORKER)
4032 [ # # ]: 0 : ereport(LOG,
4033 : : (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
4034 : : errmsg("no slot available for new autovacuum worker process")));
4035 : : else
4036 : : {
4037 : : /* shouldn't happen because we allocate enough slots */
4038 [ # # ]: 0 : elog(LOG, "no postmaster child slot available for aux process");
4039 : : }
4040 : 0 : return NULL;
4041 : : }
4042 : :
4043 : 9028 : pid = postmaster_child_launch(type, pmchild->child_slot, NULL, 0, NULL);
4044 [ - + ]: 9028 : if (pid < 0)
4045 : : {
4046 : : /* in parent, fork failed */
4047 : 0 : ReleasePostmasterChildSlot(pmchild);
4048 [ # # ]: 0 : ereport(LOG,
4049 : : (errmsg("could not fork \"%s\" process: %m", PostmasterChildName(type))));
4050 : :
4051 : : /*
4052 : : * fork failure is fatal during startup, but there's no need to choke
4053 : : * immediately if starting other child types fails.
4054 : : */
4055 [ # # ]: 0 : if (type == B_STARTUP)
4056 : 0 : ExitPostmaster(1);
4057 : 0 : return NULL;
4058 : : }
4059 : :
4060 : : /* in parent, successful fork */
4061 : 9028 : pmchild->pid = pid;
4062 : 9028 : return pmchild;
4063 : : }
4064 : :
4065 : : /*
4066 : : * StartSysLogger -- start the syslogger process
4067 : : */
4068 : : void
4069 : 1 : StartSysLogger(void)
4070 : : {
4071 : : Assert(SysLoggerPMChild == NULL);
4072 : :
4073 : 1 : SysLoggerPMChild = AssignPostmasterChildSlot(B_LOGGER);
4074 [ - + ]: 1 : if (!SysLoggerPMChild)
4075 [ # # ]: 0 : elog(PANIC, "no postmaster child slot available for syslogger");
4076 : 1 : SysLoggerPMChild->pid = SysLogger_Start(SysLoggerPMChild->child_slot);
4077 [ - + ]: 1 : if (SysLoggerPMChild->pid == 0)
4078 : : {
4079 : 0 : ReleasePostmasterChildSlot(SysLoggerPMChild);
4080 : 0 : SysLoggerPMChild = NULL;
4081 : : }
4082 : 1 : }
4083 : :
4084 : : /*
4085 : : * StartAutovacuumWorker
4086 : : * Start an autovac worker process.
4087 : : *
4088 : : * This function is here because it enters the resulting PID into the
4089 : : * postmaster's private backends list.
4090 : : *
4091 : : * NB -- this code very roughly matches BackendStartup.
4092 : : */
4093 : : static void
4094 : 1654 : StartAutovacuumWorker(void)
4095 : : {
4096 : : PMChild *bn;
4097 : :
4098 : : /*
4099 : : * If not in condition to run a process, don't try, but handle it like a
4100 : : * fork failure. This does not normally happen, since the signal is only
4101 : : * supposed to be sent by autovacuum launcher when it's OK to do it, but
4102 : : * we have to check to avoid race-condition problems during DB state
4103 : : * changes.
4104 : : */
4105 [ + - ]: 1654 : if (canAcceptConnections(B_AUTOVAC_WORKER) == CAC_OK)
4106 : : {
4107 : 1654 : bn = StartChildProcess(B_AUTOVAC_WORKER);
4108 [ + - ]: 1654 : if (bn)
4109 : : {
4110 : 1654 : bn->bgworker_notify = false;
4111 : 1654 : bn->rw = NULL;
4112 : 1654 : return;
4113 : : }
4114 : : else
4115 : : {
4116 : : /*
4117 : : * fork failed, fall through to report -- actual error message was
4118 : : * logged by StartChildProcess
4119 : : */
4120 : : }
4121 : : }
4122 : :
4123 : : /*
4124 : : * Report the failure to the launcher, if it's running. (If it's not, we
4125 : : * might not even be connected to shared memory, so don't try to call
4126 : : * AutoVacWorkerFailed.) Note that we also need to signal it so that it
4127 : : * responds to the condition, but we don't do that here, instead waiting
4128 : : * for ServerLoop to do it. This way we avoid a ping-pong signaling in
4129 : : * quick succession between the autovac launcher and postmaster in case
4130 : : * things get ugly.
4131 : : */
4132 [ # # ]: 0 : if (AutoVacLauncherPMChild != NULL)
4133 : : {
4134 : 0 : AutoVacWorkerFailed();
4135 : 0 : avlauncher_needs_signal = true;
4136 : : }
4137 : : }
4138 : :
4139 : :
4140 : : /*
4141 : : * Create the opts file
4142 : : */
4143 : : static bool
4144 : 1047 : CreateOptsFile(int argc, char *argv[], char *fullprogname)
4145 : : {
4146 : : FILE *fp;
4147 : : int i;
4148 : :
4149 : : #define OPTS_FILE "postmaster.opts"
4150 : :
4151 [ - + ]: 1047 : if ((fp = fopen(OPTS_FILE, "w")) == NULL)
4152 : : {
4153 [ # # ]: 0 : ereport(LOG,
4154 : : (errcode_for_file_access(),
4155 : : errmsg("could not create file \"%s\": %m", OPTS_FILE)));
4156 : 0 : return false;
4157 : : }
4158 : :
4159 : 1047 : fprintf(fp, "%s", fullprogname);
4160 [ + + ]: 5451 : for (i = 1; i < argc; i++)
4161 : 4404 : fprintf(fp, " \"%s\"", argv[i]);
4162 : 1047 : fputs("\n", fp);
4163 : :
4164 [ - + ]: 1047 : if (fclose(fp))
4165 : : {
4166 [ # # ]: 0 : ereport(LOG,
4167 : : (errcode_for_file_access(),
4168 : : errmsg("could not write file \"%s\": %m", OPTS_FILE)));
4169 : 0 : return false;
4170 : : }
4171 : :
4172 : 1047 : return true;
4173 : : }
4174 : :
4175 : :
4176 : : /*
4177 : : * Start a new bgworker.
4178 : : * Starting time conditions must have been checked already.
4179 : : *
4180 : : * Returns true on success, false on failure.
4181 : : * In either case, update the RegisteredBgWorker's state appropriately.
4182 : : *
4183 : : * NB -- this code very roughly matches BackendStartup.
4184 : : */
4185 : : static bool
4186 : 3619 : StartBackgroundWorker(RegisteredBgWorker *rw)
4187 : : {
4188 : : PMChild *bn;
4189 : : pid_t worker_pid;
4190 : :
4191 : : Assert(rw->rw_pid == 0);
4192 : :
4193 : : /*
4194 : : * Allocate and assign the child slot. Note we must do this before
4195 : : * forking, so that we can handle failures (out of memory or child-process
4196 : : * slots) cleanly.
4197 : : *
4198 : : * Treat failure as though the worker had crashed. That way, the
4199 : : * postmaster will wait a bit before attempting to start it again; if we
4200 : : * tried again right away, most likely we'd find ourselves hitting the
4201 : : * same resource-exhaustion condition.
4202 : : */
4203 : 3619 : bn = AssignPostmasterChildSlot(B_BG_WORKER);
4204 [ - + ]: 3619 : if (bn == NULL)
4205 : : {
4206 [ # # ]: 0 : ereport(LOG,
4207 : : (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
4208 : : errmsg("no slot available for new background worker process")));
4209 : 0 : rw->rw_crashed_at = GetCurrentTimestamp();
4210 : 0 : return false;
4211 : : }
4212 : 3619 : bn->rw = rw;
4213 : 3619 : bn->bkend_type = B_BG_WORKER;
4214 : 3619 : bn->bgworker_notify = false;
4215 : :
4216 [ + + ]: 3619 : ereport(DEBUG1,
4217 : : (errmsg_internal("starting background worker process \"%s\"",
4218 : : rw->rw_worker.bgw_name)));
4219 : :
4220 : 3619 : worker_pid = postmaster_child_launch(B_BG_WORKER, bn->child_slot,
4221 : 3619 : &rw->rw_worker, sizeof(BackgroundWorker), NULL);
4222 [ - + ]: 3619 : if (worker_pid == -1)
4223 : : {
4224 : : /* in postmaster, fork failed ... */
4225 [ # # ]: 0 : ereport(LOG,
4226 : : (errmsg("could not fork background worker process: %m")));
4227 : : /* undo what AssignPostmasterChildSlot did */
4228 : 0 : ReleasePostmasterChildSlot(bn);
4229 : :
4230 : : /* mark entry as crashed, so we'll try again later */
4231 : 0 : rw->rw_crashed_at = GetCurrentTimestamp();
4232 : 0 : return false;
4233 : : }
4234 : :
4235 : : /* in postmaster, fork successful ... */
4236 : 3619 : rw->rw_pid = worker_pid;
4237 : 3619 : bn->pid = rw->rw_pid;
4238 : 3619 : ReportBackgroundWorkerPID(rw);
4239 : 3619 : return true;
4240 : : }
4241 : :
4242 : : /*
4243 : : * Does the current postmaster state require starting a worker with the
4244 : : * specified start_time?
4245 : : */
4246 : : static bool
4247 : 4796 : bgworker_should_start_now(BgWorkerStartTime start_time)
4248 : : {
4249 [ - + + + : 4796 : switch (pmState)
- ]
4250 : : {
4251 : 0 : case PM_NO_CHILDREN:
4252 : : case PM_WAIT_CHECKPOINTER:
4253 : : case PM_WAIT_DEAD_END:
4254 : : case PM_WAIT_XLOG_ARCHIVAL:
4255 : : case PM_WAIT_XLOG_SHUTDOWN:
4256 : : case PM_WAIT_IO_WORKERS:
4257 : : case PM_WAIT_BACKENDS:
4258 : : case PM_STOP_BACKENDS:
4259 : 0 : break;
4260 : :
4261 : 3619 : case PM_RUN:
4262 [ + + ]: 3619 : if (start_time == BgWorkerStart_RecoveryFinished)
4263 : 1618 : return true;
4264 : : pg_fallthrough;
4265 : :
4266 : : case PM_HOT_STANDBY:
4267 [ + + ]: 2186 : if (start_time == BgWorkerStart_ConsistentState)
4268 : 2001 : return true;
4269 : : pg_fallthrough;
4270 : :
4271 : : case PM_RECOVERY:
4272 : : case PM_STARTUP:
4273 : : case PM_INIT:
4274 [ - + ]: 1177 : if (start_time == BgWorkerStart_PostmasterStart)
4275 : 0 : return true;
4276 : : }
4277 : :
4278 : 1177 : return false;
4279 : : }
4280 : :
4281 : : /*
4282 : : * If the time is right, start background worker(s).
4283 : : *
4284 : : * As a side effect, the bgworker control variables are set or reset
4285 : : * depending on whether more workers may need to be started.
4286 : : *
4287 : : * We limit the number of workers started per call, to avoid consuming the
4288 : : * postmaster's attention for too long when many such requests are pending.
4289 : : * As long as StartWorkerNeeded is true, ServerLoop will not block and will
4290 : : * call this function again after dealing with any other issues.
4291 : : */
4292 : : static void
4293 : 9464 : maybe_start_bgworkers(void)
4294 : : {
4295 : : #define MAX_BGWORKERS_TO_LAUNCH 100
4296 : 9464 : int num_launched = 0;
4297 : 9464 : TimestampTz now = 0;
4298 : : dlist_mutable_iter iter;
4299 : :
4300 : : /*
4301 : : * During crash recovery, we have no need to be called until the state
4302 : : * transition out of recovery.
4303 : : */
4304 [ - + ]: 9464 : if (FatalError)
4305 : : {
4306 : 0 : StartWorkerNeeded = false;
4307 : 0 : HaveCrashedWorker = false;
4308 : 0 : return;
4309 : : }
4310 : :
4311 : : /* Don't need to be called again unless we find a reason for it below */
4312 : 9464 : StartWorkerNeeded = false;
4313 : 9464 : HaveCrashedWorker = false;
4314 : :
4315 [ + - + + ]: 25745 : dlist_foreach_modify(iter, &BackgroundWorkerList)
4316 : : {
4317 : : RegisteredBgWorker *rw;
4318 : :
4319 : 16281 : rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
4320 : :
4321 : : /* ignore if already running */
4322 [ + + ]: 16281 : if (rw->rw_pid != 0)
4323 : 8357 : continue;
4324 : :
4325 : : /* if marked for death, clean up and remove from list */
4326 [ - + ]: 7924 : if (rw->rw_terminate)
4327 : : {
4328 : 0 : ForgetBackgroundWorker(rw);
4329 : 0 : continue;
4330 : : }
4331 : :
4332 : : /*
4333 : : * If this worker has crashed previously, maybe it needs to be
4334 : : * restarted (unless on registration it specified it doesn't want to
4335 : : * be restarted at all). Check how long ago did a crash last happen.
4336 : : * If the last crash is too recent, don't start it right away; let it
4337 : : * be restarted once enough time has passed.
4338 : : */
4339 [ + + ]: 7924 : if (rw->rw_crashed_at != 0)
4340 : : {
4341 [ - + ]: 3128 : if (rw->rw_worker.bgw_restart_time == BGW_NEVER_RESTART)
4342 : 0 : {
4343 : : int notify_pid;
4344 : :
4345 : 0 : notify_pid = rw->rw_worker.bgw_notify_pid;
4346 : :
4347 : 0 : ForgetBackgroundWorker(rw);
4348 : :
4349 : : /* Report worker is gone now. */
4350 [ # # ]: 0 : if (notify_pid != 0)
4351 : 0 : kill(notify_pid, SIGUSR1);
4352 : :
4353 : 0 : continue;
4354 : : }
4355 : :
4356 : : /* read system time only when needed */
4357 [ + - ]: 3128 : if (now == 0)
4358 : 3128 : now = GetCurrentTimestamp();
4359 : :
4360 [ + - ]: 3128 : if (!TimestampDifferenceExceeds(rw->rw_crashed_at, now,
4361 : 3128 : rw->rw_worker.bgw_restart_time * 1000))
4362 : : {
4363 : : /* Set flag to remember that we have workers to start later */
4364 : 3128 : HaveCrashedWorker = true;
4365 : 3128 : continue;
4366 : : }
4367 : : }
4368 : :
4369 [ + + ]: 4796 : if (bgworker_should_start_now(rw->rw_worker.bgw_start_time))
4370 : : {
4371 : : /* reset crash time before trying to start worker */
4372 : 3619 : rw->rw_crashed_at = 0;
4373 : :
4374 : : /*
4375 : : * Try to start the worker.
4376 : : *
4377 : : * On failure, give up processing workers for now, but set
4378 : : * StartWorkerNeeded so we'll come back here on the next iteration
4379 : : * of ServerLoop to try again. (We don't want to wait, because
4380 : : * there might be additional ready-to-run workers.) We could set
4381 : : * HaveCrashedWorker as well, since this worker is now marked
4382 : : * crashed, but there's no need because the next run of this
4383 : : * function will do that.
4384 : : */
4385 [ - + ]: 3619 : if (!StartBackgroundWorker(rw))
4386 : : {
4387 : 0 : StartWorkerNeeded = true;
4388 : 0 : return;
4389 : : }
4390 : :
4391 : : /*
4392 : : * If we've launched as many workers as allowed, quit, but have
4393 : : * ServerLoop call us again to look for additional ready-to-run
4394 : : * workers. There might not be any, but we'll find out the next
4395 : : * time we run.
4396 : : */
4397 [ - + ]: 3619 : if (++num_launched >= MAX_BGWORKERS_TO_LAUNCH)
4398 : : {
4399 : 0 : StartWorkerNeeded = true;
4400 : 0 : return;
4401 : : }
4402 : : }
4403 : : }
4404 : : }
4405 : :
4406 : : static bool
4407 : 23486 : maybe_reap_io_worker(int pid)
4408 : : {
4409 [ + + ]: 707749 : for (int i = 0; i < MAX_IO_WORKERS; ++i)
4410 : : {
4411 [ + + ]: 686416 : if (io_worker_children[i] &&
4412 [ + + ]: 46005 : io_worker_children[i]->pid == pid)
4413 : : {
4414 : 2153 : ReleasePostmasterChildSlot(io_worker_children[i]);
4415 : :
4416 : 2153 : --io_worker_count;
4417 : 2153 : io_worker_children[i] = NULL;
4418 : 2153 : return true;
4419 : : }
4420 : : }
4421 : 21333 : return false;
4422 : : }
4423 : :
4424 : : /*
4425 : : * Returns the next time at which maybe_start_io_workers() would start one or
4426 : : * more I/O workers. Any time in the past means ASAP, and 0 means no worker
4427 : : * is currently scheduled.
4428 : : *
4429 : : * This is called by DetermineSleepTime() and also maybe_start_io_workers()
4430 : : * itself, to make sure that they agree.
4431 : : */
4432 : : static TimestampTz
4433 : 312050 : maybe_start_io_workers_scheduled_at(void)
4434 : : {
4435 [ + + ]: 312050 : if (!pgaio_workers_enabled())
4436 : 228 : return 0;
4437 : :
4438 : : /*
4439 : : * If we're in final shutting down state, then we're just waiting for all
4440 : : * processes to exit.
4441 : : */
4442 [ + + ]: 311822 : if (pmState >= PM_WAIT_IO_WORKERS)
4443 : 5500 : return 0;
4444 : :
4445 : : /* Don't start new workers during an immediate shutdown either. */
4446 [ + + ]: 306322 : if (Shutdown >= ImmediateShutdown)
4447 : 2333 : return 0;
4448 : :
4449 : : /*
4450 : : * Don't start new workers if we're in the shutdown phase of a crash
4451 : : * restart. But we *do* need to start if we're already starting up again.
4452 : : */
4453 [ + + + + ]: 303989 : if (FatalError && pmState >= PM_STOP_BACKENDS)
4454 : 136 : return 0;
4455 : :
4456 : : /*
4457 : : * Don't start a worker if we're at or above the maximum. (Excess workers
4458 : : * exit when the GUC is lowered, but the count can be temporarily too high
4459 : : * until they are reaped.)
4460 : : */
4461 [ + + ]: 303853 : if (io_worker_count >= io_max_workers)
4462 : 41 : return 0;
4463 : :
4464 : : /* If we're under the minimum, start a worker as soon as possible. */
4465 [ + + ]: 303812 : if (io_worker_count < io_min_workers)
4466 : 2134 : return TIMESTAMP_MINUS_INFINITY; /* start worker ASAP */
4467 : :
4468 : : /* Only proceed if a "grow" signal has been received from a worker. */
4469 [ + + ]: 301678 : if (!pgaio_worker_pm_test_grow_signal_sent())
4470 : 301519 : return 0;
4471 : :
4472 : : /*
4473 : : * maybe_start_io_workers() should start a new I/O worker after this time,
4474 : : * or as soon as possible if is already in the past.
4475 : : */
4476 : 159 : return io_worker_launch_next_time;
4477 : : }
4478 : :
4479 : : /*
4480 : : * Start I/O workers if required. Used at startup, to respond to change of
4481 : : * the io_min_workers GUC, when asked to start a new one due to submission
4482 : : * queue backlog, and after workers terminate in response to errors (by
4483 : : * starting "replacement" workers).
4484 : : */
4485 : : static void
4486 : 156824 : maybe_start_io_workers(void)
4487 : : {
4488 : : TimestampTz scheduled_at;
4489 : :
4490 [ + + ]: 158977 : while ((scheduled_at = maybe_start_io_workers_scheduled_at()) != 0)
4491 : : {
4492 : 2246 : TimestampTz now = GetCurrentTimestamp();
4493 : : PMChild *child;
4494 : : int i;
4495 : :
4496 : : Assert(pmState < PM_WAIT_IO_WORKERS);
4497 : :
4498 : : /* Still waiting for the scheduled time? */
4499 [ + + ]: 2246 : if (scheduled_at > now)
4500 : 47 : break;
4501 : :
4502 : : /*
4503 : : * Compute next launch time relative to the previous value, so that
4504 : : * time spent on the postmaster's other duties don't result in an
4505 : : * inaccurate launch interval.
4506 : : */
4507 : 2199 : io_worker_launch_next_time =
4508 : 2199 : TimestampTzPlusMilliseconds(io_worker_launch_next_time,
4509 : : io_worker_launch_interval);
4510 : :
4511 : : /*
4512 : : * If that's already in the past, the interval is either impossibly
4513 : : * short or we received no requests for new workers for a period.
4514 : : * Compute a new future time relative to now instead.
4515 : : */
4516 [ + + ]: 2199 : if (io_worker_launch_next_time <= now)
4517 : 1125 : io_worker_launch_next_time =
4518 : 1125 : TimestampTzPlusMilliseconds(now, io_worker_launch_interval);
4519 : :
4520 : : /*
4521 : : * Check if a grow signal has been received, but the grow request has
4522 : : * been canceled since then because work ran out. We've still
4523 : : * advanced the next launch time, to suppress repeat signals from
4524 : : * workers until then.
4525 : : */
4526 [ + + + + ]: 2199 : if (io_worker_count >= io_min_workers && !pgaio_worker_pm_test_grow())
4527 : : {
4528 : 46 : pgaio_worker_pm_clear_grow_signal_sent();
4529 : 46 : break;
4530 : : }
4531 : :
4532 : : /* find unused entry in io_worker_children array */
4533 [ + - ]: 3760 : for (i = 0; i < MAX_IO_WORKERS; ++i)
4534 : : {
4535 [ + + ]: 3760 : if (io_worker_children[i] == NULL)
4536 : 2153 : break;
4537 : : }
4538 [ - + ]: 2153 : if (i == MAX_IO_WORKERS)
4539 [ # # ]: 0 : elog(ERROR, "could not find a free IO worker slot");
4540 : :
4541 : : /* Try to launch one. */
4542 : 2153 : child = StartChildProcess(B_IO_WORKER);
4543 [ + - ]: 2153 : if (child != NULL)
4544 : : {
4545 : 2153 : io_worker_children[i] = child;
4546 : 2153 : ++io_worker_count;
4547 : : }
4548 : : else
4549 : : {
4550 : : /*
4551 : : * Fork failure: we'll try again after the launch interval
4552 : : * expires, or be called again without delay if we don't yet have
4553 : : * io_min_workers. Don't loop here though, the postmaster has
4554 : : * other duties.
4555 : : */
4556 : 0 : break;
4557 : : }
4558 : : }
4559 : :
4560 : : /*
4561 : : * Workers decide when to shut down by themselves, according to the
4562 : : * io_max_workers and io_worker_idle_timeout GUCs.
4563 : : */
4564 : 156824 : }
4565 : :
4566 : :
4567 : : /*
4568 : : * When a backend asks to be notified about worker state changes, we
4569 : : * set a flag in its backend entry. The background worker machinery needs
4570 : : * to know when such backends exit.
4571 : : */
4572 : : bool
4573 : 2754 : PostmasterMarkPIDForWorkerNotify(int pid)
4574 : : {
4575 : : dlist_iter iter;
4576 : : PMChild *bp;
4577 : :
4578 [ + - + - ]: 6737 : dlist_foreach(iter, &ActiveChildList)
4579 : : {
4580 : 6737 : bp = dlist_container(PMChild, elem, iter.cur);
4581 [ + + ]: 6737 : if (bp->pid == pid)
4582 : : {
4583 : 2754 : bp->bgworker_notify = true;
4584 : 2754 : return true;
4585 : : }
4586 : : }
4587 : 0 : return false;
4588 : : }
4589 : :
4590 : : #ifdef WIN32
4591 : :
4592 : : /*
4593 : : * Subset implementation of waitpid() for Windows. We assume pid is -1
4594 : : * (that is, check all child processes) and options is WNOHANG (don't wait).
4595 : : */
4596 : : static pid_t
4597 : : waitpid(pid_t pid, int *exitstatus, int options)
4598 : : {
4599 : : win32_deadchild_waitinfo *childinfo;
4600 : : DWORD exitcode;
4601 : : DWORD dwd;
4602 : : ULONG_PTR key;
4603 : : OVERLAPPED *ovl;
4604 : :
4605 : : /* Try to consume one win32_deadchild_waitinfo from the queue. */
4606 : : if (!GetQueuedCompletionStatus(win32ChildQueue, &dwd, &key, &ovl, 0))
4607 : : {
4608 : : errno = EAGAIN;
4609 : : return -1;
4610 : : }
4611 : :
4612 : : childinfo = (win32_deadchild_waitinfo *) key;
4613 : : pid = childinfo->procId;
4614 : :
4615 : : /*
4616 : : * Remove handle from wait - required even though it's set to wait only
4617 : : * once
4618 : : */
4619 : : UnregisterWaitEx(childinfo->waitHandle, NULL);
4620 : :
4621 : : if (!GetExitCodeProcess(childinfo->procHandle, &exitcode))
4622 : : {
4623 : : /*
4624 : : * Should never happen. Inform user and set a fixed exitcode.
4625 : : */
4626 : : write_stderr("could not read exit code for process\n");
4627 : : exitcode = 255;
4628 : : }
4629 : : *exitstatus = exitcode;
4630 : :
4631 : : /*
4632 : : * Close the process handle. Only after this point can the PID can be
4633 : : * recycled by the kernel.
4634 : : */
4635 : : CloseHandle(childinfo->procHandle);
4636 : :
4637 : : /*
4638 : : * Free struct that was allocated before the call to
4639 : : * RegisterWaitForSingleObject()
4640 : : */
4641 : : pfree(childinfo);
4642 : :
4643 : : return pid;
4644 : : }
4645 : :
4646 : : /*
4647 : : * Note! Code below executes on a thread pool! All operations must
4648 : : * be thread safe! Note that elog() and friends must *not* be used.
4649 : : */
4650 : : static void WINAPI
4651 : : pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
4652 : : {
4653 : : /* Should never happen, since we use INFINITE as timeout value. */
4654 : : if (TimerOrWaitFired)
4655 : : return;
4656 : :
4657 : : /*
4658 : : * Post the win32_deadchild_waitinfo object for waitpid() to deal with. If
4659 : : * that fails, we leak the object, but we also leak a whole process and
4660 : : * get into an unrecoverable state, so there's not much point in worrying
4661 : : * about that. We'd like to panic, but we can't use that infrastructure
4662 : : * from this thread.
4663 : : */
4664 : : if (!PostQueuedCompletionStatus(win32ChildQueue,
4665 : : 0,
4666 : : (ULONG_PTR) lpParameter,
4667 : : NULL))
4668 : : write_stderr("could not post child completion status\n");
4669 : :
4670 : : /* Queue SIGCHLD signal. */
4671 : : pg_queue_signal(SIGCHLD);
4672 : : }
4673 : :
4674 : : /*
4675 : : * Queue a waiter to signal when this child dies. The wait will be handled
4676 : : * automatically by an operating system thread pool. The memory and the
4677 : : * process handle will be freed by a later call to waitpid().
4678 : : */
4679 : : void
4680 : : pgwin32_register_deadchild_callback(HANDLE procHandle, DWORD procId)
4681 : : {
4682 : : win32_deadchild_waitinfo *childinfo;
4683 : :
4684 : : childinfo = palloc_object(win32_deadchild_waitinfo);
4685 : : childinfo->procHandle = procHandle;
4686 : : childinfo->procId = procId;
4687 : :
4688 : : if (!RegisterWaitForSingleObject(&childinfo->waitHandle,
4689 : : procHandle,
4690 : : pgwin32_deadchild_callback,
4691 : : childinfo,
4692 : : INFINITE,
4693 : : WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD))
4694 : : ereport(FATAL,
4695 : : (errmsg_internal("could not register process for wait: error code %lu",
4696 : : GetLastError())));
4697 : : }
4698 : :
4699 : : #endif /* WIN32 */
4700 : :
4701 : : /*
4702 : : * Initialize one and only handle for monitoring postmaster death.
4703 : : *
4704 : : * Called once in the postmaster, so that child processes can subsequently
4705 : : * monitor if their parent is dead.
4706 : : */
4707 : : static void
4708 : 1047 : InitPostmasterDeathWatchHandle(void)
4709 : : {
4710 : : #ifndef WIN32
4711 : :
4712 : : /*
4713 : : * Create a pipe. Postmaster holds the write end of the pipe open
4714 : : * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
4715 : : * the read file descriptor to select() to wake up in case postmaster
4716 : : * dies, or check for postmaster death with a (read() == 0). Children must
4717 : : * close the write end as soon as possible after forking, because EOF
4718 : : * won't be signaled in the read end until all processes have closed the
4719 : : * write fd. That is taken care of in ClosePostmasterPorts().
4720 : : */
4721 : : Assert(MyProcPid == PostmasterPid);
4722 [ - + ]: 1047 : if (pipe(postmaster_alive_fds) < 0)
4723 [ # # ]: 0 : ereport(FATAL,
4724 : : (errcode_for_file_access(),
4725 : : errmsg_internal("could not create pipe to monitor postmaster death: %m")));
4726 : :
4727 : : /* Notify fd.c that we've eaten two FDs for the pipe. */
4728 : 1047 : ReserveExternalFD();
4729 : 1047 : ReserveExternalFD();
4730 : :
4731 : : /*
4732 : : * Set O_NONBLOCK to allow testing for the fd's presence with a read()
4733 : : * call.
4734 : : */
4735 [ - + ]: 1047 : if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
4736 [ # # ]: 0 : ereport(FATAL,
4737 : : (errcode_for_socket_access(),
4738 : : errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
4739 : : #else
4740 : :
4741 : : /*
4742 : : * On Windows, we use a process handle for the same purpose.
4743 : : */
4744 : : if (DuplicateHandle(GetCurrentProcess(),
4745 : : GetCurrentProcess(),
4746 : : GetCurrentProcess(),
4747 : : &PostmasterHandle,
4748 : : 0,
4749 : : TRUE,
4750 : : DUPLICATE_SAME_ACCESS) == 0)
4751 : : ereport(FATAL,
4752 : : (errmsg_internal("could not duplicate postmaster handle: error code %lu",
4753 : : GetLastError())));
4754 : : #endif /* WIN32 */
4755 : 1047 : }
|