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