The macros NULL_DEV and DEVNULL were both used to work around
[PostgreSQL.git] / src / backend / postmaster / postmaster.c
blobcef453bafdba8cbaace8dbde68af53c973a6e8a3
1 /*-------------------------------------------------------------------------
3 * postmaster.c
4 * This program acts as a clearing house for requests to the
5 * POSTGRES system. Frontend programs send a startup message
6 * to the Postmaster and the postmaster uses the info in the
7 * message to setup a backend process.
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.
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.
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.
35 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
36 * Portions Copyright (c) 1994, Regents of the University of California
39 * IDENTIFICATION
40 * $PostgreSQL$
42 * NOTES
44 * Initialization:
45 * The Postmaster sets up shared memory data structures
46 * for the backends.
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.
54 * Garbage Collection:
55 * The Postmaster cleans up after backends if they have an emergency
56 * exit and/or core dump.
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(). In particular, don't use
62 * write_stderr() for anything that occurs after pmdaemonize.
64 *-------------------------------------------------------------------------
67 #include "postgres.h"
69 #include <unistd.h>
70 #include <signal.h>
71 #include <time.h>
72 #include <sys/wait.h>
73 #include <ctype.h>
74 #include <sys/stat.h>
75 #include <sys/socket.h>
76 #include <fcntl.h>
77 #include <sys/param.h>
78 #include <netinet/in.h>
79 #include <arpa/inet.h>
80 #include <netdb.h>
81 #include <limits.h>
83 #ifdef HAVE_SYS_SELECT_H
84 #include <sys/select.h>
85 #endif
87 #ifdef HAVE_GETOPT_H
88 #include <getopt.h>
89 #endif
91 #ifdef USE_BONJOUR
92 #include <DNSServiceDiscovery/DNSServiceDiscovery.h>
93 #endif
95 #include "access/transam.h"
96 #include "access/xlog.h"
97 #include "bootstrap/bootstrap.h"
98 #include "catalog/pg_control.h"
99 #include "lib/dllist.h"
100 #include "libpq/auth.h"
101 #include "libpq/ip.h"
102 #include "libpq/libpq.h"
103 #include "libpq/pqsignal.h"
104 #include "miscadmin.h"
105 #include "pgstat.h"
106 #include "postmaster/autovacuum.h"
107 #include "postmaster/fork_process.h"
108 #include "postmaster/pgarch.h"
109 #include "postmaster/postmaster.h"
110 #include "postmaster/syslogger.h"
111 #include "storage/fd.h"
112 #include "storage/ipc.h"
113 #include "storage/pg_shmem.h"
114 #include "storage/pmsignal.h"
115 #include "storage/proc.h"
116 #include "tcop/tcopprot.h"
117 #include "utils/builtins.h"
118 #include "utils/datetime.h"
119 #include "utils/memutils.h"
120 #include "utils/ps_status.h"
122 #ifdef EXEC_BACKEND
123 #include "storage/spin.h"
124 #endif
128 * List of active backends (or child processes anyway; we don't actually
129 * know whether a given child has become a backend or is still in the
130 * authorization phase). This is used mainly to keep track of how many
131 * children we have and send them appropriate signals when necessary.
133 * "Special" children such as the startup, bgwriter and autovacuum launcher
134 * tasks are not in this list. Autovacuum worker processes are in it.
135 * Also, "dead_end" children are in it: these are children launched just
136 * for the purpose of sending a friendly rejection message to a would-be
137 * client. We must track them because they are attached to shared memory,
138 * but we know they will never become live backends.
140 typedef struct bkend
142 pid_t pid; /* process id of backend */
143 long cancel_key; /* cancel key for cancels for this backend */
144 bool is_autovacuum; /* is it an autovacuum process? */
145 bool dead_end; /* is it going to send an error and quit? */
146 } Backend;
148 static Dllist *BackendList;
150 #ifdef EXEC_BACKEND
152 * Number of entries in the shared-memory backend table. This table is used
153 * only for sending cancels, and therefore only includes children we allow
154 * cancels on: regular backends and autovac workers. In particular we exclude
155 * dead_end children, allowing the table to have a known maximum size, to wit
156 * the same too-many-children limit enforced by canAcceptConnections().
158 #define NUM_BACKENDARRAY_ELEMS (2*MaxBackends)
160 static Backend *ShmemBackendArray;
161 #endif
163 /* The socket number we are listening for connections on */
164 int PostPortNumber;
165 char *UnixSocketDir;
166 char *ListenAddresses;
169 * ReservedBackends is the number of backends reserved for superuser use.
170 * This number is taken out of the pool size given by MaxBackends so
171 * number of backend slots available to non-superusers is
172 * (MaxBackends - ReservedBackends). Note what this really means is
173 * "if there are <= ReservedBackends connections available, only superusers
174 * can make new connections" --- pre-existing superuser connections don't
175 * count against the limit.
177 int ReservedBackends;
179 /* The socket(s) we're listening to. */
180 #define MAXLISTEN 64
181 static int ListenSocket[MAXLISTEN];
184 * Set by the -o option
186 static char ExtraOptions[MAXPGPATH];
189 * These globals control the behavior of the postmaster in case some
190 * backend dumps core. Normally, it kills all peers of the dead backend
191 * and reinitializes shared memory. By specifying -s or -n, we can have
192 * the postmaster stop (rather than kill) peers and not reinitialize
193 * shared data structures. (Reinit is currently dead code, though.)
195 static bool Reinit = true;
196 static int SendStop = false;
198 /* still more option variables */
199 bool EnableSSL = false;
200 bool SilentMode = false; /* silent mode (-S) */
202 int PreAuthDelay = 0;
203 int AuthenticationTimeout = 60;
205 bool log_hostname; /* for ps display and logging */
206 bool Log_connections = false;
207 bool Db_user_namespace = false;
209 char *bonjour_name;
211 /* PIDs of special child processes; 0 when not running */
212 static pid_t StartupPID = 0,
213 BgWriterPID = 0,
214 WalWriterPID = 0,
215 AutoVacPID = 0,
216 PgArchPID = 0,
217 PgStatPID = 0,
218 SysLoggerPID = 0;
220 /* Startup/shutdown state */
221 #define NoShutdown 0
222 #define SmartShutdown 1
223 #define FastShutdown 2
225 static int Shutdown = NoShutdown;
227 static bool FatalError = false; /* T if recovering from backend crash */
230 * We use a simple state machine to control startup, shutdown, and
231 * crash recovery (which is rather like shutdown followed by startup).
233 * Normal child backends can only be launched when we are in PM_RUN state.
234 * (We also allow it in PM_WAIT_BACKUP state, but only for superusers.)
235 * In other states we handle connection requests by launching "dead_end"
236 * child processes, which will simply send the client an error message and
237 * quit. (We track these in the BackendList so that we can know when they
238 * are all gone; this is important because they're still connected to shared
239 * memory, and would interfere with an attempt to destroy the shmem segment,
240 * possibly leading to SHMALL failure when we try to make a new one.)
241 * In PM_WAIT_DEAD_END state we are waiting for all the dead_end children
242 * to drain out of the system, and therefore stop accepting connection
243 * requests at all until the last existing child has quit (which hopefully
244 * will not be very long).
246 * Notice that this state variable does not distinguish *why* we entered
247 * states later than PM_RUN --- Shutdown and FatalError must be consulted
248 * to find that out. FatalError is never true in PM_RUN state, nor in
249 * PM_SHUTDOWN states (because we don't enter those states when trying to
250 * recover from a crash). It can be true in PM_STARTUP state, because we
251 * don't clear it until we've successfully recovered.
253 typedef enum
255 PM_INIT, /* postmaster starting */
256 PM_STARTUP, /* waiting for startup subprocess */
257 PM_RUN, /* normal "database is alive" state */
258 PM_WAIT_BACKUP, /* waiting for online backup mode to end */
259 PM_WAIT_BACKENDS, /* waiting for live backends to exit */
260 PM_SHUTDOWN, /* waiting for bgwriter to do shutdown ckpt */
261 PM_SHUTDOWN_2, /* waiting for archiver to finish */
262 PM_WAIT_DEAD_END, /* waiting for dead_end children to exit */
263 PM_NO_CHILDREN /* all important children have exited */
264 } PMState;
266 static PMState pmState = PM_INIT;
268 bool ClientAuthInProgress = false; /* T during new-client
269 * authentication */
271 bool redirection_done = false; /* stderr redirected for syslogger? */
273 /* received START_AUTOVAC_LAUNCHER signal */
274 static volatile sig_atomic_t start_autovac_launcher = false;
277 * State for assigning random salts and cancel keys.
278 * Also, the global MyCancelKey passes the cancel key assigned to a given
279 * backend from the postmaster to that backend (via fork).
281 static unsigned int random_seed = 0;
282 static struct timeval random_start_time;
284 extern char *optarg;
285 extern int optind,
286 opterr;
288 #ifdef HAVE_INT_OPTRESET
289 extern int optreset;
290 #endif
293 * postmaster.c - function prototypes
295 static void checkDataDir(void);
297 #ifdef USE_BONJOUR
298 static void reg_reply(DNSServiceRegistrationReplyErrorType errorCode,
299 void *context);
300 #endif
301 static void pmdaemonize(void);
302 static Port *ConnCreate(int serverFd);
303 static void ConnFree(Port *port);
304 static void reset_shared(int port);
305 static void SIGHUP_handler(SIGNAL_ARGS);
306 static void pmdie(SIGNAL_ARGS);
307 static void reaper(SIGNAL_ARGS);
308 static void sigusr1_handler(SIGNAL_ARGS);
309 static void dummy_handler(SIGNAL_ARGS);
310 static void CleanupBackend(int pid, int exitstatus);
311 static void HandleChildCrash(int pid, int exitstatus, const char *procname);
312 static void LogChildExit(int lev, const char *procname,
313 int pid, int exitstatus);
314 static void PostmasterStateMachine(void);
315 static void BackendInitialize(Port *port);
316 static int BackendRun(Port *port);
317 static void ExitPostmaster(int status);
318 static int ServerLoop(void);
319 static int BackendStartup(Port *port);
320 static int ProcessStartupPacket(Port *port, bool SSLdone);
321 static void processCancelRequest(Port *port, void *pkt);
322 static int initMasks(fd_set *rmask);
323 static void report_fork_failure_to_client(Port *port, int errnum);
324 static enum CAC_state canAcceptConnections(void);
325 static long PostmasterRandom(void);
326 static void RandomSalt(char *md5Salt);
327 static void signal_child(pid_t pid, int signal);
328 static void SignalSomeChildren(int signal, bool only_autovac);
330 #define SignalChildren(sig) SignalSomeChildren(sig, false)
331 #define SignalAutovacWorkers(sig) SignalSomeChildren(sig, true)
332 static int CountChildren(void);
333 static bool CreateOptsFile(int argc, char *argv[], char *fullprogname);
334 static pid_t StartChildProcess(AuxProcType type);
335 static void StartAutovacuumWorker(void);
337 #ifdef EXEC_BACKEND
339 #ifdef WIN32
340 static pid_t win32_waitpid(int *exitstatus);
341 static void WINAPI pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired);
343 static HANDLE win32ChildQueue;
345 typedef struct
347 HANDLE waitHandle;
348 HANDLE procHandle;
349 DWORD procId;
350 } win32_deadchild_waitinfo;
352 HANDLE PostmasterHandle;
353 #endif
355 static pid_t backend_forkexec(Port *port);
356 static pid_t internal_forkexec(int argc, char *argv[], Port *port);
358 /* Type for a socket that can be inherited to a client process */
359 #ifdef WIN32
360 typedef struct
362 SOCKET origsocket; /* Original socket value, or -1 if not a
363 * socket */
364 WSAPROTOCOL_INFO wsainfo;
365 } InheritableSocket;
366 #else
367 typedef int InheritableSocket;
368 #endif
370 typedef struct LWLock LWLock; /* ugly kluge */
373 * Structure contains all variables passed to exec:ed backends
375 typedef struct
377 Port port;
378 InheritableSocket portsocket;
379 char DataDir[MAXPGPATH];
380 int ListenSocket[MAXLISTEN];
381 long MyCancelKey;
382 unsigned long UsedShmemSegID;
383 void *UsedShmemSegAddr;
384 slock_t *ShmemLock;
385 VariableCache ShmemVariableCache;
386 Backend *ShmemBackendArray;
387 LWLock *LWLockArray;
388 slock_t *ProcStructLock;
389 PROC_HDR *ProcGlobal;
390 PGPROC *AuxiliaryProcs;
391 InheritableSocket pgStatSock;
392 pid_t PostmasterPid;
393 TimestampTz PgStartTime;
394 TimestampTz PgReloadTime;
395 bool redirection_done;
396 #ifdef WIN32
397 HANDLE PostmasterHandle;
398 HANDLE initial_signal_pipe;
399 HANDLE syslogPipe[2];
400 #else
401 int syslogPipe[2];
402 #endif
403 char my_exec_path[MAXPGPATH];
404 char pkglib_path[MAXPGPATH];
405 char ExtraOptions[MAXPGPATH];
406 char lc_collate[NAMEDATALEN];
407 char lc_ctype[NAMEDATALEN];
408 } BackendParameters;
410 static void read_backend_variables(char *id, Port *port);
411 static void restore_backend_variables(BackendParameters * param, Port *port);
413 #ifndef WIN32
414 static bool save_backend_variables(BackendParameters * param, Port *port);
415 #else
416 static bool save_backend_variables(BackendParameters * param, Port *port,
417 HANDLE childProcess, pid_t childPid);
418 #endif
420 static void ShmemBackendArrayAdd(Backend *bn);
421 static void ShmemBackendArrayRemove(pid_t pid);
422 #endif /* EXEC_BACKEND */
424 #define StartupDataBase() StartChildProcess(StartupProcess)
425 #define StartBackgroundWriter() StartChildProcess(BgWriterProcess)
426 #define StartWalWriter() StartChildProcess(WalWriterProcess)
428 /* Macros to check exit status of a child process */
429 #define EXIT_STATUS_0(st) ((st) == 0)
430 #define EXIT_STATUS_1(st) (WIFEXITED(st) && WEXITSTATUS(st) == 1)
434 * Postmaster main entry point
437 PostmasterMain(int argc, char *argv[])
439 int opt;
440 int status;
441 char *userDoption = NULL;
442 int i;
444 MyProcPid = PostmasterPid = getpid();
446 MyStartTime = time(NULL);
448 IsPostmasterEnvironment = true;
451 * for security, no dir or file created can be group or other accessible
453 umask((mode_t) 0077);
456 * Fire up essential subsystems: memory management
458 MemoryContextInit();
461 * By default, palloc() requests in the postmaster will be allocated in
462 * the PostmasterContext, which is space that can be recycled by backends.
463 * Allocated data that needs to be available to backends should be
464 * allocated in TopMemoryContext.
466 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
467 "Postmaster",
468 ALLOCSET_DEFAULT_MINSIZE,
469 ALLOCSET_DEFAULT_INITSIZE,
470 ALLOCSET_DEFAULT_MAXSIZE);
471 MemoryContextSwitchTo(PostmasterContext);
473 if (find_my_exec(argv[0], my_exec_path) < 0)
474 elog(FATAL, "%s: could not locate my own executable path",
475 argv[0]);
477 get_pkglib_path(my_exec_path, pkglib_path);
480 * Options setup
482 InitializeGUCOptions();
484 opterr = 1;
487 * Parse command-line options. CAUTION: keep this in sync with
488 * tcop/postgres.c (the option sets should not conflict) and with the
489 * common help() function in main/main.c.
491 while ((opt = getopt(argc, argv, "A:B:c:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:W:-:")) != -1)
493 switch (opt)
495 case 'A':
496 SetConfigOption("debug_assertions", optarg, PGC_POSTMASTER, PGC_S_ARGV);
497 break;
499 case 'B':
500 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
501 break;
503 case 'D':
504 userDoption = optarg;
505 break;
507 case 'd':
508 set_debug_options(atoi(optarg), PGC_POSTMASTER, PGC_S_ARGV);
509 break;
511 case 'E':
512 SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
513 break;
515 case 'e':
516 SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
517 break;
519 case 'F':
520 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
521 break;
523 case 'f':
524 if (!set_plan_disabling_options(optarg, PGC_POSTMASTER, PGC_S_ARGV))
526 write_stderr("%s: invalid argument for option -f: \"%s\"\n",
527 progname, optarg);
528 ExitPostmaster(1);
530 break;
532 case 'h':
533 SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
534 break;
536 case 'i':
537 SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
538 break;
540 case 'j':
541 /* only used by interactive backend */
542 break;
544 case 'k':
545 SetConfigOption("unix_socket_directory", optarg, PGC_POSTMASTER, PGC_S_ARGV);
546 break;
548 case 'l':
549 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
550 break;
552 case 'N':
553 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
554 break;
556 case 'n':
557 /* Don't reinit shared mem after abnormal exit */
558 Reinit = false;
559 break;
561 case 'O':
562 SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
563 break;
565 case 'o':
566 /* Other options to pass to the backend on the command line */
567 snprintf(ExtraOptions + strlen(ExtraOptions),
568 sizeof(ExtraOptions) - strlen(ExtraOptions),
569 " %s", optarg);
570 break;
572 case 'P':
573 SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
574 break;
576 case 'p':
577 SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
578 break;
580 case 'r':
581 /* only used by single-user backend */
582 break;
584 case 'S':
585 SetConfigOption("work_mem", optarg, PGC_POSTMASTER, PGC_S_ARGV);
586 break;
588 case 's':
589 SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
590 break;
592 case 'T':
595 * In the event that some backend dumps core, send SIGSTOP,
596 * rather than SIGQUIT, to all its peers. This lets the wily
597 * post_hacker collect core dumps from everyone.
599 SendStop = true;
600 break;
602 case 't':
604 const char *tmp = get_stats_option_name(optarg);
606 if (tmp)
608 SetConfigOption(tmp, "true", PGC_POSTMASTER, PGC_S_ARGV);
610 else
612 write_stderr("%s: invalid argument for option -t: \"%s\"\n",
613 progname, optarg);
614 ExitPostmaster(1);
616 break;
619 case 'W':
620 SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
621 break;
623 case 'c':
624 case '-':
626 char *name,
627 *value;
629 ParseLongOption(optarg, &name, &value);
630 if (!value)
632 if (opt == '-')
633 ereport(ERROR,
634 (errcode(ERRCODE_SYNTAX_ERROR),
635 errmsg("--%s requires a value",
636 optarg)));
637 else
638 ereport(ERROR,
639 (errcode(ERRCODE_SYNTAX_ERROR),
640 errmsg("-c %s requires a value",
641 optarg)));
644 SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
645 free(name);
646 if (value)
647 free(value);
648 break;
651 default:
652 write_stderr("Try \"%s --help\" for more information.\n",
653 progname);
654 ExitPostmaster(1);
659 * Postmaster accepts no non-option switch arguments.
661 if (optind < argc)
663 write_stderr("%s: invalid argument: \"%s\"\n",
664 progname, argv[optind]);
665 write_stderr("Try \"%s --help\" for more information.\n",
666 progname);
667 ExitPostmaster(1);
670 #ifdef EXEC_BACKEND
671 /* Locate executable backend before we change working directory */
672 if (find_other_exec(argv[0], "postgres", PG_BACKEND_VERSIONSTR,
673 postgres_exec_path) < 0)
674 ereport(FATAL,
675 (errmsg("%s: could not locate matching postgres executable",
676 progname)));
677 #endif
680 * Locate the proper configuration files and data directory, and read
681 * postgresql.conf for the first time.
683 if (!SelectConfigFiles(userDoption, progname))
684 ExitPostmaster(2);
686 /* Verify that DataDir looks reasonable */
687 checkDataDir();
689 /* And switch working directory into it */
690 ChangeToDataDir();
693 * Check for invalid combinations of GUC settings.
695 if (ReservedBackends >= MaxBackends)
697 write_stderr("%s: superuser_reserved_connections must be less than max_connections\n", progname);
698 ExitPostmaster(1);
702 * Other one-time internal sanity checks can go here, if they are fast.
703 * (Put any slow processing further down, after postmaster.pid creation.)
705 if (!CheckDateTokenTables())
707 write_stderr("%s: invalid datetoken tables, please fix\n", progname);
708 ExitPostmaster(1);
712 * Now that we are done processing the postmaster arguments, reset
713 * getopt(3) library so that it will work correctly in subprocesses.
715 optind = 1;
716 #ifdef HAVE_INT_OPTRESET
717 optreset = 1; /* some systems need this too */
718 #endif
720 /* For debugging: display postmaster environment */
722 extern char **environ;
723 char **p;
725 ereport(DEBUG3,
726 (errmsg_internal("%s: PostmasterMain: initial environ dump:",
727 progname)));
728 ereport(DEBUG3,
729 (errmsg_internal("-----------------------------------------")));
730 for (p = environ; *p; ++p)
731 ereport(DEBUG3,
732 (errmsg_internal("\t%s", *p)));
733 ereport(DEBUG3,
734 (errmsg_internal("-----------------------------------------")));
738 * Fork away from controlling terminal, if -S specified.
740 * Must do this before we grab any interlock files, else the interlocks
741 * will show the wrong PID.
743 if (SilentMode)
744 pmdaemonize();
747 * Create lockfile for data directory.
749 * We want to do this before we try to grab the input sockets, because the
750 * data directory interlock is more reliable than the socket-file
751 * interlock (thanks to whoever decided to put socket files in /tmp :-().
752 * For the same reason, it's best to grab the TCP socket(s) before the
753 * Unix socket.
755 CreateDataDirLockFile(true);
758 * If timezone is not set, determine what the OS uses. (In theory this
759 * should be done during GUC initialization, but because it can take as
760 * much as several seconds, we delay it until after we've created the
761 * postmaster.pid file. This prevents problems with boot scripts that
762 * expect the pidfile to appear quickly. Also, we avoid problems with
763 * trying to locate the timezone files too early in initialization.)
765 pg_timezone_initialize();
768 * Likewise, init timezone_abbreviations if not already set.
770 pg_timezone_abbrev_initialize();
773 * Initialize SSL library, if specified.
775 #ifdef USE_SSL
776 if (EnableSSL)
777 secure_initialize();
778 #endif
781 * process any libraries that should be preloaded at postmaster start
783 process_shared_preload_libraries();
786 * Remove old temporary files. At this point there can be no other
787 * Postgres processes running in this directory, so this should be safe.
789 RemovePgTempFiles();
792 * Establish input sockets.
794 for (i = 0; i < MAXLISTEN; i++)
795 ListenSocket[i] = -1;
797 if (ListenAddresses)
799 char *rawstring;
800 List *elemlist;
801 ListCell *l;
802 int success = 0;
804 /* Need a modifiable copy of ListenAddresses */
805 rawstring = pstrdup(ListenAddresses);
807 /* Parse string into list of identifiers */
808 if (!SplitIdentifierString(rawstring, ',', &elemlist))
810 /* syntax error in list */
811 ereport(FATAL,
812 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
813 errmsg("invalid list syntax for \"listen_addresses\"")));
816 foreach(l, elemlist)
818 char *curhost = (char *) lfirst(l);
820 if (strcmp(curhost, "*") == 0)
821 status = StreamServerPort(AF_UNSPEC, NULL,
822 (unsigned short) PostPortNumber,
823 UnixSocketDir,
824 ListenSocket, MAXLISTEN);
825 else
826 status = StreamServerPort(AF_UNSPEC, curhost,
827 (unsigned short) PostPortNumber,
828 UnixSocketDir,
829 ListenSocket, MAXLISTEN);
830 if (status == STATUS_OK)
831 success++;
832 else
833 ereport(WARNING,
834 (errmsg("could not create listen socket for \"%s\"",
835 curhost)));
838 if (!success && list_length(elemlist))
839 ereport(FATAL,
840 (errmsg("could not create any TCP/IP sockets")));
842 list_free(elemlist);
843 pfree(rawstring);
846 #ifdef USE_BONJOUR
847 /* Register for Bonjour only if we opened TCP socket(s) */
848 if (ListenSocket[0] != -1 && bonjour_name != NULL)
850 DNSServiceRegistrationCreate(bonjour_name,
851 "_postgresql._tcp.",
853 htons(PostPortNumber),
855 (DNSServiceRegistrationReply) reg_reply,
856 NULL);
858 #endif
860 #ifdef HAVE_UNIX_SOCKETS
861 status = StreamServerPort(AF_UNIX, NULL,
862 (unsigned short) PostPortNumber,
863 UnixSocketDir,
864 ListenSocket, MAXLISTEN);
865 if (status != STATUS_OK)
866 ereport(WARNING,
867 (errmsg("could not create Unix-domain socket")));
868 #endif
871 * check that we have some socket to listen on
873 if (ListenSocket[0] == -1)
874 ereport(FATAL,
875 (errmsg("no socket created for listening")));
878 * Set up shared memory and semaphores.
880 reset_shared(PostPortNumber);
883 * Estimate number of openable files. This must happen after setting up
884 * semaphores, because on some platforms semaphores count as open files.
886 set_max_safe_fds();
889 * Load configuration files for client authentication.
891 if (!load_hba())
894 * It makes no sense continue if we fail to load the HBA file, since
895 * there is no way to connect to the database in this case.
897 ereport(FATAL,
898 (errmsg("could not load pg_hba.conf")));
900 load_ident();
903 * Initialize the list of active backends.
905 BackendList = DLNewList();
907 #ifdef WIN32
910 * Initialize I/O completion port used to deliver list of dead children.
912 win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
913 if (win32ChildQueue == NULL)
914 ereport(FATAL,
915 (errmsg("could not create I/O completion port for child queue")));
918 * Set up a handle that child processes can use to check whether the
919 * postmaster is still running.
921 if (DuplicateHandle(GetCurrentProcess(),
922 GetCurrentProcess(),
923 GetCurrentProcess(),
924 &PostmasterHandle,
926 TRUE,
927 DUPLICATE_SAME_ACCESS) == 0)
928 ereport(FATAL,
929 (errmsg_internal("could not duplicate postmaster handle: error code %d",
930 (int) GetLastError())));
931 #endif
934 * Record postmaster options. We delay this till now to avoid recording
935 * bogus options (eg, NBuffers too high for available memory).
937 if (!CreateOptsFile(argc, argv, my_exec_path))
938 ExitPostmaster(1);
940 #ifdef EXEC_BACKEND
941 /* Write out nondefault GUC settings for child processes to use */
942 write_nondefault_variables(PGC_POSTMASTER);
943 #endif
946 * Write the external PID file if requested
948 if (external_pid_file)
950 FILE *fpidfile = fopen(external_pid_file, "w");
952 if (fpidfile)
954 fprintf(fpidfile, "%d\n", MyProcPid);
955 fclose(fpidfile);
956 /* Should we remove the pid file on postmaster exit? */
958 else
959 write_stderr("%s: could not write external PID file \"%s\": %s\n",
960 progname, external_pid_file, strerror(errno));
964 * Set up signal handlers for the postmaster process.
966 * CAUTION: when changing this list, check for side-effects on the signal
967 * handling setup of child processes. See tcop/postgres.c,
968 * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/walwriter.c,
969 * postmaster/autovacuum.c, postmaster/pgarch.c, postmaster/pgstat.c, and
970 * postmaster/syslogger.c.
972 pqinitmask();
973 PG_SETMASK(&BlockSig);
975 pqsignal(SIGHUP, SIGHUP_handler); /* reread config file and have
976 * children do same */
977 pqsignal(SIGINT, pmdie); /* send SIGTERM and shut down */
978 pqsignal(SIGQUIT, pmdie); /* send SIGQUIT and die */
979 pqsignal(SIGTERM, pmdie); /* wait for children and shut down */
980 pqsignal(SIGALRM, SIG_IGN); /* ignored */
981 pqsignal(SIGPIPE, SIG_IGN); /* ignored */
982 pqsignal(SIGUSR1, sigusr1_handler); /* message from child process */
983 pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
984 pqsignal(SIGCHLD, reaper); /* handle child termination */
985 pqsignal(SIGTTIN, SIG_IGN); /* ignored */
986 pqsignal(SIGTTOU, SIG_IGN); /* ignored */
987 /* ignore SIGXFSZ, so that ulimit violations work like disk full */
988 #ifdef SIGXFSZ
989 pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
990 #endif
993 * If enabled, start up syslogger collection subprocess
995 SysLoggerPID = SysLogger_Start();
998 * Reset whereToSendOutput from DestDebug (its starting state) to
999 * DestNone. This stops ereport from sending log messages to stderr unless
1000 * Log_destination permits. We don't do this until the postmaster is
1001 * fully launched, since startup failures may as well be reported to
1002 * stderr.
1004 whereToSendOutput = DestNone;
1007 * Initialize stats collection subsystem (this does NOT start the
1008 * collector process!)
1010 pgstat_init();
1013 * Initialize the autovacuum subsystem (again, no process start yet)
1015 autovac_init();
1018 * Remember postmaster startup time
1020 PgStartTime = GetCurrentTimestamp();
1021 /* PostmasterRandom wants its own copy */
1022 gettimeofday(&random_start_time, NULL);
1025 * We're ready to rock and roll...
1027 StartupPID = StartupDataBase();
1028 Assert(StartupPID != 0);
1029 pmState = PM_STARTUP;
1031 status = ServerLoop();
1034 * ServerLoop probably shouldn't ever return, but if it does, close down.
1036 ExitPostmaster(status != STATUS_OK);
1038 return 0; /* not reached */
1043 * Validate the proposed data directory
1045 static void
1046 checkDataDir(void)
1048 char path[MAXPGPATH];
1049 FILE *fp;
1050 struct stat stat_buf;
1052 Assert(DataDir);
1054 if (stat(DataDir, &stat_buf) != 0)
1056 if (errno == ENOENT)
1057 ereport(FATAL,
1058 (errcode_for_file_access(),
1059 errmsg("data directory \"%s\" does not exist",
1060 DataDir)));
1061 else
1062 ereport(FATAL,
1063 (errcode_for_file_access(),
1064 errmsg("could not read permissions of directory \"%s\": %m",
1065 DataDir)));
1068 /* eventual chdir would fail anyway, but let's test ... */
1069 if (!S_ISDIR(stat_buf.st_mode))
1070 ereport(FATAL,
1071 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1072 errmsg("specified data directory \"%s\" is not a directory",
1073 DataDir)));
1076 * Check that the directory belongs to my userid; if not, reject.
1078 * This check is an essential part of the interlock that prevents two
1079 * postmasters from starting in the same directory (see CreateLockFile()).
1080 * Do not remove or weaken it.
1082 * XXX can we safely enable this check on Windows?
1084 #if !defined(WIN32) && !defined(__CYGWIN__)
1085 if (stat_buf.st_uid != geteuid())
1086 ereport(FATAL,
1087 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1088 errmsg("data directory \"%s\" has wrong ownership",
1089 DataDir),
1090 errhint("The server must be started by the user that owns the data directory.")));
1091 #endif
1094 * Check if the directory has group or world access. If so, reject.
1096 * It would be possible to allow weaker constraints (for example, allow
1097 * group access) but we cannot make a general assumption that that is
1098 * okay; for example there are platforms where nearly all users
1099 * customarily belong to the same group. Perhaps this test should be
1100 * configurable.
1102 * XXX temporarily suppress check when on Windows, because there may not
1103 * be proper support for Unix-y file permissions. Need to think of a
1104 * reasonable check to apply on Windows.
1106 #if !defined(WIN32) && !defined(__CYGWIN__)
1107 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
1108 ereport(FATAL,
1109 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1110 errmsg("data directory \"%s\" has group or world access",
1111 DataDir),
1112 errdetail("Permissions should be u=rwx (0700).")));
1113 #endif
1115 /* Look for PG_VERSION before looking for pg_control */
1116 ValidatePgVersion(DataDir);
1118 snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1120 fp = AllocateFile(path, PG_BINARY_R);
1121 if (fp == NULL)
1123 write_stderr("%s: could not find the database system\n"
1124 "Expected to find it in the directory \"%s\",\n"
1125 "but could not open file \"%s\": %s\n",
1126 progname, DataDir, path, strerror(errno));
1127 ExitPostmaster(2);
1129 FreeFile(fp);
1133 #ifdef USE_BONJOUR
1136 * empty callback function for DNSServiceRegistrationCreate()
1138 static void
1139 reg_reply(DNSServiceRegistrationReplyErrorType errorCode, void *context)
1142 #endif /* USE_BONJOUR */
1146 * Fork away from the controlling terminal (-S option)
1148 static void
1149 pmdaemonize(void)
1151 #ifndef WIN32
1152 int i;
1153 pid_t pid;
1155 pid = fork_process();
1156 if (pid == (pid_t) -1)
1158 write_stderr("%s: could not fork background process: %s\n",
1159 progname, strerror(errno));
1160 ExitPostmaster(1);
1162 else if (pid)
1163 { /* parent */
1164 /* Parent should just exit, without doing any atexit cleanup */
1165 _exit(0);
1168 MyProcPid = PostmasterPid = getpid(); /* reset PID vars to child */
1170 MyStartTime = time(NULL);
1173 * GH: If there's no setsid(), we hopefully don't need silent mode. Until
1174 * there's a better solution.
1176 #ifdef HAVE_SETSID
1177 if (setsid() < 0)
1179 write_stderr("%s: could not dissociate from controlling TTY: %s\n",
1180 progname, strerror(errno));
1181 ExitPostmaster(1);
1183 #endif
1184 i = open(DEVNULL, O_RDWR, 0);
1185 dup2(i, 0);
1186 dup2(i, 1);
1187 dup2(i, 2);
1188 close(i);
1189 #else /* WIN32 */
1190 /* not supported */
1191 elog(FATAL, "SilentMode not supported under WIN32");
1192 #endif /* WIN32 */
1197 * Main idle loop of postmaster
1199 static int
1200 ServerLoop(void)
1202 fd_set readmask;
1203 int nSockets;
1204 time_t now,
1205 last_touch_time;
1207 last_touch_time = time(NULL);
1209 nSockets = initMasks(&readmask);
1211 for (;;)
1213 fd_set rmask;
1214 int selres;
1217 * Wait for a connection request to arrive.
1219 * We wait at most one minute, to ensure that the other background
1220 * tasks handled below get done even when no requests are arriving.
1222 * If we are in PM_WAIT_DEAD_END state, then we don't want to accept
1223 * any new connections, so we don't call select() at all; just sleep
1224 * for a little bit with signals unblocked.
1226 memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
1228 PG_SETMASK(&UnBlockSig);
1230 if (pmState == PM_WAIT_DEAD_END)
1232 pg_usleep(100000L); /* 100 msec seems reasonable */
1233 selres = 0;
1235 else
1237 /* must set timeout each time; some OSes change it! */
1238 struct timeval timeout;
1240 timeout.tv_sec = 60;
1241 timeout.tv_usec = 0;
1243 selres = select(nSockets, &rmask, NULL, NULL, &timeout);
1247 * Block all signals until we wait again. (This makes it safe for our
1248 * signal handlers to do nontrivial work.)
1250 PG_SETMASK(&BlockSig);
1252 /* Now check the select() result */
1253 if (selres < 0)
1255 if (errno != EINTR && errno != EWOULDBLOCK)
1257 ereport(LOG,
1258 (errcode_for_socket_access(),
1259 errmsg("select() failed in postmaster: %m")));
1260 return STATUS_ERROR;
1265 * New connection pending on any of our sockets? If so, fork a child
1266 * process to deal with it.
1268 if (selres > 0)
1270 int i;
1272 for (i = 0; i < MAXLISTEN; i++)
1274 if (ListenSocket[i] == -1)
1275 break;
1276 if (FD_ISSET(ListenSocket[i], &rmask))
1278 Port *port;
1280 port = ConnCreate(ListenSocket[i]);
1281 if (port)
1283 BackendStartup(port);
1286 * We no longer need the open socket or port structure
1287 * in this process
1289 StreamClose(port->sock);
1290 ConnFree(port);
1296 /* If we have lost the log collector, try to start a new one */
1297 if (SysLoggerPID == 0 && Logging_collector)
1298 SysLoggerPID = SysLogger_Start();
1301 * If no background writer process is running, and we are not in a
1302 * state that prevents it, start one. It doesn't matter if this
1303 * fails, we'll just try again later.
1305 if (BgWriterPID == 0 && pmState == PM_RUN)
1306 BgWriterPID = StartBackgroundWriter();
1309 * Likewise, if we have lost the walwriter process, try to start a new
1310 * one.
1312 if (WalWriterPID == 0 && pmState == PM_RUN)
1313 WalWriterPID = StartWalWriter();
1315 /* If we have lost the autovacuum launcher, try to start a new one */
1316 if (AutoVacPID == 0 &&
1317 (AutoVacuumingActive() || start_autovac_launcher) &&
1318 pmState == PM_RUN)
1320 AutoVacPID = StartAutoVacLauncher();
1321 if (AutoVacPID != 0)
1322 start_autovac_launcher = false; /* signal processed */
1325 /* If we have lost the archiver, try to start a new one */
1326 if (XLogArchivingActive() && PgArchPID == 0 && pmState == PM_RUN)
1327 PgArchPID = pgarch_start();
1329 /* If we have lost the stats collector, try to start a new one */
1330 if (PgStatPID == 0 && pmState == PM_RUN)
1331 PgStatPID = pgstat_start();
1334 * Touch the socket and lock file every 58 minutes, to ensure that
1335 * they are not removed by overzealous /tmp-cleaning tasks. We assume
1336 * no one runs cleaners with cutoff times of less than an hour ...
1338 now = time(NULL);
1339 if (now - last_touch_time >= 58 * SECS_PER_MINUTE)
1341 TouchSocketFile();
1342 TouchSocketLockFile();
1343 last_touch_time = now;
1350 * Initialise the masks for select() for the ports we are listening on.
1351 * Return the number of sockets to listen on.
1353 static int
1354 initMasks(fd_set *rmask)
1356 int maxsock = -1;
1357 int i;
1359 FD_ZERO(rmask);
1361 for (i = 0; i < MAXLISTEN; i++)
1363 int fd = ListenSocket[i];
1365 if (fd == -1)
1366 break;
1367 FD_SET(fd, rmask);
1368 if (fd > maxsock)
1369 maxsock = fd;
1372 return maxsock + 1;
1377 * Read a client's startup packet and do something according to it.
1379 * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
1380 * not return at all.
1382 * (Note that ereport(FATAL) stuff is sent to the client, so only use it
1383 * if that's what you want. Return STATUS_ERROR if you don't want to
1384 * send anything to the client, which would typically be appropriate
1385 * if we detect a communications failure.)
1387 static int
1388 ProcessStartupPacket(Port *port, bool SSLdone)
1390 int32 len;
1391 void *buf;
1392 ProtocolVersion proto;
1393 MemoryContext oldcontext;
1395 if (pq_getbytes((char *) &len, 4) == EOF)
1398 * EOF after SSLdone probably means the client didn't like our
1399 * response to NEGOTIATE_SSL_CODE. That's not an error condition, so
1400 * don't clutter the log with a complaint.
1402 if (!SSLdone)
1403 ereport(COMMERROR,
1404 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1405 errmsg("incomplete startup packet")));
1406 return STATUS_ERROR;
1409 len = ntohl(len);
1410 len -= 4;
1412 if (len < (int32) sizeof(ProtocolVersion) ||
1413 len > MAX_STARTUP_PACKET_LENGTH)
1415 ereport(COMMERROR,
1416 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1417 errmsg("invalid length of startup packet")));
1418 return STATUS_ERROR;
1422 * Allocate at least the size of an old-style startup packet, plus one
1423 * extra byte, and make sure all are zeroes. This ensures we will have
1424 * null termination of all strings, in both fixed- and variable-length
1425 * packet layouts.
1427 if (len <= (int32) sizeof(StartupPacket))
1428 buf = palloc0(sizeof(StartupPacket) + 1);
1429 else
1430 buf = palloc0(len + 1);
1432 if (pq_getbytes(buf, len) == EOF)
1434 ereport(COMMERROR,
1435 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1436 errmsg("incomplete startup packet")));
1437 return STATUS_ERROR;
1441 * The first field is either a protocol version number or a special
1442 * request code.
1444 port->proto = proto = ntohl(*((ProtocolVersion *) buf));
1446 if (proto == CANCEL_REQUEST_CODE)
1448 processCancelRequest(port, buf);
1449 return 127; /* XXX */
1452 if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
1454 char SSLok;
1456 #ifdef USE_SSL
1457 /* No SSL when disabled or on Unix sockets */
1458 if (!EnableSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
1459 SSLok = 'N';
1460 else
1461 SSLok = 'S'; /* Support for SSL */
1462 #else
1463 SSLok = 'N'; /* No support for SSL */
1464 #endif
1466 retry1:
1467 if (send(port->sock, &SSLok, 1, 0) != 1)
1469 if (errno == EINTR)
1470 goto retry1; /* if interrupted, just retry */
1471 ereport(COMMERROR,
1472 (errcode_for_socket_access(),
1473 errmsg("failed to send SSL negotiation response: %m")));
1474 return STATUS_ERROR; /* close the connection */
1477 #ifdef USE_SSL
1478 if (SSLok == 'S' && secure_open_server(port) == -1)
1479 return STATUS_ERROR;
1480 #endif
1481 /* regular startup packet, cancel, etc packet should follow... */
1482 /* but not another SSL negotiation request */
1483 return ProcessStartupPacket(port, true);
1486 /* Could add additional special packet types here */
1489 * Set FrontendProtocol now so that ereport() knows what format to send if
1490 * we fail during startup.
1492 FrontendProtocol = proto;
1494 /* Check we can handle the protocol the frontend is using. */
1496 if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
1497 PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
1498 (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
1499 PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
1500 ereport(FATAL,
1501 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1502 errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
1503 PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
1504 PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST),
1505 PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST),
1506 PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))));
1509 * Now fetch parameters out of startup packet and save them into the Port
1510 * structure. All data structures attached to the Port struct must be
1511 * allocated in TopMemoryContext so that they won't disappear when we pass
1512 * them to PostgresMain (see BackendRun). We need not worry about leaking
1513 * this storage on failure, since we aren't in the postmaster process
1514 * anymore.
1516 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1518 if (PG_PROTOCOL_MAJOR(proto) >= 3)
1520 int32 offset = sizeof(ProtocolVersion);
1523 * Scan packet body for name/option pairs. We can assume any string
1524 * beginning within the packet body is null-terminated, thanks to
1525 * zeroing extra byte above.
1527 port->guc_options = NIL;
1529 while (offset < len)
1531 char *nameptr = ((char *) buf) + offset;
1532 int32 valoffset;
1533 char *valptr;
1535 if (*nameptr == '\0')
1536 break; /* found packet terminator */
1537 valoffset = offset + strlen(nameptr) + 1;
1538 if (valoffset >= len)
1539 break; /* missing value, will complain below */
1540 valptr = ((char *) buf) + valoffset;
1542 if (strcmp(nameptr, "database") == 0)
1543 port->database_name = pstrdup(valptr);
1544 else if (strcmp(nameptr, "user") == 0)
1545 port->user_name = pstrdup(valptr);
1546 else if (strcmp(nameptr, "options") == 0)
1547 port->cmdline_options = pstrdup(valptr);
1548 else
1550 /* Assume it's a generic GUC option */
1551 port->guc_options = lappend(port->guc_options,
1552 pstrdup(nameptr));
1553 port->guc_options = lappend(port->guc_options,
1554 pstrdup(valptr));
1556 offset = valoffset + strlen(valptr) + 1;
1560 * If we didn't find a packet terminator exactly at the end of the
1561 * given packet length, complain.
1563 if (offset != len - 1)
1564 ereport(FATAL,
1565 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1566 errmsg("invalid startup packet layout: expected terminator as last byte")));
1568 else
1571 * Get the parameters from the old-style, fixed-width-fields startup
1572 * packet as C strings. The packet destination was cleared first so a
1573 * short packet has zeros silently added. We have to be prepared to
1574 * truncate the pstrdup result for oversize fields, though.
1576 StartupPacket *packet = (StartupPacket *) buf;
1578 port->database_name = pstrdup(packet->database);
1579 if (strlen(port->database_name) > sizeof(packet->database))
1580 port->database_name[sizeof(packet->database)] = '\0';
1581 port->user_name = pstrdup(packet->user);
1582 if (strlen(port->user_name) > sizeof(packet->user))
1583 port->user_name[sizeof(packet->user)] = '\0';
1584 port->cmdline_options = pstrdup(packet->options);
1585 if (strlen(port->cmdline_options) > sizeof(packet->options))
1586 port->cmdline_options[sizeof(packet->options)] = '\0';
1587 port->guc_options = NIL;
1590 /* Check a user name was given. */
1591 if (port->user_name == NULL || port->user_name[0] == '\0')
1592 ereport(FATAL,
1593 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1594 errmsg("no PostgreSQL user name specified in startup packet")));
1596 /* The database defaults to the user name. */
1597 if (port->database_name == NULL || port->database_name[0] == '\0')
1598 port->database_name = pstrdup(port->user_name);
1600 if (Db_user_namespace)
1603 * If user@, it is a global user, remove '@'. We only want to do this
1604 * if there is an '@' at the end and no earlier in the user string or
1605 * they may fake as a local user of another database attaching to this
1606 * database.
1608 if (strchr(port->user_name, '@') ==
1609 port->user_name + strlen(port->user_name) - 1)
1610 *strchr(port->user_name, '@') = '\0';
1611 else
1613 /* Append '@' and dbname */
1614 char *db_user;
1616 db_user = palloc(strlen(port->user_name) +
1617 strlen(port->database_name) + 2);
1618 sprintf(db_user, "%s@%s", port->user_name, port->database_name);
1619 port->user_name = db_user;
1624 * Truncate given database and user names to length of a Postgres name.
1625 * This avoids lookup failures when overlength names are given.
1627 if (strlen(port->database_name) >= NAMEDATALEN)
1628 port->database_name[NAMEDATALEN - 1] = '\0';
1629 if (strlen(port->user_name) >= NAMEDATALEN)
1630 port->user_name[NAMEDATALEN - 1] = '\0';
1633 * Done putting stuff in TopMemoryContext.
1635 MemoryContextSwitchTo(oldcontext);
1638 * If we're going to reject the connection due to database state, say so
1639 * now instead of wasting cycles on an authentication exchange. (This also
1640 * allows a pg_ping utility to be written.)
1642 switch (port->canAcceptConnections)
1644 case CAC_STARTUP:
1645 ereport(FATAL,
1646 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1647 errmsg("the database system is starting up")));
1648 break;
1649 case CAC_SHUTDOWN:
1650 ereport(FATAL,
1651 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1652 errmsg("the database system is shutting down")));
1653 break;
1654 case CAC_RECOVERY:
1655 ereport(FATAL,
1656 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1657 errmsg("the database system is in recovery mode")));
1658 break;
1659 case CAC_TOOMANY:
1660 ereport(FATAL,
1661 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
1662 errmsg("sorry, too many clients already")));
1663 break;
1664 case CAC_WAITBACKUP:
1665 /* OK for now, will check in InitPostgres */
1666 break;
1667 case CAC_OK:
1668 break;
1671 return STATUS_OK;
1676 * The client has sent a cancel request packet, not a normal
1677 * start-a-new-connection packet. Perform the necessary processing.
1678 * Nothing is sent back to the client.
1680 static void
1681 processCancelRequest(Port *port, void *pkt)
1683 CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
1684 int backendPID;
1685 long cancelAuthCode;
1686 Backend *bp;
1688 #ifndef EXEC_BACKEND
1689 Dlelem *curr;
1690 #else
1691 int i;
1692 #endif
1694 backendPID = (int) ntohl(canc->backendPID);
1695 cancelAuthCode = (long) ntohl(canc->cancelAuthCode);
1698 * See if we have a matching backend. In the EXEC_BACKEND case, we can no
1699 * longer access the postmaster's own backend list, and must rely on the
1700 * duplicate array in shared memory.
1702 #ifndef EXEC_BACKEND
1703 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
1705 bp = (Backend *) DLE_VAL(curr);
1706 #else
1707 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
1709 bp = (Backend *) &ShmemBackendArray[i];
1710 #endif
1711 if (bp->pid == backendPID)
1713 if (bp->cancel_key == cancelAuthCode)
1715 /* Found a match; signal that backend to cancel current op */
1716 ereport(DEBUG2,
1717 (errmsg_internal("processing cancel request: sending SIGINT to process %d",
1718 backendPID)));
1719 signal_child(bp->pid, SIGINT);
1721 else
1722 /* Right PID, wrong key: no way, Jose */
1723 ereport(LOG,
1724 (errmsg("wrong key in cancel request for process %d",
1725 backendPID)));
1726 return;
1730 /* No matching backend */
1731 ereport(LOG,
1732 (errmsg("PID %d in cancel request did not match any process",
1733 backendPID)));
1737 * canAcceptConnections --- check to see if database state allows connections.
1739 static enum CAC_state
1740 canAcceptConnections(void)
1743 * Can't start backends when in startup/shutdown/recovery state.
1745 * In state PM_WAIT_BACKUP only superusers can connect (this must be
1746 * allowed so that a superuser can end online backup mode); we return
1747 * CAC_WAITBACKUP code to indicate that this must be checked later.
1749 if (pmState != PM_RUN)
1751 if (pmState == PM_WAIT_BACKUP)
1752 return CAC_WAITBACKUP; /* allow superusers only */
1753 if (Shutdown > NoShutdown)
1754 return CAC_SHUTDOWN; /* shutdown is pending */
1755 if (pmState == PM_STARTUP && !FatalError)
1756 return CAC_STARTUP; /* normal startup */
1757 return CAC_RECOVERY; /* else must be crash recovery */
1761 * Don't start too many children.
1763 * We allow more connections than we can have backends here because some
1764 * might still be authenticating; they might fail auth, or some existing
1765 * backend might exit before the auth cycle is completed. The exact
1766 * MaxBackends limit is enforced when a new backend tries to join the
1767 * shared-inval backend array.
1769 * In the EXEC_BACKEND case, the limit here must match the size of the
1770 * ShmemBackendArray, since all these processes will have cancel codes.
1772 if (CountChildren() >= 2 * MaxBackends)
1773 return CAC_TOOMANY;
1775 return CAC_OK;
1780 * ConnCreate -- create a local connection data structure
1782 static Port *
1783 ConnCreate(int serverFd)
1785 Port *port;
1787 if (!(port = (Port *) calloc(1, sizeof(Port))))
1789 ereport(LOG,
1790 (errcode(ERRCODE_OUT_OF_MEMORY),
1791 errmsg("out of memory")));
1792 ExitPostmaster(1);
1795 if (StreamConnection(serverFd, port) != STATUS_OK)
1797 if (port->sock >= 0)
1798 StreamClose(port->sock);
1799 ConnFree(port);
1800 port = NULL;
1802 else
1805 * Precompute password salt values to use for this connection. It's
1806 * slightly annoying to do this long in advance of knowing whether
1807 * we'll need 'em or not, but we must do the random() calls before we
1808 * fork, not after. Else the postmaster's random sequence won't get
1809 * advanced, and all backends would end up using the same salt...
1811 RandomSalt(port->md5Salt);
1815 * Allocate GSSAPI specific state struct
1817 #ifndef EXEC_BACKEND
1818 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
1819 port->gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
1820 if (!port->gss)
1822 ereport(LOG,
1823 (errcode(ERRCODE_OUT_OF_MEMORY),
1824 errmsg("out of memory")));
1825 ExitPostmaster(1);
1827 #endif
1828 #endif
1830 return port;
1835 * ConnFree -- free a local connection data structure
1837 static void
1838 ConnFree(Port *conn)
1840 #ifdef USE_SSL
1841 secure_close(conn);
1842 #endif
1843 if (conn->gss)
1844 free(conn->gss);
1845 free(conn);
1850 * ClosePostmasterPorts -- close all the postmaster's open sockets
1852 * This is called during child process startup to release file descriptors
1853 * that are not needed by that child process. The postmaster still has
1854 * them open, of course.
1856 * Note: we pass am_syslogger as a boolean because we don't want to set
1857 * the global variable yet when this is called.
1859 void
1860 ClosePostmasterPorts(bool am_syslogger)
1862 int i;
1864 /* Close the listen sockets */
1865 for (i = 0; i < MAXLISTEN; i++)
1867 if (ListenSocket[i] != -1)
1869 StreamClose(ListenSocket[i]);
1870 ListenSocket[i] = -1;
1874 /* If using syslogger, close the read side of the pipe */
1875 if (!am_syslogger)
1877 #ifndef WIN32
1878 if (syslogPipe[0] >= 0)
1879 close(syslogPipe[0]);
1880 syslogPipe[0] = -1;
1881 #else
1882 if (syslogPipe[0])
1883 CloseHandle(syslogPipe[0]);
1884 syslogPipe[0] = 0;
1885 #endif
1891 * reset_shared -- reset shared memory and semaphores
1893 static void
1894 reset_shared(int port)
1897 * Create or re-create shared memory and semaphores.
1899 * Note: in each "cycle of life" we will normally assign the same IPC keys
1900 * (if using SysV shmem and/or semas), since the port number is used to
1901 * determine IPC keys. This helps ensure that we will clean up dead IPC
1902 * objects if the postmaster crashes and is restarted.
1904 CreateSharedMemoryAndSemaphores(false, port);
1909 * SIGHUP -- reread config files, and tell children to do same
1911 static void
1912 SIGHUP_handler(SIGNAL_ARGS)
1914 int save_errno = errno;
1916 PG_SETMASK(&BlockSig);
1918 if (Shutdown <= SmartShutdown)
1920 ereport(LOG,
1921 (errmsg("received SIGHUP, reloading configuration files")));
1922 ProcessConfigFile(PGC_SIGHUP);
1923 SignalChildren(SIGHUP);
1924 if (BgWriterPID != 0)
1925 signal_child(BgWriterPID, SIGHUP);
1926 if (WalWriterPID != 0)
1927 signal_child(WalWriterPID, SIGHUP);
1928 if (AutoVacPID != 0)
1929 signal_child(AutoVacPID, SIGHUP);
1930 if (PgArchPID != 0)
1931 signal_child(PgArchPID, SIGHUP);
1932 if (SysLoggerPID != 0)
1933 signal_child(SysLoggerPID, SIGHUP);
1934 if (PgStatPID != 0)
1935 signal_child(PgStatPID, SIGHUP);
1937 /* Reload authentication config files too */
1938 if (!load_hba())
1939 ereport(WARNING,
1940 (errmsg("pg_hba.conf not reloaded")));
1942 load_ident();
1944 #ifdef EXEC_BACKEND
1945 /* Update the starting-point file for future children */
1946 write_nondefault_variables(PGC_SIGHUP);
1947 #endif
1950 PG_SETMASK(&UnBlockSig);
1952 errno = save_errno;
1957 * pmdie -- signal handler for processing various postmaster signals.
1959 static void
1960 pmdie(SIGNAL_ARGS)
1962 int save_errno = errno;
1964 PG_SETMASK(&BlockSig);
1966 ereport(DEBUG2,
1967 (errmsg_internal("postmaster received signal %d",
1968 postgres_signal_arg)));
1970 switch (postgres_signal_arg)
1972 case SIGTERM:
1975 * Smart Shutdown:
1977 * Wait for children to end their work, then shut down.
1979 if (Shutdown >= SmartShutdown)
1980 break;
1981 Shutdown = SmartShutdown;
1982 ereport(LOG,
1983 (errmsg("received smart shutdown request")));
1985 if (pmState == PM_RUN)
1987 /* autovacuum workers are told to shut down immediately */
1988 SignalAutovacWorkers(SIGTERM);
1989 /* and the autovac launcher too */
1990 if (AutoVacPID != 0)
1991 signal_child(AutoVacPID, SIGTERM);
1992 /* and the walwriter too */
1993 if (WalWriterPID != 0)
1994 signal_child(WalWriterPID, SIGTERM);
1995 pmState = PM_WAIT_BACKUP;
1999 * Now wait for online backup mode to end and
2000 * backends to exit. If that is already the case,
2001 * PostmasterStateMachine will take the next step.
2003 PostmasterStateMachine();
2004 break;
2006 case SIGINT:
2009 * Fast Shutdown:
2011 * Abort all children with SIGTERM (rollback active transactions
2012 * and exit) and shut down when they are gone.
2014 if (Shutdown >= FastShutdown)
2015 break;
2016 Shutdown = FastShutdown;
2017 ereport(LOG,
2018 (errmsg("received fast shutdown request")));
2020 if (StartupPID != 0)
2021 signal_child(StartupPID, SIGTERM);
2022 if (pmState == PM_RUN || pmState == PM_WAIT_BACKUP)
2024 ereport(LOG,
2025 (errmsg("aborting any active transactions")));
2026 /* shut down all backends and autovac workers */
2027 SignalChildren(SIGTERM);
2028 /* and the autovac launcher too */
2029 if (AutoVacPID != 0)
2030 signal_child(AutoVacPID, SIGTERM);
2031 /* and the walwriter too */
2032 if (WalWriterPID != 0)
2033 signal_child(WalWriterPID, SIGTERM);
2034 pmState = PM_WAIT_BACKENDS;
2038 * Now wait for backends to exit. If there are none,
2039 * PostmasterStateMachine will take the next step.
2041 PostmasterStateMachine();
2042 break;
2044 case SIGQUIT:
2047 * Immediate Shutdown:
2049 * abort all children with SIGQUIT and exit without attempt to
2050 * properly shut down data base system.
2052 ereport(LOG,
2053 (errmsg("received immediate shutdown request")));
2054 SignalChildren(SIGQUIT);
2055 if (StartupPID != 0)
2056 signal_child(StartupPID, SIGQUIT);
2057 if (BgWriterPID != 0)
2058 signal_child(BgWriterPID, SIGQUIT);
2059 if (WalWriterPID != 0)
2060 signal_child(WalWriterPID, SIGQUIT);
2061 if (AutoVacPID != 0)
2062 signal_child(AutoVacPID, SIGQUIT);
2063 if (PgArchPID != 0)
2064 signal_child(PgArchPID, SIGQUIT);
2065 if (PgStatPID != 0)
2066 signal_child(PgStatPID, SIGQUIT);
2067 ExitPostmaster(0);
2068 break;
2071 PG_SETMASK(&UnBlockSig);
2073 errno = save_errno;
2077 * Reaper -- signal handler to cleanup after a child process dies.
2079 static void
2080 reaper(SIGNAL_ARGS)
2082 int save_errno = errno;
2083 int pid; /* process id of dead child process */
2084 int exitstatus; /* its exit status */
2086 /* These macros hide platform variations in getting child status */
2087 #ifdef HAVE_WAITPID
2088 int status; /* child exit status */
2090 #define LOOPTEST() ((pid = waitpid(-1, &status, WNOHANG)) > 0)
2091 #define LOOPHEADER() (exitstatus = status)
2092 #else /* !HAVE_WAITPID */
2093 #ifndef WIN32
2094 union wait status; /* child exit status */
2096 #define LOOPTEST() ((pid = wait3(&status, WNOHANG, NULL)) > 0)
2097 #define LOOPHEADER() (exitstatus = status.w_status)
2098 #else /* WIN32 */
2099 #define LOOPTEST() ((pid = win32_waitpid(&exitstatus)) > 0)
2100 #define LOOPHEADER()
2101 #endif /* WIN32 */
2102 #endif /* HAVE_WAITPID */
2104 PG_SETMASK(&BlockSig);
2106 ereport(DEBUG4,
2107 (errmsg_internal("reaping dead processes")));
2109 while (LOOPTEST())
2111 LOOPHEADER();
2114 * Check if this child was a startup process.
2116 if (pid == StartupPID)
2118 StartupPID = 0;
2119 Assert(pmState == PM_STARTUP);
2121 /* FATAL exit of startup is treated as catastrophic */
2122 if (!EXIT_STATUS_0(exitstatus))
2124 LogChildExit(LOG, _("startup process"),
2125 pid, exitstatus);
2126 ereport(LOG,
2127 (errmsg("aborting startup due to startup process failure")));
2128 ExitPostmaster(1);
2132 * Startup succeeded - we are done with system startup or
2133 * recovery.
2135 FatalError = false;
2138 * Go to shutdown mode if a shutdown request was pending.
2140 if (Shutdown > NoShutdown)
2142 pmState = PM_WAIT_BACKENDS;
2143 /* PostmasterStateMachine logic does the rest */
2144 continue;
2148 * Otherwise, commence normal operations.
2150 pmState = PM_RUN;
2153 * Load the flat authorization file into postmaster's cache. The
2154 * startup process has recomputed this from the database contents,
2155 * so we wait till it finishes before loading it.
2157 load_role();
2160 * Crank up the background writer. It doesn't matter if this
2161 * fails, we'll just try again later.
2163 Assert(BgWriterPID == 0);
2164 BgWriterPID = StartBackgroundWriter();
2167 * Likewise, start other special children as needed. In a restart
2168 * situation, some of them may be alive already.
2170 if (WalWriterPID == 0)
2171 WalWriterPID = StartWalWriter();
2172 if (AutoVacuumingActive() && AutoVacPID == 0)
2173 AutoVacPID = StartAutoVacLauncher();
2174 if (XLogArchivingActive() && PgArchPID == 0)
2175 PgArchPID = pgarch_start();
2176 if (PgStatPID == 0)
2177 PgStatPID = pgstat_start();
2179 /* at this point we are really open for business */
2180 ereport(LOG,
2181 (errmsg("database system is ready to accept connections")));
2183 continue;
2187 * Was it the bgwriter?
2189 if (pid == BgWriterPID)
2191 BgWriterPID = 0;
2192 if (EXIT_STATUS_0(exitstatus) && pmState == PM_SHUTDOWN)
2195 * OK, we saw normal exit of the bgwriter after it's been told
2196 * to shut down. We expect that it wrote a shutdown
2197 * checkpoint. (If for some reason it didn't, recovery will
2198 * occur on next postmaster start.)
2200 * At this point we should have no normal backend children
2201 * left (else we'd not be in PM_SHUTDOWN state) but we might
2202 * have dead_end children to wait for.
2204 * If we have an archiver subprocess, tell it to do a last
2205 * archive cycle and quit; otherwise we can go directly to
2206 * PM_WAIT_DEAD_END state.
2208 Assert(Shutdown > NoShutdown);
2210 if (PgArchPID != 0)
2212 /* Waken archiver for the last time */
2213 signal_child(PgArchPID, SIGUSR2);
2214 pmState = PM_SHUTDOWN_2;
2216 else
2217 pmState = PM_WAIT_DEAD_END;
2220 * We can also shut down the stats collector now; there's
2221 * nothing left for it to do.
2223 if (PgStatPID != 0)
2224 signal_child(PgStatPID, SIGQUIT);
2226 else
2229 * Any unexpected exit of the bgwriter (including FATAL exit)
2230 * is treated as a crash.
2232 HandleChildCrash(pid, exitstatus,
2233 _("background writer process"));
2236 continue;
2240 * Was it the wal writer? Normal exit can be ignored; we'll start a
2241 * new one at the next iteration of the postmaster's main loop, if
2242 * necessary. Any other exit condition is treated as a crash.
2244 if (pid == WalWriterPID)
2246 WalWriterPID = 0;
2247 if (!EXIT_STATUS_0(exitstatus))
2248 HandleChildCrash(pid, exitstatus,
2249 _("WAL writer process"));
2250 continue;
2254 * Was it the autovacuum launcher? Normal exit can be ignored; we'll
2255 * start a new one at the next iteration of the postmaster's main
2256 * loop, if necessary. Any other exit condition is treated as a
2257 * crash.
2259 if (pid == AutoVacPID)
2261 AutoVacPID = 0;
2262 if (!EXIT_STATUS_0(exitstatus))
2263 HandleChildCrash(pid, exitstatus,
2264 _("autovacuum launcher process"));
2265 continue;
2269 * Was it the archiver? If so, just try to start a new one; no need
2270 * to force reset of the rest of the system. (If fail, we'll try
2271 * again in future cycles of the main loop.) But if we were waiting
2272 * for it to shut down, advance to the next shutdown step.
2274 if (pid == PgArchPID)
2276 PgArchPID = 0;
2277 if (!EXIT_STATUS_0(exitstatus))
2278 LogChildExit(LOG, _("archiver process"),
2279 pid, exitstatus);
2280 if (XLogArchivingActive() && pmState == PM_RUN)
2281 PgArchPID = pgarch_start();
2282 else if (pmState == PM_SHUTDOWN_2)
2283 pmState = PM_WAIT_DEAD_END;
2284 continue;
2288 * Was it the statistics collector? If so, just try to start a new
2289 * one; no need to force reset of the rest of the system. (If fail,
2290 * we'll try again in future cycles of the main loop.)
2292 if (pid == PgStatPID)
2294 PgStatPID = 0;
2295 if (!EXIT_STATUS_0(exitstatus))
2296 LogChildExit(LOG, _("statistics collector process"),
2297 pid, exitstatus);
2298 if (pmState == PM_RUN)
2299 PgStatPID = pgstat_start();
2300 continue;
2303 /* Was it the system logger? If so, try to start a new one */
2304 if (pid == SysLoggerPID)
2306 SysLoggerPID = 0;
2307 /* for safety's sake, launch new logger *first* */
2308 SysLoggerPID = SysLogger_Start();
2309 if (!EXIT_STATUS_0(exitstatus))
2310 LogChildExit(LOG, _("system logger process"),
2311 pid, exitstatus);
2312 continue;
2316 * Else do standard backend child cleanup.
2318 CleanupBackend(pid, exitstatus);
2319 } /* loop over pending child-death reports */
2322 * After cleaning out the SIGCHLD queue, see if we have any state changes
2323 * or actions to make.
2325 PostmasterStateMachine();
2327 /* Done with signal handler */
2328 PG_SETMASK(&UnBlockSig);
2330 errno = save_errno;
2335 * CleanupBackend -- cleanup after terminated backend.
2337 * Remove all local state associated with backend.
2339 static void
2340 CleanupBackend(int pid,
2341 int exitstatus) /* child's exit status. */
2343 Dlelem *curr;
2345 LogChildExit(DEBUG2, _("server process"), pid, exitstatus);
2348 * If a backend dies in an ugly way then we must signal all other backends
2349 * to quickdie. If exit status is zero (normal) or one (FATAL exit), we
2350 * assume everything is all right and simply remove the backend from the
2351 * active backend list.
2353 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2355 HandleChildCrash(pid, exitstatus, _("server process"));
2356 return;
2359 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2361 Backend *bp = (Backend *) DLE_VAL(curr);
2363 if (bp->pid == pid)
2365 #ifdef EXEC_BACKEND
2366 if (!bp->dead_end)
2367 ShmemBackendArrayRemove(pid);
2368 #endif
2369 DLRemove(curr);
2370 free(bp);
2371 DLFreeElem(curr);
2372 break;
2378 * HandleChildCrash -- cleanup after failed backend, bgwriter, walwriter,
2379 * or autovacuum.
2381 * The objectives here are to clean up our local state about the child
2382 * process, and to signal all other remaining children to quickdie.
2384 static void
2385 HandleChildCrash(int pid, int exitstatus, const char *procname)
2387 Dlelem *curr,
2388 *next;
2389 Backend *bp;
2392 * Make log entry unless there was a previous crash (if so, nonzero exit
2393 * status is to be expected in SIGQUIT response; don't clutter log)
2395 if (!FatalError)
2397 LogChildExit(LOG, procname, pid, exitstatus);
2398 ereport(LOG,
2399 (errmsg("terminating any other active server processes")));
2402 /* Process regular backends */
2403 for (curr = DLGetHead(BackendList); curr; curr = next)
2405 next = DLGetSucc(curr);
2406 bp = (Backend *) DLE_VAL(curr);
2407 if (bp->pid == pid)
2410 * Found entry for freshly-dead backend, so remove it.
2412 #ifdef EXEC_BACKEND
2413 if (!bp->dead_end)
2414 ShmemBackendArrayRemove(pid);
2415 #endif
2416 DLRemove(curr);
2417 free(bp);
2418 DLFreeElem(curr);
2419 /* Keep looping so we can signal remaining backends */
2421 else
2424 * This backend is still alive. Unless we did so already, tell it
2425 * to commit hara-kiri.
2427 * SIGQUIT is the special signal that says exit without proc_exit
2428 * and let the user know what's going on. But if SendStop is set
2429 * (-s on command line), then we send SIGSTOP instead, so that we
2430 * can get core dumps from all backends by hand.
2432 * We could exclude dead_end children here, but at least in the
2433 * SIGSTOP case it seems better to include them.
2435 if (!FatalError)
2437 ereport(DEBUG2,
2438 (errmsg_internal("sending %s to process %d",
2439 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2440 (int) bp->pid)));
2441 signal_child(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
2446 /* Take care of the bgwriter too */
2447 if (pid == BgWriterPID)
2448 BgWriterPID = 0;
2449 else if (BgWriterPID != 0 && !FatalError)
2451 ereport(DEBUG2,
2452 (errmsg_internal("sending %s to process %d",
2453 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2454 (int) BgWriterPID)));
2455 signal_child(BgWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
2458 /* Take care of the walwriter too */
2459 if (pid == WalWriterPID)
2460 WalWriterPID = 0;
2461 else if (WalWriterPID != 0 && !FatalError)
2463 ereport(DEBUG2,
2464 (errmsg_internal("sending %s to process %d",
2465 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2466 (int) WalWriterPID)));
2467 signal_child(WalWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
2470 /* Take care of the autovacuum launcher too */
2471 if (pid == AutoVacPID)
2472 AutoVacPID = 0;
2473 else if (AutoVacPID != 0 && !FatalError)
2475 ereport(DEBUG2,
2476 (errmsg_internal("sending %s to process %d",
2477 (SendStop ? "SIGSTOP" : "SIGQUIT"),
2478 (int) AutoVacPID)));
2479 signal_child(AutoVacPID, (SendStop ? SIGSTOP : SIGQUIT));
2483 * Force a power-cycle of the pgarch process too. (This isn't absolutely
2484 * necessary, but it seems like a good idea for robustness, and it
2485 * simplifies the state-machine logic in the case where a shutdown request
2486 * arrives during crash processing.)
2488 if (PgArchPID != 0 && !FatalError)
2490 ereport(DEBUG2,
2491 (errmsg_internal("sending %s to process %d",
2492 "SIGQUIT",
2493 (int) PgArchPID)));
2494 signal_child(PgArchPID, SIGQUIT);
2498 * Force a power-cycle of the pgstat process too. (This isn't absolutely
2499 * necessary, but it seems like a good idea for robustness, and it
2500 * simplifies the state-machine logic in the case where a shutdown request
2501 * arrives during crash processing.)
2503 if (PgStatPID != 0 && !FatalError)
2505 ereport(DEBUG2,
2506 (errmsg_internal("sending %s to process %d",
2507 "SIGQUIT",
2508 (int) PgStatPID)));
2509 signal_child(PgStatPID, SIGQUIT);
2510 allow_immediate_pgstat_restart();
2513 /* We do NOT restart the syslogger */
2515 FatalError = true;
2516 /* We now transit into a state of waiting for children to die */
2517 if (pmState == PM_RUN ||
2518 pmState == PM_WAIT_BACKUP ||
2519 pmState == PM_SHUTDOWN)
2520 pmState = PM_WAIT_BACKENDS;
2524 * Log the death of a child process.
2526 static void
2527 LogChildExit(int lev, const char *procname, int pid, int exitstatus)
2529 if (WIFEXITED(exitstatus))
2530 ereport(lev,
2532 /*------
2533 translator: %s is a noun phrase describing a child process, such as
2534 "server process" */
2535 (errmsg("%s (PID %d) exited with exit code %d",
2536 procname, pid, WEXITSTATUS(exitstatus))));
2537 else if (WIFSIGNALED(exitstatus))
2538 #if defined(WIN32)
2539 ereport(lev,
2541 /*------
2542 translator: %s is a noun phrase describing a child process, such as
2543 "server process" */
2544 (errmsg("%s (PID %d) was terminated by exception 0x%X",
2545 procname, pid, WTERMSIG(exitstatus)),
2546 errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value.")));
2547 #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST
2548 ereport(lev,
2550 /*------
2551 translator: %s is a noun phrase describing a child process, such as
2552 "server process" */
2553 (errmsg("%s (PID %d) was terminated by signal %d: %s",
2554 procname, pid, WTERMSIG(exitstatus),
2555 WTERMSIG(exitstatus) < NSIG ?
2556 sys_siglist[WTERMSIG(exitstatus)] : "(unknown)")));
2557 #else
2558 ereport(lev,
2560 /*------
2561 translator: %s is a noun phrase describing a child process, such as
2562 "server process" */
2563 (errmsg("%s (PID %d) was terminated by signal %d",
2564 procname, pid, WTERMSIG(exitstatus))));
2565 #endif
2566 else
2567 ereport(lev,
2569 /*------
2570 translator: %s is a noun phrase describing a child process, such as
2571 "server process" */
2572 (errmsg("%s (PID %d) exited with unrecognized status %d",
2573 procname, pid, exitstatus)));
2577 * Advance the postmaster's state machine and take actions as appropriate
2579 * This is common code for pmdie() and reaper(), which receive the signals
2580 * that might mean we need to change state.
2582 static void
2583 PostmasterStateMachine(void)
2585 if (pmState == PM_WAIT_BACKUP)
2588 * PM_WAIT_BACKUP state ends when online backup mode is not active.
2590 if (!BackupInProgress())
2591 pmState = PM_WAIT_BACKENDS;
2595 * If we are in a state-machine state that implies waiting for backends to
2596 * exit, see if they're all gone, and change state if so.
2598 if (pmState == PM_WAIT_BACKENDS)
2601 * PM_WAIT_BACKENDS state ends when we have no regular backends
2602 * (including autovac workers) and no walwriter or autovac launcher.
2603 * If we are doing crash recovery then we expect the bgwriter to exit
2604 * too, otherwise not. The archiver, stats, and syslogger processes
2605 * are disregarded since they are not connected to shared memory; we
2606 * also disregard dead_end children here.
2608 if (CountChildren() == 0 &&
2609 StartupPID == 0 &&
2610 (BgWriterPID == 0 || !FatalError) &&
2611 WalWriterPID == 0 &&
2612 AutoVacPID == 0)
2614 if (FatalError)
2617 * Start waiting for dead_end children to die. This state
2618 * change causes ServerLoop to stop creating new ones.
2620 pmState = PM_WAIT_DEAD_END;
2623 * We already SIGQUIT'd the archiver and stats processes,
2624 * if any, when we entered FatalError state.
2627 else
2630 * If we get here, we are proceeding with normal shutdown. All
2631 * the regular children are gone, and it's time to tell the
2632 * bgwriter to do a shutdown checkpoint.
2634 Assert(Shutdown > NoShutdown);
2635 /* Start the bgwriter if not running */
2636 if (BgWriterPID == 0)
2637 BgWriterPID = StartBackgroundWriter();
2638 /* And tell it to shut down */
2639 if (BgWriterPID != 0)
2641 signal_child(BgWriterPID, SIGUSR2);
2642 pmState = PM_SHUTDOWN;
2644 else
2647 * If we failed to fork a bgwriter, just shut down. Any
2648 * required cleanup will happen at next restart. We set
2649 * FatalError so that an "abnormal shutdown" message gets
2650 * logged when we exit.
2652 FatalError = true;
2653 pmState = PM_WAIT_DEAD_END;
2655 /* Kill the archiver and stats collector too */
2656 if (PgArchPID != 0)
2657 signal_child(PgArchPID, SIGQUIT);
2658 if (PgStatPID != 0)
2659 signal_child(PgStatPID, SIGQUIT);
2665 if (pmState == PM_WAIT_DEAD_END)
2668 * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
2669 * (ie, no dead_end children remain), and the archiver and stats
2670 * collector are gone too.
2672 * The reason we wait for those two is to protect them against a new
2673 * postmaster starting conflicting subprocesses; this isn't an
2674 * ironclad protection, but it at least helps in the
2675 * shutdown-and-immediately-restart scenario. Note that they have
2676 * already been sent appropriate shutdown signals, either during a
2677 * normal state transition leading up to PM_WAIT_DEAD_END, or during
2678 * FatalError processing.
2680 if (DLGetHead(BackendList) == NULL &&
2681 PgArchPID == 0 && PgStatPID == 0)
2683 /* These other guys should be dead already */
2684 Assert(StartupPID == 0);
2685 Assert(BgWriterPID == 0);
2686 Assert(WalWriterPID == 0);
2687 Assert(AutoVacPID == 0);
2688 /* syslogger is not considered here */
2689 pmState = PM_NO_CHILDREN;
2694 * If we've been told to shut down, we exit as soon as there are no
2695 * remaining children. If there was a crash, cleanup will occur at the
2696 * next startup. (Before PostgreSQL 8.3, we tried to recover from the
2697 * crash before exiting, but that seems unwise if we are quitting because
2698 * we got SIGTERM from init --- there may well not be time for recovery
2699 * before init decides to SIGKILL us.)
2701 * Note that the syslogger continues to run. It will exit when it sees
2702 * EOF on its input pipe, which happens when there are no more upstream
2703 * processes.
2705 if (Shutdown > NoShutdown && pmState == PM_NO_CHILDREN)
2707 if (FatalError)
2709 ereport(LOG, (errmsg("abnormal database system shutdown")));
2710 ExitPostmaster(1);
2712 else
2715 * Terminate backup mode to avoid recovery after a
2716 * clean fast shutdown.
2718 CancelBackup();
2720 /* Normal exit from the postmaster is here */
2721 ExitPostmaster(0);
2726 * If we need to recover from a crash, wait for all non-syslogger
2727 * children to exit, then reset shmem and StartupDataBase.
2729 if (FatalError && pmState == PM_NO_CHILDREN)
2731 ereport(LOG,
2732 (errmsg("all server processes terminated; reinitializing")));
2734 shmem_exit(0);
2735 reset_shared(PostPortNumber);
2737 StartupPID = StartupDataBase();
2738 Assert(StartupPID != 0);
2739 pmState = PM_STARTUP;
2745 * Send a signal to a postmaster child process
2747 * On systems that have setsid(), each child process sets itself up as a
2748 * process group leader. For signals that are generally interpreted in the
2749 * appropriate fashion, we signal the entire process group not just the
2750 * direct child process. This allows us to, for example, SIGQUIT a blocked
2751 * archive_recovery script, or SIGINT a script being run by a backend via
2752 * system().
2754 * There is a race condition for recently-forked children: they might not
2755 * have executed setsid() yet. So we signal the child directly as well as
2756 * the group. We assume such a child will handle the signal before trying
2757 * to spawn any grandchild processes. We also assume that signaling the
2758 * child twice will not cause any problems.
2760 static void
2761 signal_child(pid_t pid, int signal)
2763 if (kill(pid, signal) < 0)
2764 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
2765 #ifdef HAVE_SETSID
2766 switch (signal)
2768 case SIGINT:
2769 case SIGTERM:
2770 case SIGQUIT:
2771 case SIGSTOP:
2772 if (kill(-pid, signal) < 0)
2773 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) (-pid), signal);
2774 break;
2775 default:
2776 break;
2778 #endif
2782 * Send a signal to all backend children, including autovacuum workers
2783 * (but NOT special children; dead_end children are never signaled, either).
2784 * If only_autovac is TRUE, only the autovacuum worker processes are signalled.
2786 static void
2787 SignalSomeChildren(int signal, bool only_autovac)
2789 Dlelem *curr;
2791 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2793 Backend *bp = (Backend *) DLE_VAL(curr);
2795 if (bp->dead_end)
2796 continue;
2797 if (only_autovac && !bp->is_autovacuum)
2798 continue;
2800 ereport(DEBUG4,
2801 (errmsg_internal("sending signal %d to process %d",
2802 signal, (int) bp->pid)));
2803 signal_child(bp->pid, signal);
2808 * BackendStartup -- start backend process
2810 * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
2812 * Note: if you change this code, also consider StartAutovacuumWorker.
2814 static int
2815 BackendStartup(Port *port)
2817 Backend *bn; /* for backend cleanup */
2818 pid_t pid;
2821 * Compute the cancel key that will be assigned to this backend. The
2822 * backend will have its own copy in the forked-off process' value of
2823 * MyCancelKey, so that it can transmit the key to the frontend.
2825 MyCancelKey = PostmasterRandom();
2828 * Make room for backend data structure. Better before the fork() so we
2829 * can handle failure cleanly.
2831 bn = (Backend *) malloc(sizeof(Backend));
2832 if (!bn)
2834 ereport(LOG,
2835 (errcode(ERRCODE_OUT_OF_MEMORY),
2836 errmsg("out of memory")));
2837 return STATUS_ERROR;
2840 /* Pass down canAcceptConnections state */
2841 port->canAcceptConnections = canAcceptConnections();
2843 #ifdef EXEC_BACKEND
2844 pid = backend_forkexec(port);
2845 #else /* !EXEC_BACKEND */
2846 pid = fork_process();
2847 if (pid == 0) /* child */
2849 free(bn);
2852 * Let's clean up ourselves as the postmaster child, and close the
2853 * postmaster's listen sockets. (In EXEC_BACKEND case this is all
2854 * done in SubPostmasterMain.)
2856 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
2858 MyProcPid = getpid(); /* reset MyProcPid */
2860 MyStartTime = time(NULL);
2862 /* We don't want the postmaster's proc_exit() handlers */
2863 on_exit_reset();
2865 /* Close the postmaster's sockets */
2866 ClosePostmasterPorts(false);
2868 /* Perform additional initialization and client authentication */
2869 BackendInitialize(port);
2871 /* And run the backend */
2872 proc_exit(BackendRun(port));
2874 #endif /* EXEC_BACKEND */
2876 if (pid < 0)
2878 /* in parent, fork failed */
2879 int save_errno = errno;
2881 free(bn);
2882 errno = save_errno;
2883 ereport(LOG,
2884 (errmsg("could not fork new process for connection: %m")));
2885 report_fork_failure_to_client(port, save_errno);
2886 return STATUS_ERROR;
2889 /* in parent, successful fork */
2890 ereport(DEBUG2,
2891 (errmsg_internal("forked new backend, pid=%d socket=%d",
2892 (int) pid, port->sock)));
2895 * Everything's been successful, it's safe to add this backend to our list
2896 * of backends.
2898 bn->pid = pid;
2899 bn->cancel_key = MyCancelKey;
2900 bn->is_autovacuum = false;
2901 bn->dead_end = (port->canAcceptConnections != CAC_OK &&
2902 port->canAcceptConnections != CAC_WAITBACKUP);
2903 DLAddHead(BackendList, DLNewElem(bn));
2904 #ifdef EXEC_BACKEND
2905 if (!bn->dead_end)
2906 ShmemBackendArrayAdd(bn);
2907 #endif
2909 return STATUS_OK;
2913 * Try to report backend fork() failure to client before we close the
2914 * connection. Since we do not care to risk blocking the postmaster on
2915 * this connection, we set the connection to non-blocking and try only once.
2917 * This is grungy special-purpose code; we cannot use backend libpq since
2918 * it's not up and running.
2920 static void
2921 report_fork_failure_to_client(Port *port, int errnum)
2923 char buffer[1000];
2924 int rc;
2926 /* Format the error message packet (always V2 protocol) */
2927 snprintf(buffer, sizeof(buffer), "E%s%s\n",
2928 _("could not fork new process for connection: "),
2929 strerror(errnum));
2931 /* Set port to non-blocking. Don't do send() if this fails */
2932 if (!pg_set_noblock(port->sock))
2933 return;
2935 /* We'll retry after EINTR, but ignore all other failures */
2938 rc = send(port->sock, buffer, strlen(buffer) + 1, 0);
2939 } while (rc < 0 && errno == EINTR);
2944 * split_opts -- split a string of options and append it to an argv array
2946 * NB: the string is destructively modified!
2948 * Since no current POSTGRES arguments require any quoting characters,
2949 * we can use the simple-minded tactic of assuming each set of space-
2950 * delimited characters is a separate argv element.
2952 * If you don't like that, well, we *used* to pass the whole option string
2953 * as ONE argument to execl(), which was even less intelligent...
2955 static void
2956 split_opts(char **argv, int *argcp, char *s)
2958 while (s && *s)
2960 while (isspace((unsigned char) *s))
2961 ++s;
2962 if (*s == '\0')
2963 break;
2964 argv[(*argcp)++] = s;
2965 while (*s && !isspace((unsigned char) *s))
2966 ++s;
2967 if (*s)
2968 *s++ = '\0';
2974 * BackendInitialize -- initialize an interactive (postmaster-child)
2975 * backend process, and perform client authentication.
2977 * returns: nothing. Will not return at all if there's any failure.
2979 * Note: this code does not depend on having any access to shared memory.
2980 * In the EXEC_BACKEND case, we are physically attached to shared memory
2981 * but have not yet set up most of our local pointers to shmem structures.
2983 static void
2984 BackendInitialize(Port *port)
2986 int status;
2987 char remote_host[NI_MAXHOST];
2988 char remote_port[NI_MAXSERV];
2989 char remote_ps_data[NI_MAXHOST];
2991 /* Save port etc. for ps status */
2992 MyProcPort = port;
2995 * PreAuthDelay is a debugging aid for investigating problems in the
2996 * authentication cycle: it can be set in postgresql.conf to allow time to
2997 * attach to the newly-forked backend with a debugger. (See also the -W
2998 * backend switch, which we allow clients to pass through PGOPTIONS, but
2999 * it is not honored until after authentication.)
3001 if (PreAuthDelay > 0)
3002 pg_usleep(PreAuthDelay * 1000000L);
3004 ClientAuthInProgress = true; /* limit visibility of log messages */
3006 /* save process start time */
3007 port->SessionStartTime = GetCurrentTimestamp();
3008 MyStartTime = timestamptz_to_time_t(port->SessionStartTime);
3010 /* set these to empty in case they are needed before we set them up */
3011 port->remote_host = "";
3012 port->remote_port = "";
3015 * Initialize libpq and enable reporting of ereport errors to the client.
3016 * Must do this now because authentication uses libpq to send messages.
3018 pq_init(); /* initialize libpq to talk to client */
3019 whereToSendOutput = DestRemote; /* now safe to ereport to client */
3022 * If possible, make this process a group leader, so that the postmaster
3023 * can signal any child processes too. (We do this now on the off chance
3024 * that something might spawn a child process during authentication.)
3026 #ifdef HAVE_SETSID
3027 if (setsid() < 0)
3028 elog(FATAL, "setsid() failed: %m");
3029 #endif
3032 * We arrange for a simple exit(1) if we receive SIGTERM or SIGQUIT during
3033 * any client authentication related communication. Otherwise the
3034 * postmaster cannot shutdown the database FAST or IMMED cleanly if a
3035 * buggy client blocks a backend during authentication.
3037 pqsignal(SIGTERM, authdie);
3038 pqsignal(SIGQUIT, authdie);
3039 pqsignal(SIGALRM, authdie);
3040 PG_SETMASK(&AuthBlockSig);
3043 * Get the remote host name and port for logging and status display.
3045 remote_host[0] = '\0';
3046 remote_port[0] = '\0';
3047 if (pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
3048 remote_host, sizeof(remote_host),
3049 remote_port, sizeof(remote_port),
3050 (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV))
3052 int ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
3053 remote_host, sizeof(remote_host),
3054 remote_port, sizeof(remote_port),
3055 NI_NUMERICHOST | NI_NUMERICSERV);
3057 if (ret)
3058 ereport(WARNING,
3059 (errmsg_internal("pg_getnameinfo_all() failed: %s",
3060 gai_strerror(ret))));
3062 snprintf(remote_ps_data, sizeof(remote_ps_data),
3063 remote_port[0] == '\0' ? "%s" : "%s(%s)",
3064 remote_host, remote_port);
3066 if (Log_connections)
3067 ereport(LOG,
3068 (errmsg("connection received: host=%s%s%s",
3069 remote_host, remote_port[0] ? " port=" : "",
3070 remote_port)));
3073 * save remote_host and remote_port in port structure
3075 port->remote_host = strdup(remote_host);
3076 port->remote_port = strdup(remote_port);
3079 * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
3080 * etcetera from the postmaster, and have to load them ourselves. Build
3081 * the PostmasterContext (which didn't exist before, in this process) to
3082 * contain the data.
3084 * FIXME: [fork/exec] Ugh. Is there a way around this overhead?
3086 #ifdef EXEC_BACKEND
3087 Assert(PostmasterContext == NULL);
3088 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
3089 "Postmaster",
3090 ALLOCSET_DEFAULT_MINSIZE,
3091 ALLOCSET_DEFAULT_INITSIZE,
3092 ALLOCSET_DEFAULT_MAXSIZE);
3093 MemoryContextSwitchTo(PostmasterContext);
3095 if (!load_hba())
3098 * It makes no sense continue if we fail to load the HBA file, since
3099 * there is no way to connect to the database in this case.
3101 ereport(FATAL,
3102 (errmsg("could not load pg_hba.conf")));
3104 load_ident();
3105 load_role();
3106 #endif
3109 * Ready to begin client interaction. We will give up and exit(0) after a
3110 * time delay, so that a broken client can't hog a connection
3111 * indefinitely. PreAuthDelay doesn't count against the time limit.
3113 if (!enable_sig_alarm(AuthenticationTimeout * 1000, false))
3114 elog(FATAL, "could not set timer for authorization timeout");
3117 * Receive the startup packet (which might turn out to be a cancel request
3118 * packet).
3120 status = ProcessStartupPacket(port, false);
3122 if (status != STATUS_OK)
3123 proc_exit(0);
3126 * Now that we have the user and database name, we can set the process
3127 * title for ps. It's good to do this as early as possible in startup.
3129 init_ps_display(port->user_name, port->database_name, remote_ps_data,
3130 update_process_title ? "authentication" : "");
3133 * Now perform authentication exchange.
3135 ClientAuthentication(port); /* might not return, if failure */
3138 * Done with authentication. Disable timeout, and prevent SIGTERM/SIGQUIT
3139 * again until backend startup is complete.
3141 if (!disable_sig_alarm(false))
3142 elog(FATAL, "could not disable timer for authorization timeout");
3143 PG_SETMASK(&BlockSig);
3145 if (Log_connections)
3146 ereport(LOG,
3147 (errmsg("connection authorized: user=%s database=%s",
3148 port->user_name, port->database_name)));
3153 * BackendRun -- set up the backend's argument list and invoke PostgresMain()
3155 * returns:
3156 * Shouldn't return at all.
3157 * If PostgresMain() fails, return status.
3159 static int
3160 BackendRun(Port *port)
3162 char **av;
3163 int maxac;
3164 int ac;
3165 long secs;
3166 int usecs;
3167 char protobuf[32];
3168 int i;
3171 * Don't want backend to be able to see the postmaster random number
3172 * generator state. We have to clobber the static random_seed *and* start
3173 * a new random sequence in the random() library function.
3175 random_seed = 0;
3176 random_start_time.tv_usec = 0;
3177 /* slightly hacky way to get integer microseconds part of timestamptz */
3178 TimestampDifference(0, port->SessionStartTime, &secs, &usecs);
3179 srandom((unsigned int) (MyProcPid ^ usecs));
3181 /* ----------------
3182 * Now, build the argv vector that will be given to PostgresMain.
3184 * The layout of the command line is
3185 * postgres [secure switches] -y databasename [insecure switches]
3186 * where the switches after -y come from the client request.
3188 * The maximum possible number of commandline arguments that could come
3189 * from ExtraOptions or port->cmdline_options is (strlen + 1) / 2; see
3190 * split_opts().
3191 * ----------------
3193 maxac = 10; /* for fixed args supplied below */
3194 maxac += (strlen(ExtraOptions) + 1) / 2;
3195 if (port->cmdline_options)
3196 maxac += (strlen(port->cmdline_options) + 1) / 2;
3198 av = (char **) MemoryContextAlloc(TopMemoryContext,
3199 maxac * sizeof(char *));
3200 ac = 0;
3202 av[ac++] = "postgres";
3205 * Pass any backend switches specified with -o in the postmaster's own
3206 * command line. We assume these are secure. (It's OK to mangle
3207 * ExtraOptions now, since we're safely inside a subprocess.)
3209 split_opts(av, &ac, ExtraOptions);
3211 /* Tell the backend what protocol the frontend is using. */
3212 snprintf(protobuf, sizeof(protobuf), "-v%u", port->proto);
3213 av[ac++] = protobuf;
3216 * Tell the backend it is being called from the postmaster, and which
3217 * database to use. -y marks the end of secure switches.
3219 av[ac++] = "-y";
3220 av[ac++] = port->database_name;
3223 * Pass the (insecure) option switches from the connection request. (It's
3224 * OK to mangle port->cmdline_options now.)
3226 if (port->cmdline_options)
3227 split_opts(av, &ac, port->cmdline_options);
3229 av[ac] = NULL;
3231 Assert(ac < maxac);
3234 * Release postmaster's working memory context so that backend can recycle
3235 * the space. Note this does not trash *MyProcPort, because ConnCreate()
3236 * allocated that space with malloc() ... else we'd need to copy the Port
3237 * data here. Also, subsidiary data such as the username isn't lost
3238 * either; see ProcessStartupPacket().
3240 MemoryContextSwitchTo(TopMemoryContext);
3241 MemoryContextDelete(PostmasterContext);
3242 PostmasterContext = NULL;
3245 * Debug: print arguments being passed to backend
3247 ereport(DEBUG3,
3248 (errmsg_internal("%s child[%d]: starting with (",
3249 progname, (int) getpid())));
3250 for (i = 0; i < ac; ++i)
3251 ereport(DEBUG3,
3252 (errmsg_internal("\t%s", av[i])));
3253 ereport(DEBUG3,
3254 (errmsg_internal(")")));
3256 ClientAuthInProgress = false; /* client_min_messages is active now */
3258 return (PostgresMain(ac, av, port->user_name));
3262 #ifdef EXEC_BACKEND
3265 * postmaster_forkexec -- fork and exec a postmaster subprocess
3267 * The caller must have set up the argv array already, except for argv[2]
3268 * which will be filled with the name of the temp variable file.
3270 * Returns the child process PID, or -1 on fork failure (a suitable error
3271 * message has been logged on failure).
3273 * All uses of this routine will dispatch to SubPostmasterMain in the
3274 * child process.
3276 pid_t
3277 postmaster_forkexec(int argc, char *argv[])
3279 Port port;
3281 /* This entry point passes dummy values for the Port variables */
3282 memset(&port, 0, sizeof(port));
3283 return internal_forkexec(argc, argv, &port);
3287 * backend_forkexec -- fork/exec off a backend process
3289 * Some operating systems (WIN32) don't have fork() so we have to simulate
3290 * it by storing parameters that need to be passed to the child and
3291 * then create a new child process.
3293 * returns the pid of the fork/exec'd process, or -1 on failure
3295 static pid_t
3296 backend_forkexec(Port *port)
3298 char *av[4];
3299 int ac = 0;
3301 av[ac++] = "postgres";
3302 av[ac++] = "--forkbackend";
3303 av[ac++] = NULL; /* filled in by internal_forkexec */
3305 av[ac] = NULL;
3306 Assert(ac < lengthof(av));
3308 return internal_forkexec(ac, av, port);
3311 #ifndef WIN32
3314 * internal_forkexec non-win32 implementation
3316 * - writes out backend variables to the parameter file
3317 * - fork():s, and then exec():s the child process
3319 static pid_t
3320 internal_forkexec(int argc, char *argv[], Port *port)
3322 static unsigned long tmpBackendFileNum = 0;
3323 pid_t pid;
3324 char tmpfilename[MAXPGPATH];
3325 BackendParameters param;
3326 FILE *fp;
3328 if (!save_backend_variables(&param, port))
3329 return -1; /* log made by save_backend_variables */
3331 /* Calculate name for temp file */
3332 snprintf(tmpfilename, MAXPGPATH, "%s/%s.backend_var.%d.%lu",
3333 PG_TEMP_FILES_DIR, PG_TEMP_FILE_PREFIX,
3334 MyProcPid, ++tmpBackendFileNum);
3336 /* Open file */
3337 fp = AllocateFile(tmpfilename, PG_BINARY_W);
3338 if (!fp)
3340 /* As in OpenTemporaryFile, try to make the temp-file directory */
3341 mkdir(PG_TEMP_FILES_DIR, S_IRWXU);
3343 fp = AllocateFile(tmpfilename, PG_BINARY_W);
3344 if (!fp)
3346 ereport(LOG,
3347 (errcode_for_file_access(),
3348 errmsg("could not create file \"%s\": %m",
3349 tmpfilename)));
3350 return -1;
3354 if (fwrite(&param, sizeof(param), 1, fp) != 1)
3356 ereport(LOG,
3357 (errcode_for_file_access(),
3358 errmsg("could not write to file \"%s\": %m", tmpfilename)));
3359 FreeFile(fp);
3360 return -1;
3363 /* Release file */
3364 if (FreeFile(fp))
3366 ereport(LOG,
3367 (errcode_for_file_access(),
3368 errmsg("could not write to file \"%s\": %m", tmpfilename)));
3369 return -1;
3372 /* Make sure caller set up argv properly */
3373 Assert(argc >= 3);
3374 Assert(argv[argc] == NULL);
3375 Assert(strncmp(argv[1], "--fork", 6) == 0);
3376 Assert(argv[2] == NULL);
3378 /* Insert temp file name after --fork argument */
3379 argv[2] = tmpfilename;
3381 /* Fire off execv in child */
3382 if ((pid = fork_process()) == 0)
3384 if (execv(postgres_exec_path, argv) < 0)
3386 ereport(LOG,
3387 (errmsg("could not execute server process \"%s\": %m",
3388 postgres_exec_path)));
3389 /* We're already in the child process here, can't return */
3390 exit(1);
3394 return pid; /* Parent returns pid, or -1 on fork failure */
3396 #else /* WIN32 */
3399 * internal_forkexec win32 implementation
3401 * - starts backend using CreateProcess(), in suspended state
3402 * - writes out backend variables to the parameter file
3403 * - during this, duplicates handles and sockets required for
3404 * inheritance into the new process
3405 * - resumes execution of the new process once the backend parameter
3406 * file is complete.
3408 static pid_t
3409 internal_forkexec(int argc, char *argv[], Port *port)
3411 STARTUPINFO si;
3412 PROCESS_INFORMATION pi;
3413 int i;
3414 int j;
3415 char cmdLine[MAXPGPATH * 2];
3416 HANDLE paramHandle;
3417 BackendParameters *param;
3418 SECURITY_ATTRIBUTES sa;
3419 char paramHandleStr[32];
3420 win32_deadchild_waitinfo *childinfo;
3422 /* Make sure caller set up argv properly */
3423 Assert(argc >= 3);
3424 Assert(argv[argc] == NULL);
3425 Assert(strncmp(argv[1], "--fork", 6) == 0);
3426 Assert(argv[2] == NULL);
3428 /* Set up shared memory for parameter passing */
3429 ZeroMemory(&sa, sizeof(sa));
3430 sa.nLength = sizeof(sa);
3431 sa.bInheritHandle = TRUE;
3432 paramHandle = CreateFileMapping(INVALID_HANDLE_VALUE,
3433 &sa,
3434 PAGE_READWRITE,
3436 sizeof(BackendParameters),
3437 NULL);
3438 if (paramHandle == INVALID_HANDLE_VALUE)
3440 elog(LOG, "could not create backend parameter file mapping: error code %d",
3441 (int) GetLastError());
3442 return -1;
3445 param = MapViewOfFile(paramHandle, FILE_MAP_WRITE, 0, 0, sizeof(BackendParameters));
3446 if (!param)
3448 elog(LOG, "could not map backend parameter memory: error code %d",
3449 (int) GetLastError());
3450 CloseHandle(paramHandle);
3451 return -1;
3454 /* Insert temp file name after --fork argument */
3455 sprintf(paramHandleStr, "%lu", (DWORD) paramHandle);
3456 argv[2] = paramHandleStr;
3458 /* Format the cmd line */
3459 cmdLine[sizeof(cmdLine) - 1] = '\0';
3460 cmdLine[sizeof(cmdLine) - 2] = '\0';
3461 snprintf(cmdLine, sizeof(cmdLine) - 1, "\"%s\"", postgres_exec_path);
3462 i = 0;
3463 while (argv[++i] != NULL)
3465 j = strlen(cmdLine);
3466 snprintf(cmdLine + j, sizeof(cmdLine) - 1 - j, " \"%s\"", argv[i]);
3468 if (cmdLine[sizeof(cmdLine) - 2] != '\0')
3470 elog(LOG, "subprocess command line too long");
3471 return -1;
3474 memset(&pi, 0, sizeof(pi));
3475 memset(&si, 0, sizeof(si));
3476 si.cb = sizeof(si);
3479 * Create the subprocess in a suspended state. This will be resumed later,
3480 * once we have written out the parameter file.
3482 if (!CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, CREATE_SUSPENDED,
3483 NULL, NULL, &si, &pi))
3485 elog(LOG, "CreateProcess call failed: %m (error code %d)",
3486 (int) GetLastError());
3487 return -1;
3490 if (!save_backend_variables(param, port, pi.hProcess, pi.dwProcessId))
3493 * log made by save_backend_variables, but we have to clean up the
3494 * mess with the half-started process
3496 if (!TerminateProcess(pi.hProcess, 255))
3497 ereport(ERROR,
3498 (errmsg_internal("could not terminate unstarted process: error code %d",
3499 (int) GetLastError())));
3500 CloseHandle(pi.hProcess);
3501 CloseHandle(pi.hThread);
3502 return -1; /* log made by save_backend_variables */
3505 /* Drop the shared memory that is now inherited to the backend */
3506 if (!UnmapViewOfFile(param))
3507 elog(LOG, "could not unmap view of backend parameter file: error code %d",
3508 (int) GetLastError());
3509 if (!CloseHandle(paramHandle))
3510 elog(LOG, "could not close handle to backend parameter file: error code %d",
3511 (int) GetLastError());
3514 * Now that the backend variables are written out, we start the child
3515 * thread so it can start initializing while we set up the rest of the
3516 * parent state.
3518 if (ResumeThread(pi.hThread) == -1)
3520 if (!TerminateProcess(pi.hProcess, 255))
3522 ereport(ERROR,
3523 (errmsg_internal("could not terminate unstartable process: error code %d",
3524 (int) GetLastError())));
3525 CloseHandle(pi.hProcess);
3526 CloseHandle(pi.hThread);
3527 return -1;
3529 CloseHandle(pi.hProcess);
3530 CloseHandle(pi.hThread);
3531 ereport(ERROR,
3532 (errmsg_internal("could not resume thread of unstarted process: error code %d",
3533 (int) GetLastError())));
3534 return -1;
3538 * Queue a waiter for to signal when this child dies. The wait will be
3539 * handled automatically by an operating system thread pool.
3541 * Note: use malloc instead of palloc, since it needs to be thread-safe.
3542 * Struct will be free():d from the callback function that runs on a
3543 * different thread.
3545 childinfo = malloc(sizeof(win32_deadchild_waitinfo));
3546 if (!childinfo)
3547 ereport(FATAL,
3548 (errcode(ERRCODE_OUT_OF_MEMORY),
3549 errmsg("out of memory")));
3551 childinfo->procHandle = pi.hProcess;
3552 childinfo->procId = pi.dwProcessId;
3554 if (!RegisterWaitForSingleObject(&childinfo->waitHandle,
3555 pi.hProcess,
3556 pgwin32_deadchild_callback,
3557 childinfo,
3558 INFINITE,
3559 WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD))
3560 ereport(FATAL,
3561 (errmsg_internal("could not register process for wait: error code %d",
3562 (int) GetLastError())));
3564 /* Don't close pi.hProcess here - the wait thread needs access to it */
3566 CloseHandle(pi.hThread);
3568 return pi.dwProcessId;
3570 #endif /* WIN32 */
3574 * SubPostmasterMain -- Get the fork/exec'd process into a state equivalent
3575 * to what it would be if we'd simply forked on Unix, and then
3576 * dispatch to the appropriate place.
3578 * The first two command line arguments are expected to be "--forkFOO"
3579 * (where FOO indicates which postmaster child we are to become), and
3580 * the name of a variables file that we can read to load data that would
3581 * have been inherited by fork() on Unix. Remaining arguments go to the
3582 * subprocess FooMain() routine.
3585 SubPostmasterMain(int argc, char *argv[])
3587 Port port;
3589 /* Do this sooner rather than later... */
3590 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
3592 MyProcPid = getpid(); /* reset MyProcPid */
3594 MyStartTime = time(NULL);
3597 * make sure stderr is in binary mode before anything can possibly be
3598 * written to it, in case it's actually the syslogger pipe, so the pipe
3599 * chunking protocol isn't disturbed. Non-logpipe data gets translated on
3600 * redirection (e.g. via pg_ctl -l) anyway.
3602 #ifdef WIN32
3603 _setmode(fileno(stderr), _O_BINARY);
3604 #endif
3606 /* Lose the postmaster's on-exit routines (really a no-op) */
3607 on_exit_reset();
3609 /* In EXEC_BACKEND case we will not have inherited these settings */
3610 IsPostmasterEnvironment = true;
3611 whereToSendOutput = DestNone;
3613 /* Setup essential subsystems (to ensure elog() behaves sanely) */
3614 MemoryContextInit();
3615 InitializeGUCOptions();
3617 /* Read in the variables file */
3618 memset(&port, 0, sizeof(Port));
3619 read_backend_variables(argv[2], &port);
3622 * Set up memory area for GSS information. Mirrors the code in ConnCreate
3623 * for the non-exec case.
3625 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
3626 port.gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
3627 if (!port.gss)
3628 ereport(FATAL,
3629 (errcode(ERRCODE_OUT_OF_MEMORY),
3630 errmsg("out of memory")));
3631 #endif
3634 /* Check we got appropriate args */
3635 if (argc < 3)
3636 elog(FATAL, "invalid subpostmaster invocation");
3639 * If appropriate, physically re-attach to shared memory segment. We want
3640 * to do this before going any further to ensure that we can attach at the
3641 * same address the postmaster used.
3643 if (strcmp(argv[1], "--forkbackend") == 0 ||
3644 strcmp(argv[1], "--forkavlauncher") == 0 ||
3645 strcmp(argv[1], "--forkavworker") == 0 ||
3646 strcmp(argv[1], "--forkboot") == 0)
3647 PGSharedMemoryReAttach();
3649 /* autovacuum needs this set before calling InitProcess */
3650 if (strcmp(argv[1], "--forkavlauncher") == 0)
3651 AutovacuumLauncherIAm();
3652 if (strcmp(argv[1], "--forkavworker") == 0)
3653 AutovacuumWorkerIAm();
3656 * Start our win32 signal implementation. This has to be done after we
3657 * read the backend variables, because we need to pick up the signal pipe
3658 * from the parent process.
3660 #ifdef WIN32
3661 pgwin32_signal_initialize();
3662 #endif
3664 /* In EXEC_BACKEND case we will not have inherited these settings */
3665 pqinitmask();
3666 PG_SETMASK(&BlockSig);
3668 /* Read in remaining GUC variables */
3669 read_nondefault_variables();
3671 /* Run backend or appropriate child */
3672 if (strcmp(argv[1], "--forkbackend") == 0)
3674 Assert(argc == 3); /* shouldn't be any more args */
3676 /* Close the postmaster's sockets */
3677 ClosePostmasterPorts(false);
3680 * Need to reinitialize the SSL library in the backend, since the
3681 * context structures contain function pointers and cannot be passed
3682 * through the parameter file.
3684 #ifdef USE_SSL
3685 if (EnableSSL)
3686 secure_initialize();
3687 #endif
3690 * process any libraries that should be preloaded at postmaster start
3692 * NOTE: we have to re-load the shared_preload_libraries here because
3693 * this backend is not fork()ed so we can't inherit any shared
3694 * libraries / DLL's from our parent (the postmaster).
3696 process_shared_preload_libraries();
3699 * Perform additional initialization and client authentication.
3701 * We want to do this before InitProcess() for a couple of reasons: 1.
3702 * so that we aren't eating up a PGPROC slot while waiting on the
3703 * client. 2. so that if InitProcess() fails due to being out of
3704 * PGPROC slots, we have already initialized libpq and are able to
3705 * report the error to the client.
3707 BackendInitialize(&port);
3709 /* Restore basic shared memory pointers */
3710 InitShmemAccess(UsedShmemSegAddr);
3712 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3713 InitProcess();
3716 * Attach process to shared data structures. If testing EXEC_BACKEND
3717 * on Linux, you must run this as root before starting the postmaster:
3719 * echo 0 >/proc/sys/kernel/randomize_va_space
3721 * This prevents a randomized stack base address that causes child
3722 * shared memory to be at a different address than the parent, making
3723 * it impossible to attached to shared memory. Return the value to
3724 * '1' when finished.
3726 CreateSharedMemoryAndSemaphores(false, 0);
3728 /* And run the backend */
3729 proc_exit(BackendRun(&port));
3731 if (strcmp(argv[1], "--forkboot") == 0)
3733 /* Close the postmaster's sockets */
3734 ClosePostmasterPorts(false);
3736 /* Restore basic shared memory pointers */
3737 InitShmemAccess(UsedShmemSegAddr);
3739 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3740 InitAuxiliaryProcess();
3742 /* Attach process to shared data structures */
3743 CreateSharedMemoryAndSemaphores(false, 0);
3745 AuxiliaryProcessMain(argc - 2, argv + 2);
3746 proc_exit(0);
3748 if (strcmp(argv[1], "--forkavlauncher") == 0)
3750 /* Close the postmaster's sockets */
3751 ClosePostmasterPorts(false);
3753 /* Restore basic shared memory pointers */
3754 InitShmemAccess(UsedShmemSegAddr);
3756 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3757 InitAuxiliaryProcess();
3759 /* Attach process to shared data structures */
3760 CreateSharedMemoryAndSemaphores(false, 0);
3762 AutoVacLauncherMain(argc - 2, argv + 2);
3763 proc_exit(0);
3765 if (strcmp(argv[1], "--forkavworker") == 0)
3767 /* Close the postmaster's sockets */
3768 ClosePostmasterPorts(false);
3770 /* Restore basic shared memory pointers */
3771 InitShmemAccess(UsedShmemSegAddr);
3773 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3774 InitProcess();
3776 /* Attach process to shared data structures */
3777 CreateSharedMemoryAndSemaphores(false, 0);
3779 AutoVacWorkerMain(argc - 2, argv + 2);
3780 proc_exit(0);
3782 if (strcmp(argv[1], "--forkarch") == 0)
3784 /* Close the postmaster's sockets */
3785 ClosePostmasterPorts(false);
3787 /* Do not want to attach to shared memory */
3789 PgArchiverMain(argc, argv);
3790 proc_exit(0);
3792 if (strcmp(argv[1], "--forkcol") == 0)
3794 /* Close the postmaster's sockets */
3795 ClosePostmasterPorts(false);
3797 /* Do not want to attach to shared memory */
3799 PgstatCollectorMain(argc, argv);
3800 proc_exit(0);
3802 if (strcmp(argv[1], "--forklog") == 0)
3804 /* Close the postmaster's sockets */
3805 ClosePostmasterPorts(true);
3807 /* Do not want to attach to shared memory */
3809 SysLoggerMain(argc, argv);
3810 proc_exit(0);
3813 return 1; /* shouldn't get here */
3815 #endif /* EXEC_BACKEND */
3819 * ExitPostmaster -- cleanup
3821 * Do NOT call exit() directly --- always go through here!
3823 static void
3824 ExitPostmaster(int status)
3826 /* should cleanup shared memory and kill all backends */
3829 * Not sure of the semantics here. When the Postmaster dies, should the
3830 * backends all be killed? probably not.
3832 * MUST -- vadim 05-10-1999
3835 proc_exit(status);
3839 * sigusr1_handler - handle signal conditions from child processes
3841 static void
3842 sigusr1_handler(SIGNAL_ARGS)
3844 int save_errno = errno;
3846 PG_SETMASK(&BlockSig);
3848 if (CheckPostmasterSignal(PMSIGNAL_PASSWORD_CHANGE))
3851 * Authorization file has changed.
3853 load_role();
3856 if (CheckPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER) &&
3857 PgArchPID != 0)
3860 * Send SIGUSR1 to archiver process, to wake it up and begin archiving
3861 * next transaction log file.
3863 signal_child(PgArchPID, SIGUSR1);
3866 if (CheckPostmasterSignal(PMSIGNAL_ROTATE_LOGFILE) &&
3867 SysLoggerPID != 0)
3869 /* Tell syslogger to rotate logfile */
3870 signal_child(SysLoggerPID, SIGUSR1);
3873 if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER))
3876 * Start one iteration of the autovacuum daemon, even if autovacuuming
3877 * is nominally not enabled. This is so we can have an active defense
3878 * against transaction ID wraparound. We set a flag for the main loop
3879 * to do it rather than trying to do it here --- this is because the
3880 * autovac process itself may send the signal, and we want to handle
3881 * that by launching another iteration as soon as the current one
3882 * completes.
3884 start_autovac_launcher = true;
3887 if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER))
3889 /* The autovacuum launcher wants us to start a worker process. */
3890 StartAutovacuumWorker();
3893 PG_SETMASK(&UnBlockSig);
3895 errno = save_errno;
3900 * Dummy signal handler
3902 * We use this for signals that we don't actually use in the postmaster,
3903 * but we do use in backends. If we were to SIG_IGN such signals in the
3904 * postmaster, then a newly started backend might drop a signal that arrives
3905 * before it's able to reconfigure its signal processing. (See notes in
3906 * tcop/postgres.c.)
3908 static void
3909 dummy_handler(SIGNAL_ARGS)
3914 * RandomSalt
3916 static void
3917 RandomSalt(char *md5Salt)
3919 long rand;
3922 * We use % 255, sacrificing one possible byte value, so as to ensure that
3923 * all bits of the random() value participate in the result. While at it,
3924 * add one to avoid generating any null bytes.
3926 rand = PostmasterRandom();
3927 md5Salt[0] = (rand % 255) + 1;
3928 rand = PostmasterRandom();
3929 md5Salt[1] = (rand % 255) + 1;
3930 rand = PostmasterRandom();
3931 md5Salt[2] = (rand % 255) + 1;
3932 rand = PostmasterRandom();
3933 md5Salt[3] = (rand % 255) + 1;
3937 * PostmasterRandom
3939 static long
3940 PostmasterRandom(void)
3943 * Select a random seed at the time of first receiving a request.
3945 if (random_seed == 0)
3949 struct timeval random_stop_time;
3951 gettimeofday(&random_stop_time, NULL);
3954 * We are not sure how much precision is in tv_usec, so we swap
3955 * the high and low 16 bits of 'random_stop_time' and XOR them
3956 * with 'random_start_time'. On the off chance that the result is
3957 * 0, we loop until it isn't.
3959 random_seed = random_start_time.tv_usec ^
3960 ((random_stop_time.tv_usec << 16) |
3961 ((random_stop_time.tv_usec >> 16) & 0xffff));
3963 while (random_seed == 0);
3965 srandom(random_seed);
3968 return random();
3972 * Count up number of child processes (excluding special children and
3973 * dead_end children)
3975 static int
3976 CountChildren(void)
3978 Dlelem *curr;
3979 int cnt = 0;
3981 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
3983 Backend *bp = (Backend *) DLE_VAL(curr);
3985 if (!bp->dead_end)
3986 cnt++;
3988 return cnt;
3993 * StartChildProcess -- start an auxiliary process for the postmaster
3995 * xlop determines what kind of child will be started. All child types
3996 * initially go to AuxiliaryProcessMain, which will handle common setup.
3998 * Return value of StartChildProcess is subprocess' PID, or 0 if failed
3999 * to start subprocess.
4001 static pid_t
4002 StartChildProcess(AuxProcType type)
4004 pid_t pid;
4005 char *av[10];
4006 int ac = 0;
4007 char typebuf[32];
4010 * Set up command-line arguments for subprocess
4012 av[ac++] = "postgres";
4014 #ifdef EXEC_BACKEND
4015 av[ac++] = "--forkboot";
4016 av[ac++] = NULL; /* filled in by postmaster_forkexec */
4017 #endif
4019 snprintf(typebuf, sizeof(typebuf), "-x%d", type);
4020 av[ac++] = typebuf;
4022 av[ac] = NULL;
4023 Assert(ac < lengthof(av));
4025 #ifdef EXEC_BACKEND
4026 pid = postmaster_forkexec(ac, av);
4027 #else /* !EXEC_BACKEND */
4028 pid = fork_process();
4030 if (pid == 0) /* child */
4032 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
4034 /* Close the postmaster's sockets */
4035 ClosePostmasterPorts(false);
4037 /* Lose the postmaster's on-exit routines and port connections */
4038 on_exit_reset();
4040 /* Release postmaster's working memory context */
4041 MemoryContextSwitchTo(TopMemoryContext);
4042 MemoryContextDelete(PostmasterContext);
4043 PostmasterContext = NULL;
4045 AuxiliaryProcessMain(ac, av);
4046 ExitPostmaster(0);
4048 #endif /* EXEC_BACKEND */
4050 if (pid < 0)
4052 /* in parent, fork failed */
4053 int save_errno = errno;
4055 errno = save_errno;
4056 switch (type)
4058 case StartupProcess:
4059 ereport(LOG,
4060 (errmsg("could not fork startup process: %m")));
4061 break;
4062 case BgWriterProcess:
4063 ereport(LOG,
4064 (errmsg("could not fork background writer process: %m")));
4065 break;
4066 case WalWriterProcess:
4067 ereport(LOG,
4068 (errmsg("could not fork WAL writer process: %m")));
4069 break;
4070 default:
4071 ereport(LOG,
4072 (errmsg("could not fork process: %m")));
4073 break;
4077 * fork failure is fatal during startup, but there's no need to choke
4078 * immediately if starting other child types fails.
4080 if (type == StartupProcess)
4081 ExitPostmaster(1);
4082 return 0;
4086 * in parent, successful fork
4088 return pid;
4092 * StartAutovacuumWorker
4093 * Start an autovac worker process.
4095 * This function is here because it enters the resulting PID into the
4096 * postmaster's private backends list.
4098 * NB -- this code very roughly matches BackendStartup.
4100 static void
4101 StartAutovacuumWorker(void)
4103 Backend *bn;
4106 * If not in condition to run a process, don't try, but handle it like a
4107 * fork failure. This does not normally happen, since the signal is only
4108 * supposed to be sent by autovacuum launcher when it's OK to do it, but
4109 * we have to check to avoid race-condition problems during DB state
4110 * changes.
4112 if (canAcceptConnections() == CAC_OK)
4115 * Compute the cancel key that will be assigned to this session. We
4116 * probably don't need cancel keys for autovac workers, but we'd
4117 * better have something random in the field to prevent unfriendly
4118 * people from sending cancels to them.
4120 MyCancelKey = PostmasterRandom();
4122 bn = (Backend *) malloc(sizeof(Backend));
4123 if (bn)
4125 bn->pid = StartAutoVacWorker();
4126 if (bn->pid > 0)
4128 bn->cancel_key = MyCancelKey;
4129 bn->is_autovacuum = true;
4130 bn->dead_end = false;
4131 DLAddHead(BackendList, DLNewElem(bn));
4132 #ifdef EXEC_BACKEND
4133 ShmemBackendArrayAdd(bn);
4134 #endif
4135 /* all OK */
4136 return;
4140 * fork failed, fall through to report -- actual error message was
4141 * logged by StartAutoVacWorker
4143 free(bn);
4145 else
4146 ereport(LOG,
4147 (errcode(ERRCODE_OUT_OF_MEMORY),
4148 errmsg("out of memory")));
4152 * Report the failure to the launcher, if it's running. (If it's not, we
4153 * might not even be connected to shared memory, so don't try to call
4154 * AutoVacWorkerFailed.)
4156 if (AutoVacPID != 0)
4158 AutoVacWorkerFailed();
4159 kill(AutoVacPID, SIGUSR1);
4164 * Create the opts file
4166 static bool
4167 CreateOptsFile(int argc, char *argv[], char *fullprogname)
4169 FILE *fp;
4170 int i;
4172 #define OPTS_FILE "postmaster.opts"
4174 if ((fp = fopen(OPTS_FILE, "w")) == NULL)
4176 elog(LOG, "could not create file \"%s\": %m", OPTS_FILE);
4177 return false;
4180 fprintf(fp, "%s", fullprogname);
4181 for (i = 1; i < argc; i++)
4182 fprintf(fp, " \"%s\"", argv[i]);
4183 fputs("\n", fp);
4185 if (fclose(fp))
4187 elog(LOG, "could not write file \"%s\": %m", OPTS_FILE);
4188 return false;
4191 return true;
4195 #ifdef EXEC_BACKEND
4198 * The following need to be available to the save/restore_backend_variables
4199 * functions
4201 extern slock_t *ShmemLock;
4202 extern LWLock *LWLockArray;
4203 extern slock_t *ProcStructLock;
4204 extern PROC_HDR *ProcGlobal;
4205 extern PGPROC *AuxiliaryProcs;
4206 extern int pgStatSock;
4208 #ifndef WIN32
4209 #define write_inheritable_socket(dest, src, childpid) (*(dest) = (src))
4210 #define read_inheritable_socket(dest, src) (*(dest) = *(src))
4211 #else
4212 static void write_duplicated_handle(HANDLE * dest, HANDLE src, HANDLE child);
4213 static void write_inheritable_socket(InheritableSocket * dest, SOCKET src,
4214 pid_t childPid);
4215 static void read_inheritable_socket(SOCKET * dest, InheritableSocket * src);
4216 #endif
4219 /* Save critical backend variables into the BackendParameters struct */
4220 #ifndef WIN32
4221 static bool
4222 save_backend_variables(BackendParameters * param, Port *port)
4223 #else
4224 static bool
4225 save_backend_variables(BackendParameters * param, Port *port,
4226 HANDLE childProcess, pid_t childPid)
4227 #endif
4229 memcpy(&param->port, port, sizeof(Port));
4230 write_inheritable_socket(&param->portsocket, port->sock, childPid);
4232 strlcpy(param->DataDir, DataDir, MAXPGPATH);
4234 memcpy(&param->ListenSocket, &ListenSocket, sizeof(ListenSocket));
4236 param->MyCancelKey = MyCancelKey;
4238 param->UsedShmemSegID = UsedShmemSegID;
4239 param->UsedShmemSegAddr = UsedShmemSegAddr;
4241 param->ShmemLock = ShmemLock;
4242 param->ShmemVariableCache = ShmemVariableCache;
4243 param->ShmemBackendArray = ShmemBackendArray;
4245 param->LWLockArray = LWLockArray;
4246 param->ProcStructLock = ProcStructLock;
4247 param->ProcGlobal = ProcGlobal;
4248 param->AuxiliaryProcs = AuxiliaryProcs;
4249 write_inheritable_socket(&param->pgStatSock, pgStatSock, childPid);
4251 param->PostmasterPid = PostmasterPid;
4252 param->PgStartTime = PgStartTime;
4253 param->PgReloadTime = PgReloadTime;
4255 param->redirection_done = redirection_done;
4257 #ifdef WIN32
4258 param->PostmasterHandle = PostmasterHandle;
4259 write_duplicated_handle(&param->initial_signal_pipe,
4260 pgwin32_create_signal_listener(childPid),
4261 childProcess);
4262 #endif
4264 memcpy(&param->syslogPipe, &syslogPipe, sizeof(syslogPipe));
4266 strlcpy(param->my_exec_path, my_exec_path, MAXPGPATH);
4268 strlcpy(param->pkglib_path, pkglib_path, MAXPGPATH);
4270 strlcpy(param->ExtraOptions, ExtraOptions, MAXPGPATH);
4272 strlcpy(param->lc_collate, setlocale(LC_COLLATE, NULL), NAMEDATALEN);
4273 strlcpy(param->lc_ctype, setlocale(LC_CTYPE, NULL), NAMEDATALEN);
4275 return true;
4279 #ifdef WIN32
4281 * Duplicate a handle for usage in a child process, and write the child
4282 * process instance of the handle to the parameter file.
4284 static void
4285 write_duplicated_handle(HANDLE * dest, HANDLE src, HANDLE childProcess)
4287 HANDLE hChild = INVALID_HANDLE_VALUE;
4289 if (!DuplicateHandle(GetCurrentProcess(),
4290 src,
4291 childProcess,
4292 &hChild,
4294 TRUE,
4295 DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS))
4296 ereport(ERROR,
4297 (errmsg_internal("could not duplicate handle to be written to backend parameter file: error code %d",
4298 (int) GetLastError())));
4300 *dest = hChild;
4304 * Duplicate a socket for usage in a child process, and write the resulting
4305 * structure to the parameter file.
4306 * This is required because a number of LSPs (Layered Service Providers) very
4307 * common on Windows (antivirus, firewalls, download managers etc) break
4308 * straight socket inheritance.
4310 static void
4311 write_inheritable_socket(InheritableSocket * dest, SOCKET src, pid_t childpid)
4313 dest->origsocket = src;
4314 if (src != 0 && src != -1)
4316 /* Actual socket */
4317 if (WSADuplicateSocket(src, childpid, &dest->wsainfo) != 0)
4318 ereport(ERROR,
4319 (errmsg("could not duplicate socket %d for use in backend: error code %d",
4320 src, WSAGetLastError())));
4325 * Read a duplicate socket structure back, and get the socket descriptor.
4327 static void
4328 read_inheritable_socket(SOCKET * dest, InheritableSocket * src)
4330 SOCKET s;
4332 if (src->origsocket == -1 || src->origsocket == 0)
4334 /* Not a real socket! */
4335 *dest = src->origsocket;
4337 else
4339 /* Actual socket, so create from structure */
4340 s = WSASocket(FROM_PROTOCOL_INFO,
4341 FROM_PROTOCOL_INFO,
4342 FROM_PROTOCOL_INFO,
4343 &src->wsainfo,
4346 if (s == INVALID_SOCKET)
4348 write_stderr("could not create inherited socket: error code %d\n",
4349 WSAGetLastError());
4350 exit(1);
4352 *dest = s;
4355 * To make sure we don't get two references to the same socket, close
4356 * the original one. (This would happen when inheritance actually
4357 * works..
4359 closesocket(src->origsocket);
4362 #endif
4364 static void
4365 read_backend_variables(char *id, Port *port)
4367 BackendParameters param;
4369 #ifndef WIN32
4370 /* Non-win32 implementation reads from file */
4371 FILE *fp;
4373 /* Open file */
4374 fp = AllocateFile(id, PG_BINARY_R);
4375 if (!fp)
4377 write_stderr("could not read from backend variables file \"%s\": %s\n",
4378 id, strerror(errno));
4379 exit(1);
4382 if (fread(&param, sizeof(param), 1, fp) != 1)
4384 write_stderr("could not read from backend variables file \"%s\": %s\n",
4385 id, strerror(errno));
4386 exit(1);
4389 /* Release file */
4390 FreeFile(fp);
4391 if (unlink(id) != 0)
4393 write_stderr("could not remove file \"%s\": %s\n",
4394 id, strerror(errno));
4395 exit(1);
4397 #else
4398 /* Win32 version uses mapped file */
4399 HANDLE paramHandle;
4400 BackendParameters *paramp;
4402 paramHandle = (HANDLE) atol(id);
4403 paramp = MapViewOfFile(paramHandle, FILE_MAP_READ, 0, 0, 0);
4404 if (!paramp)
4406 write_stderr("could not map view of backend variables: error code %d\n",
4407 (int) GetLastError());
4408 exit(1);
4411 memcpy(&param, paramp, sizeof(BackendParameters));
4413 if (!UnmapViewOfFile(paramp))
4415 write_stderr("could not unmap view of backend variables: error code %d\n",
4416 (int) GetLastError());
4417 exit(1);
4420 if (!CloseHandle(paramHandle))
4422 write_stderr("could not close handle to backend parameter variables: error code %d\n",
4423 (int) GetLastError());
4424 exit(1);
4426 #endif
4428 restore_backend_variables(&param, port);
4431 /* Restore critical backend variables from the BackendParameters struct */
4432 static void
4433 restore_backend_variables(BackendParameters * param, Port *port)
4435 memcpy(port, &param->port, sizeof(Port));
4436 read_inheritable_socket(&port->sock, &param->portsocket);
4438 SetDataDir(param->DataDir);
4440 memcpy(&ListenSocket, &param->ListenSocket, sizeof(ListenSocket));
4442 MyCancelKey = param->MyCancelKey;
4444 UsedShmemSegID = param->UsedShmemSegID;
4445 UsedShmemSegAddr = param->UsedShmemSegAddr;
4447 ShmemLock = param->ShmemLock;
4448 ShmemVariableCache = param->ShmemVariableCache;
4449 ShmemBackendArray = param->ShmemBackendArray;
4451 LWLockArray = param->LWLockArray;
4452 ProcStructLock = param->ProcStructLock;
4453 ProcGlobal = param->ProcGlobal;
4454 AuxiliaryProcs = param->AuxiliaryProcs;
4455 read_inheritable_socket(&pgStatSock, &param->pgStatSock);
4457 PostmasterPid = param->PostmasterPid;
4458 PgStartTime = param->PgStartTime;
4459 PgReloadTime = param->PgReloadTime;
4461 redirection_done = param->redirection_done;
4463 #ifdef WIN32
4464 PostmasterHandle = param->PostmasterHandle;
4465 pgwin32_initial_signal_pipe = param->initial_signal_pipe;
4466 #endif
4468 memcpy(&syslogPipe, &param->syslogPipe, sizeof(syslogPipe));
4470 strlcpy(my_exec_path, param->my_exec_path, MAXPGPATH);
4472 strlcpy(pkglib_path, param->pkglib_path, MAXPGPATH);
4474 strlcpy(ExtraOptions, param->ExtraOptions, MAXPGPATH);
4476 setlocale(LC_COLLATE, param->lc_collate);
4477 setlocale(LC_CTYPE, param->lc_ctype);
4481 Size
4482 ShmemBackendArraySize(void)
4484 return mul_size(NUM_BACKENDARRAY_ELEMS, sizeof(Backend));
4487 void
4488 ShmemBackendArrayAllocation(void)
4490 Size size = ShmemBackendArraySize();
4492 ShmemBackendArray = (Backend *) ShmemAlloc(size);
4493 /* Mark all slots as empty */
4494 memset(ShmemBackendArray, 0, size);
4497 static void
4498 ShmemBackendArrayAdd(Backend *bn)
4500 int i;
4502 /* Find an empty slot */
4503 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
4505 if (ShmemBackendArray[i].pid == 0)
4507 ShmemBackendArray[i] = *bn;
4508 return;
4512 ereport(FATAL,
4513 (errmsg_internal("no free slots in shmem backend array")));
4516 static void
4517 ShmemBackendArrayRemove(pid_t pid)
4519 int i;
4521 for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
4523 if (ShmemBackendArray[i].pid == pid)
4525 /* Mark the slot as empty */
4526 ShmemBackendArray[i].pid = 0;
4527 return;
4531 ereport(WARNING,
4532 (errmsg_internal("could not find backend entry with pid %d",
4533 (int) pid)));
4535 #endif /* EXEC_BACKEND */
4538 #ifdef WIN32
4540 static pid_t
4541 win32_waitpid(int *exitstatus)
4543 DWORD dwd;
4544 ULONG_PTR key;
4545 OVERLAPPED *ovl;
4548 * Check if there are any dead children. If there are, return the pid of
4549 * the first one that died.
4551 if (GetQueuedCompletionStatus(win32ChildQueue, &dwd, &key, &ovl, 0))
4553 *exitstatus = (int) key;
4554 return dwd;
4557 return -1;
4561 * Note! Code below executes on a thread pool! All operations must
4562 * be thread safe! Note that elog() and friends must *not* be used.
4564 static void WINAPI
4565 pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
4567 win32_deadchild_waitinfo *childinfo = (win32_deadchild_waitinfo *) lpParameter;
4568 DWORD exitcode;
4570 if (TimerOrWaitFired)
4571 return; /* timeout. Should never happen, since we use
4572 * INFINITE as timeout value. */
4575 * Remove handle from wait - required even though it's set to wait only
4576 * once
4578 UnregisterWaitEx(childinfo->waitHandle, NULL);
4580 if (!GetExitCodeProcess(childinfo->procHandle, &exitcode))
4583 * Should never happen. Inform user and set a fixed exitcode.
4585 write_stderr("could not read exit code for process\n");
4586 exitcode = 255;
4589 if (!PostQueuedCompletionStatus(win32ChildQueue, childinfo->procId, (ULONG_PTR) exitcode, NULL))
4590 write_stderr("could not post child completion status\n");
4593 * Handle is per-process, so we close it here instead of in the
4594 * originating thread
4596 CloseHandle(childinfo->procHandle);
4599 * Free struct that was allocated before the call to
4600 * RegisterWaitForSingleObject()
4602 free(childinfo);
4604 /* Queue SIGCHLD signal */
4605 pg_queue_signal(SIGCHLD);
4608 #endif /* WIN32 */