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