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