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