PostgreSQL Source Code  git master
postmaster.h File Reference
#include "miscadmin.h"
Include dependency graph for postmaster.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Macros

#define POSTMASTER_FD_WATCH
 
#define POSTMASTER_FD_OWN   1 /* kept open by postmaster only */
 
#define MAX_BACKENDS   0x3FFFF
 

Functions

void PostmasterMain (int argc, char *argv[]) pg_attribute_noreturn()
 
void ClosePostmasterPorts (bool am_syslogger)
 
void InitProcessGlobals (void)
 
int MaxLivePostmasterChildren (void)
 
bool PostmasterMarkPIDForWorkerNotify (int)
 
void processCancelRequest (int backendPID, int32 cancelAuthCode)
 
pid_t postmaster_child_launch (BackendType child_type, char *startup_data, size_t startup_data_len, struct ClientSocket *sock)
 
const char * PostmasterChildName (BackendType child_type)
 

Variables

PGDLLIMPORT bool EnableSSL
 
PGDLLIMPORT int SuperuserReservedConnections
 
PGDLLIMPORT int ReservedConnections
 
PGDLLIMPORT int PostPortNumber
 
PGDLLIMPORT int Unix_socket_permissions
 
PGDLLIMPORT char * Unix_socket_group
 
PGDLLIMPORT char * Unix_socket_directories
 
PGDLLIMPORT char * ListenAddresses
 
PGDLLIMPORT bool ClientAuthInProgress
 
PGDLLIMPORT int PreAuthDelay
 
PGDLLIMPORT int AuthenticationTimeout
 
PGDLLIMPORT bool Log_connections
 
PGDLLIMPORT bool log_hostname
 
PGDLLIMPORT bool enable_bonjour
 
PGDLLIMPORT char * bonjour_name
 
PGDLLIMPORT bool restart_after_crash
 
PGDLLIMPORT bool remove_temp_files_after_crash
 
PGDLLIMPORT bool send_abort_for_crash
 
PGDLLIMPORT bool send_abort_for_kill
 
PGDLLIMPORT int postmaster_alive_fds [2]
 
PGDLLIMPORT const char * progname
 
PGDLLIMPORT bool LoadedSSL
 
PGDLLIMPORT struct ClientSocketMyClientSocket
 

Macro Definition Documentation

◆ MAX_BACKENDS

#define MAX_BACKENDS   0x3FFFF

Definition at line 95 of file postmaster.h.

◆ POSTMASTER_FD_OWN

#define POSTMASTER_FD_OWN   1 /* kept open by postmaster only */

Definition at line 49 of file postmaster.h.

◆ POSTMASTER_FD_WATCH

#define POSTMASTER_FD_WATCH
Value:
0 /* used in children to check for
* postmaster death */

Definition at line 48 of file postmaster.h.

Function Documentation

◆ ClosePostmasterPorts()

void ClosePostmasterPorts ( bool  am_syslogger)

Definition at line 1955 of file postmaster.c.

1956 {
1957  /* Release resources held by the postmaster's WaitEventSet. */
1958  if (pm_wait_set)
1959  {
1961  pm_wait_set = NULL;
1962  }
1963 
1964 #ifndef WIN32
1965 
1966  /*
1967  * Close the write end of postmaster death watch pipe. It's important to
1968  * do this as early as possible, so that if postmaster dies, others won't
1969  * think that it's still running because we're holding the pipe open.
1970  */
1972  ereport(FATAL,
1974  errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
1976  /* Notify fd.c that we released one pipe FD. */
1978 #endif
1979 
1980  /*
1981  * Close the postmaster's listen sockets. These aren't tracked by fd.c,
1982  * so we don't call ReleaseExternalFD() here.
1983  *
1984  * The listen sockets are marked as FD_CLOEXEC, so this isn't needed in
1985  * EXEC_BACKEND mode.
1986  */
1987 #ifndef EXEC_BACKEND
1988  if (ListenSockets)
1989  {
1990  for (int i = 0; i < NumListenSockets; i++)
1991  {
1992  if (closesocket(ListenSockets[i]) != 0)
1993  elog(LOG, "could not close listen socket: %m");
1994  }
1996  }
1997  NumListenSockets = 0;
1998  ListenSockets = NULL;
1999 #endif
2000 
2001  /*
2002  * If using syslogger, close the read side of the pipe. We don't bother
2003  * tracking this in fd.c, either.
2004  */
2005  if (!am_syslogger)
2006  {
2007 #ifndef WIN32
2008  if (syslogPipe[0] >= 0)
2009  close(syslogPipe[0]);
2010  syslogPipe[0] = -1;
2011 #else
2012  if (syslogPipe[0])
2013  CloseHandle(syslogPipe[0]);
2014  syslogPipe[0] = 0;
2015 #endif
2016  }
2017 
2018 #ifdef USE_BONJOUR
2019  /* If using Bonjour, close the connection to the mDNS daemon */
2020  if (bonjour_sdref)
2021  close(DNSServiceRefSockFD(bonjour_sdref));
2022 #endif
2023 }
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
int errcode_for_file_access(void)
Definition: elog.c:880
#define LOG
Definition: elog.h:31
#define FATAL
Definition: elog.h:41
#define elog(elevel,...)
Definition: elog.h:224
#define ereport(elevel,...)
Definition: elog.h:149
void ReleaseExternalFD(void)
Definition: fd.c:1239
#define close(a)
Definition: win32.h:12
int i
Definition: isn.c:73
void FreeWaitEventSetAfterFork(WaitEventSet *set)
Definition: latch.c:917
void pfree(void *pointer)
Definition: mcxt.c:1520
#define closesocket
Definition: port.h:349
static pgsocket * ListenSockets
Definition: postmaster.c:222
static int NumListenSockets
Definition: postmaster.c:221
int postmaster_alive_fds[2]
Definition: postmaster.c:479
static WaitEventSet * pm_wait_set
Definition: postmaster.c:377
#define POSTMASTER_FD_OWN
Definition: postmaster.h:49
int syslogPipe[2]
Definition: syslogger.c:116

References close, closesocket, elog, ereport, errcode_for_file_access(), errmsg_internal(), FATAL, FreeWaitEventSetAfterFork(), i, ListenSockets, LOG, NumListenSockets, pfree(), pm_wait_set, postmaster_alive_fds, POSTMASTER_FD_OWN, ReleaseExternalFD(), and syslogPipe.

Referenced by postmaster_child_launch().

◆ InitProcessGlobals()

void InitProcessGlobals ( void  )

Definition at line 2032 of file postmaster.c.

2033 {
2034  MyProcPid = getpid();
2037 
2038  /*
2039  * Set a different global seed in every process. We want something
2040  * unpredictable, so if possible, use high-quality random bits for the
2041  * seed. Otherwise, fall back to a seed based on timestamp and PID.
2042  */
2044  {
2045  uint64 rseed;
2046 
2047  /*
2048  * Since PIDs and timestamps tend to change more frequently in their
2049  * least significant bits, shift the timestamp left to allow a larger
2050  * total number of seeds in a given time period. Since that would
2051  * leave only 20 bits of the timestamp that cycle every ~1 second,
2052  * also mix in some higher bits.
2053  */
2054  rseed = ((uint64) MyProcPid) ^
2055  ((uint64) MyStartTimestamp << 12) ^
2056  ((uint64) MyStartTimestamp >> 20);
2057 
2059  }
2060 
2061  /*
2062  * Also make sure that we've set a good seed for random(3). Use of that
2063  * is deprecated in core Postgres, but extensions might use it.
2064  */
2065 #ifndef WIN32
2067 #endif
2068 }
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1654
pg_time_t timestamptz_to_time_t(TimestampTz t)
Definition: timestamp.c:1833
#define unlikely(x)
Definition: c.h:311
int MyProcPid
Definition: globals.c:45
TimestampTz MyStartTimestamp
Definition: globals.c:47
pg_time_t MyStartTime
Definition: globals.c:46
uint32 pg_prng_uint32(pg_prng_state *state)
Definition: pg_prng.c:227
void pg_prng_seed(pg_prng_state *state, uint64 seed)
Definition: pg_prng.c:89
pg_prng_state pg_global_prng_state
Definition: pg_prng.c:34
#define pg_prng_strong_seed(state)
Definition: pg_prng.h:46

References GetCurrentTimestamp(), MyProcPid, MyStartTime, MyStartTimestamp, pg_global_prng_state, pg_prng_seed(), pg_prng_strong_seed, pg_prng_uint32(), timestamptz_to_time_t(), and unlikely.

Referenced by InitPostmasterChild(), InitStandaloneProcess(), and PostmasterMain().

◆ MaxLivePostmasterChildren()

int MaxLivePostmasterChildren ( void  )

Definition at line 4145 of file postmaster.c.

4146 {
4147  return 2 * (MaxConnections + autovacuum_max_workers + 1 +
4149 }
int autovacuum_max_workers
Definition: autovacuum.c:117
int MaxConnections
Definition: globals.c:140
int max_worker_processes
Definition: globals.c:141
int max_wal_senders
Definition: walsender.c:121

References autovacuum_max_workers, max_wal_senders, max_worker_processes, and MaxConnections.

Referenced by canAcceptConnections(), PMSignalShmemInit(), PMSignalShmemSize(), and processCancelRequest().

◆ postmaster_child_launch()

pid_t postmaster_child_launch ( BackendType  child_type,
char *  startup_data,
size_t  startup_data_len,
struct ClientSocket sock 
)

Definition at line 226 of file launch_backend.c.

229 {
230  pid_t pid;
231 
233 
234 #ifdef EXEC_BACKEND
235  pid = internal_forkexec(child_process_kinds[child_type].name,
236  startup_data, startup_data_len, client_sock);
237  /* the child process will arrive in SubPostmasterMain */
238 #else /* !EXEC_BACKEND */
239  pid = fork_process();
240  if (pid == 0) /* child */
241  {
242  /* Close the postmaster's sockets */
243  ClosePostmasterPorts(child_type == B_LOGGER);
244 
245  /* Detangle from postmaster */
247 
248  /*
249  * Enter the Main function with TopMemoryContext. The startup data is
250  * allocated in PostmasterContext, so we cannot release it here yet.
251  * The Main function will do it after it's done handling the startup
252  * data.
253  */
255 
256  if (client_sock)
257  {
259  memcpy(MyClientSocket, client_sock, sizeof(ClientSocket));
260  }
261 
262  /*
263  * Run the appropriate Main function
264  */
265  child_process_kinds[child_type].main_fn(startup_data, startup_data_len);
266  pg_unreachable(); /* main_fn never returns */
267  }
268 #endif /* EXEC_BACKEND */
269  return pid;
270 }
#define Assert(condition)
Definition: c.h:858
#define pg_unreachable()
Definition: c.h:296
pid_t fork_process(void)
Definition: fork_process.c:32
struct ClientSocket * MyClientSocket
Definition: globals.c:48
bool IsUnderPostmaster
Definition: globals.c:117
bool IsPostmasterEnvironment
Definition: globals.c:116
child_process_kind child_process_kinds[]
MemoryContext TopMemoryContext
Definition: mcxt.c:149
void * palloc(Size size)
Definition: mcxt.c:1316
@ B_LOGGER
Definition: miscadmin.h:367
void InitPostmasterChild(void)
Definition: miscinit.c:95
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:1955
MemoryContextSwitchTo(old_ctx)
void(* main_fn)(char *startup_data, size_t startup_data_len) pg_attribute_noreturn()
const char * name

References Assert, B_LOGGER, child_process_kinds, ClosePostmasterPorts(), fork_process(), InitPostmasterChild(), IsPostmasterEnvironment, IsUnderPostmaster, child_process_kind::main_fn, MemoryContextSwitchTo(), MyClientSocket, name, palloc(), pg_unreachable, bkend::pid, and TopMemoryContext.

Referenced by BackendStartup(), do_start_bgworker(), StartChildProcess(), and SysLogger_Start().

◆ PostmasterChildName()

const char* PostmasterChildName ( BackendType  child_type)

Definition at line 209 of file launch_backend.c.

210 {
211  return child_process_kinds[child_type].name;
212 }

References child_process_kinds, and child_process_kind::name.

Referenced by StartChildProcess().

◆ PostmasterMain()

void PostmasterMain ( int  argc,
char *  argv[] 
)

Definition at line 489 of file postmaster.c.

490 {
491  int opt;
492  int status;
493  char *userDoption = NULL;
494  bool listen_addr_saved = false;
495  char *output_config_variable = NULL;
496 
498 
500 
502 
503  /*
504  * Start our win32 signal implementation
505  */
506 #ifdef WIN32
508 #endif
509 
510  /*
511  * We should not be creating any files or directories before we check the
512  * data directory (see checkDataDir()), but just in case set the umask to
513  * the most restrictive (owner-only) permissions.
514  *
515  * checkDataDir() will reset the umask based on the data directory
516  * permissions.
517  */
518  umask(PG_MODE_MASK_OWNER);
519 
520  /*
521  * By default, palloc() requests in the postmaster will be allocated in
522  * the PostmasterContext, which is space that can be recycled by backends.
523  * Allocated data that needs to be available to backends should be
524  * allocated in TopMemoryContext.
525  */
527  "Postmaster",
530 
531  /* Initialize paths to installation files */
532  getInstallationPaths(argv[0]);
533 
534  /*
535  * Set up signal handlers for the postmaster process.
536  *
537  * CAUTION: when changing this list, check for side-effects on the signal
538  * handling setup of child processes. See tcop/postgres.c,
539  * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/walwriter.c,
540  * postmaster/autovacuum.c, postmaster/pgarch.c, postmaster/syslogger.c,
541  * postmaster/bgworker.c and postmaster/checkpointer.c.
542  */
543  pqinitmask();
544  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
545 
550  pqsignal(SIGALRM, SIG_IGN); /* ignored */
551  pqsignal(SIGPIPE, SIG_IGN); /* ignored */
553  pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
555 
556  /* This may configure SIGURG, depending on platform. */
559 
560  /*
561  * No other place in Postgres should touch SIGTTIN/SIGTTOU handling. We
562  * ignore those signals in a postmaster environment, so that there is no
563  * risk of a child process freezing up due to writing to stderr. But for
564  * a standalone backend, their default handling is reasonable. Hence, all
565  * child processes should just allow the inherited settings to stand.
566  */
567 #ifdef SIGTTIN
568  pqsignal(SIGTTIN, SIG_IGN); /* ignored */
569 #endif
570 #ifdef SIGTTOU
571  pqsignal(SIGTTOU, SIG_IGN); /* ignored */
572 #endif
573 
574  /* ignore SIGXFSZ, so that ulimit violations work like disk full */
575 #ifdef SIGXFSZ
576  pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
577 #endif
578 
579  /* Begin accepting signals. */
580  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
581 
582  /*
583  * Options setup
584  */
586 
587  opterr = 1;
588 
589  /*
590  * Parse command-line options. CAUTION: keep this in sync with
591  * tcop/postgres.c (the option sets should not conflict) and with the
592  * common help() function in main/main.c.
593  */
594  while ((opt = getopt(argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:OPp:r:S:sTt:W:-:")) != -1)
595  {
596  switch (opt)
597  {
598  case 'B':
599  SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
600  break;
601 
602  case 'b':
603  /* Undocumented flag used for binary upgrades */
604  IsBinaryUpgrade = true;
605  break;
606 
607  case 'C':
608  output_config_variable = strdup(optarg);
609  break;
610 
611  case 'c':
612  case '-':
613  {
614  char *name,
615  *value;
616 
618  if (!value)
619  {
620  if (opt == '-')
621  ereport(ERROR,
622  (errcode(ERRCODE_SYNTAX_ERROR),
623  errmsg("--%s requires a value",
624  optarg)));
625  else
626  ereport(ERROR,
627  (errcode(ERRCODE_SYNTAX_ERROR),
628  errmsg("-c %s requires a value",
629  optarg)));
630  }
631 
633  pfree(name);
634  pfree(value);
635  break;
636  }
637 
638  case 'D':
639  userDoption = strdup(optarg);
640  break;
641 
642  case 'd':
644  break;
645 
646  case 'E':
647  SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
648  break;
649 
650  case 'e':
651  SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
652  break;
653 
654  case 'F':
655  SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
656  break;
657 
658  case 'f':
660  {
661  write_stderr("%s: invalid argument for option -f: \"%s\"\n",
662  progname, optarg);
663  ExitPostmaster(1);
664  }
665  break;
666 
667  case 'h':
668  SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
669  break;
670 
671  case 'i':
672  SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
673  break;
674 
675  case 'j':
676  /* only used by interactive backend */
677  break;
678 
679  case 'k':
680  SetConfigOption("unix_socket_directories", optarg, PGC_POSTMASTER, PGC_S_ARGV);
681  break;
682 
683  case 'l':
684  SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
685  break;
686 
687  case 'N':
688  SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
689  break;
690 
691  case 'O':
692  SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
693  break;
694 
695  case 'P':
696  SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
697  break;
698 
699  case 'p':
701  break;
702 
703  case 'r':
704  /* only used by single-user backend */
705  break;
706 
707  case 'S':
709  break;
710 
711  case 's':
712  SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
713  break;
714 
715  case 'T':
716 
717  /*
718  * This option used to be defined as sending SIGSTOP after a
719  * backend crash, but sending SIGABRT seems more useful.
720  */
721  SetConfigOption("send_abort_for_crash", "true", PGC_POSTMASTER, PGC_S_ARGV);
722  break;
723 
724  case 't':
725  {
726  const char *tmp = get_stats_option_name(optarg);
727 
728  if (tmp)
729  {
731  }
732  else
733  {
734  write_stderr("%s: invalid argument for option -t: \"%s\"\n",
735  progname, optarg);
736  ExitPostmaster(1);
737  }
738  break;
739  }
740 
741  case 'W':
742  SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
743  break;
744 
745  default:
746  write_stderr("Try \"%s --help\" for more information.\n",
747  progname);
748  ExitPostmaster(1);
749  }
750  }
751 
752  /*
753  * Postmaster accepts no non-option switch arguments.
754  */
755  if (optind < argc)
756  {
757  write_stderr("%s: invalid argument: \"%s\"\n",
758  progname, argv[optind]);
759  write_stderr("Try \"%s --help\" for more information.\n",
760  progname);
761  ExitPostmaster(1);
762  }
763 
764  /*
765  * Locate the proper configuration files and data directory, and read
766  * postgresql.conf for the first time.
767  */
769  ExitPostmaster(2);
770 
771  if (output_config_variable != NULL)
772  {
773  /*
774  * If this is a runtime-computed GUC, it hasn't yet been initialized,
775  * and the present value is not useful. However, this is a convenient
776  * place to print the value for most GUCs because it is safe to run
777  * postmaster startup to this point even if the server is already
778  * running. For the handful of runtime-computed GUCs that we cannot
779  * provide meaningful values for yet, we wait until later in
780  * postmaster startup to print the value. We won't be able to use -C
781  * on running servers for those GUCs, but using this option now would
782  * lead to incorrect results for them.
783  */
784  int flags = GetConfigOptionFlags(output_config_variable, true);
785 
786  if ((flags & GUC_RUNTIME_COMPUTED) == 0)
787  {
788  /*
789  * "-C guc" was specified, so print GUC's value and exit. No
790  * extra permission check is needed because the user is reading
791  * inside the data dir.
792  */
793  const char *config_val = GetConfigOption(output_config_variable,
794  false, false);
795 
796  puts(config_val ? config_val : "");
797  ExitPostmaster(0);
798  }
799 
800  /*
801  * A runtime-computed GUC will be printed later on. As we initialize
802  * a server startup sequence, silence any log messages that may show
803  * up in the output generated. FATAL and more severe messages are
804  * useful to show, even if one would only expect at least PANIC. LOG
805  * entries are hidden.
806  */
807  SetConfigOption("log_min_messages", "FATAL", PGC_SUSET,
809  }
810 
811  /* Verify that DataDir looks reasonable */
812  checkDataDir();
813 
814  /* Check that pg_control exists */
816 
817  /* And switch working directory into it */
818  ChangeToDataDir();
819 
820  /*
821  * Check for invalid combinations of GUC settings.
822  */
824  {
825  write_stderr("%s: \"superuser_reserved_connections\" (%d) plus \"reserved_connections\" (%d) must be less than \"max_connections\" (%d)\n",
826  progname,
829  ExitPostmaster(1);
830  }
832  ereport(ERROR,
833  (errmsg("WAL archival cannot be enabled when \"wal_level\" is \"minimal\"")));
835  ereport(ERROR,
836  (errmsg("WAL streaming (\"max_wal_senders\" > 0) requires \"wal_level\" to be \"replica\" or \"logical\"")));
838  ereport(ERROR,
839  (errmsg("WAL cannot be summarized when \"wal_level\" is \"minimal\"")));
840 
841  /*
842  * Other one-time internal sanity checks can go here, if they are fast.
843  * (Put any slow processing further down, after postmaster.pid creation.)
844  */
845  if (!CheckDateTokenTables())
846  {
847  write_stderr("%s: invalid datetoken tables, please fix\n", progname);
848  ExitPostmaster(1);
849  }
850 
851  /*
852  * Now that we are done processing the postmaster arguments, reset
853  * getopt(3) library so that it will work correctly in subprocesses.
854  */
855  optind = 1;
856 #ifdef HAVE_INT_OPTRESET
857  optreset = 1; /* some systems need this too */
858 #endif
859 
860  /* For debugging: display postmaster environment */
861  {
862  extern char **environ;
863  char **p;
864 
865  ereport(DEBUG3,
866  (errmsg_internal("%s: PostmasterMain: initial environment dump:",
867  progname)));
868  ereport(DEBUG3,
869  (errmsg_internal("-----------------------------------------")));
870  for (p = environ; *p; ++p)
871  ereport(DEBUG3,
872  (errmsg_internal("\t%s", *p)));
873  ereport(DEBUG3,
874  (errmsg_internal("-----------------------------------------")));
875  }
876 
877  /*
878  * Create lockfile for data directory.
879  *
880  * We want to do this before we try to grab the input sockets, because the
881  * data directory interlock is more reliable than the socket-file
882  * interlock (thanks to whoever decided to put socket files in /tmp :-().
883  * For the same reason, it's best to grab the TCP socket(s) before the
884  * Unix socket(s).
885  *
886  * Also note that this internally sets up the on_proc_exit function that
887  * is responsible for removing both data directory and socket lockfiles;
888  * so it must happen before opening sockets so that at exit, the socket
889  * lockfiles go away after CloseServerPorts runs.
890  */
891  CreateDataDirLockFile(true);
892 
893  /*
894  * Read the control file (for error checking and config info).
895  *
896  * Since we verify the control file's CRC, this has a useful side effect
897  * on machines where we need a run-time test for CRC support instructions.
898  * The postmaster will do the test once at startup, and then its child
899  * processes will inherit the correct function pointer and not need to
900  * repeat the test.
901  */
903 
904  /*
905  * Register the apply launcher. It's probably a good idea to call this
906  * before any modules had a chance to take the background worker slots.
907  */
909 
910  /*
911  * process any libraries that should be preloaded at postmaster start
912  */
914 
915  /*
916  * Initialize SSL library, if specified.
917  */
918 #ifdef USE_SSL
919  if (EnableSSL)
920  {
921  (void) secure_initialize(true);
922  LoadedSSL = true;
923  }
924 #endif
925 
926  /*
927  * Now that loadable modules have had their chance to alter any GUCs,
928  * calculate MaxBackends.
929  */
931 
932  /*
933  * Give preloaded libraries a chance to request additional shared memory.
934  */
936 
937  /*
938  * Now that loadable modules have had their chance to request additional
939  * shared memory, determine the value of any runtime-computed GUCs that
940  * depend on the amount of shared memory required.
941  */
943 
944  /*
945  * Now that modules have been loaded, we can process any custom resource
946  * managers specified in the wal_consistency_checking GUC.
947  */
949 
950  /*
951  * If -C was specified with a runtime-computed GUC, we held off printing
952  * the value earlier, as the GUC was not yet initialized. We handle -C
953  * for most GUCs before we lock the data directory so that the option may
954  * be used on a running server. However, a handful of GUCs are runtime-
955  * computed and do not have meaningful values until after locking the data
956  * directory, and we cannot safely calculate their values earlier on a
957  * running server. At this point, such GUCs should be properly
958  * initialized, and we haven't yet set up shared memory, so this is a good
959  * time to handle the -C option for these special GUCs.
960  */
961  if (output_config_variable != NULL)
962  {
963  const char *config_val = GetConfigOption(output_config_variable,
964  false, false);
965 
966  puts(config_val ? config_val : "");
967  ExitPostmaster(0);
968  }
969 
970  /*
971  * Set up shared memory and semaphores.
972  *
973  * Note: if using SysV shmem and/or semas, each postmaster startup will
974  * normally choose the same IPC keys. This helps ensure that we will
975  * clean up dead IPC objects if the postmaster crashes and is restarted.
976  */
978 
979  /*
980  * Estimate number of openable files. This must happen after setting up
981  * semaphores, because on some platforms semaphores count as open files.
982  */
984 
985  /*
986  * Set reference point for stack-depth checking.
987  */
988  (void) set_stack_base();
989 
990  /*
991  * Initialize pipe (or process handle on Windows) that allows children to
992  * wake up from sleep on postmaster death.
993  */
995 
996 #ifdef WIN32
997 
998  /*
999  * Initialize I/O completion port used to deliver list of dead children.
1000  */
1001  win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
1002  if (win32ChildQueue == NULL)
1003  ereport(FATAL,
1004  (errmsg("could not create I/O completion port for child queue")));
1005 #endif
1006 
1007 #ifdef EXEC_BACKEND
1008  /* Write out nondefault GUC settings for child processes to use */
1009  write_nondefault_variables(PGC_POSTMASTER);
1010 
1011  /*
1012  * Clean out the temp directory used to transmit parameters to child
1013  * processes (see internal_forkexec). We must do this before launching
1014  * any child processes, else we have a race condition: we could remove a
1015  * parameter file before the child can read it. It should be safe to do
1016  * so now, because we verified earlier that there are no conflicting
1017  * Postgres processes in this data directory.
1018  */
1020 #endif
1021 
1022  /*
1023  * Forcibly remove the files signaling a standby promotion request.
1024  * Otherwise, the existence of those files triggers a promotion too early,
1025  * whether a user wants that or not.
1026  *
1027  * This removal of files is usually unnecessary because they can exist
1028  * only during a few moments during a standby promotion. However there is
1029  * a race condition: if pg_ctl promote is executed and creates the files
1030  * during a promotion, the files can stay around even after the server is
1031  * brought up to be the primary. Then, if a new standby starts by using
1032  * the backup taken from the new primary, the files can exist at server
1033  * startup and must be removed in order to avoid an unexpected promotion.
1034  *
1035  * Note that promotion signal files need to be removed before the startup
1036  * process is invoked. Because, after that, they can be used by
1037  * postmaster's SIGUSR1 signal handler.
1038  */
1040 
1041  /* Do the same for logrotate signal file */
1043 
1044  /* Remove any outdated file holding the current log filenames. */
1045  if (unlink(LOG_METAINFO_DATAFILE) < 0 && errno != ENOENT)
1046  ereport(LOG,
1048  errmsg("could not remove file \"%s\": %m",
1050 
1051  /*
1052  * If enabled, start up syslogger collection subprocess
1053  */
1055 
1056  /*
1057  * Reset whereToSendOutput from DestDebug (its starting state) to
1058  * DestNone. This stops ereport from sending log messages to stderr unless
1059  * Log_destination permits. We don't do this until the postmaster is
1060  * fully launched, since startup failures may as well be reported to
1061  * stderr.
1062  *
1063  * If we are in fact disabling logging to stderr, first emit a log message
1064  * saying so, to provide a breadcrumb trail for users who may not remember
1065  * that their logging is configured to go somewhere else.
1066  */
1068  ereport(LOG,
1069  (errmsg("ending log output to stderr"),
1070  errhint("Future log output will go to log destination \"%s\".",
1072 
1074 
1075  /*
1076  * Report server startup in log. While we could emit this much earlier,
1077  * it seems best to do so after starting the log collector, if we intend
1078  * to use one.
1079  */
1080  ereport(LOG,
1081  (errmsg("starting %s", PG_VERSION_STR)));
1082 
1083  /*
1084  * Establish input sockets.
1085  *
1086  * First set up an on_proc_exit function that's charged with closing the
1087  * sockets again at postmaster shutdown.
1088  */
1089  ListenSockets = palloc(MAXLISTEN * sizeof(pgsocket));
1091 
1092  if (ListenAddresses)
1093  {
1094  char *rawstring;
1095  List *elemlist;
1096  ListCell *l;
1097  int success = 0;
1098 
1099  /* Need a modifiable copy of ListenAddresses */
1100  rawstring = pstrdup(ListenAddresses);
1101 
1102  /* Parse string into list of hostnames */
1103  if (!SplitGUCList(rawstring, ',', &elemlist))
1104  {
1105  /* syntax error in list */
1106  ereport(FATAL,
1107  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1108  errmsg("invalid list syntax in parameter \"%s\"",
1109  "listen_addresses")));
1110  }
1111 
1112  foreach(l, elemlist)
1113  {
1114  char *curhost = (char *) lfirst(l);
1115 
1116  if (strcmp(curhost, "*") == 0)
1117  status = ListenServerPort(AF_UNSPEC, NULL,
1118  (unsigned short) PostPortNumber,
1119  NULL,
1120  ListenSockets,
1122  MAXLISTEN);
1123  else
1124  status = ListenServerPort(AF_UNSPEC, curhost,
1125  (unsigned short) PostPortNumber,
1126  NULL,
1127  ListenSockets,
1129  MAXLISTEN);
1130 
1131  if (status == STATUS_OK)
1132  {
1133  success++;
1134  /* record the first successful host addr in lockfile */
1135  if (!listen_addr_saved)
1136  {
1138  listen_addr_saved = true;
1139  }
1140  }
1141  else
1142  ereport(WARNING,
1143  (errmsg("could not create listen socket for \"%s\"",
1144  curhost)));
1145  }
1146 
1147  if (!success && elemlist != NIL)
1148  ereport(FATAL,
1149  (errmsg("could not create any TCP/IP sockets")));
1150 
1151  list_free(elemlist);
1152  pfree(rawstring);
1153  }
1154 
1155 #ifdef USE_BONJOUR
1156  /* Register for Bonjour only if we opened TCP socket(s) */
1157  if (enable_bonjour && NumListenSockets > 0)
1158  {
1159  DNSServiceErrorType err;
1160 
1161  /*
1162  * We pass 0 for interface_index, which will result in registering on
1163  * all "applicable" interfaces. It's not entirely clear from the
1164  * DNS-SD docs whether this would be appropriate if we have bound to
1165  * just a subset of the available network interfaces.
1166  */
1167  err = DNSServiceRegister(&bonjour_sdref,
1168  0,
1169  0,
1170  bonjour_name,
1171  "_postgresql._tcp.",
1172  NULL,
1173  NULL,
1175  0,
1176  NULL,
1177  NULL,
1178  NULL);
1179  if (err != kDNSServiceErr_NoError)
1180  ereport(LOG,
1181  (errmsg("DNSServiceRegister() failed: error code %ld",
1182  (long) err)));
1183 
1184  /*
1185  * We don't bother to read the mDNS daemon's reply, and we expect that
1186  * it will automatically terminate our registration when the socket is
1187  * closed at postmaster termination. So there's nothing more to be
1188  * done here. However, the bonjour_sdref is kept around so that
1189  * forked children can close their copies of the socket.
1190  */
1191  }
1192 #endif
1193 
1195  {
1196  char *rawstring;
1197  List *elemlist;
1198  ListCell *l;
1199  int success = 0;
1200 
1201  /* Need a modifiable copy of Unix_socket_directories */
1202  rawstring = pstrdup(Unix_socket_directories);
1203 
1204  /* Parse string into list of directories */
1205  if (!SplitDirectoriesString(rawstring, ',', &elemlist))
1206  {
1207  /* syntax error in list */
1208  ereport(FATAL,
1209  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1210  errmsg("invalid list syntax in parameter \"%s\"",
1211  "unix_socket_directories")));
1212  }
1213 
1214  foreach(l, elemlist)
1215  {
1216  char *socketdir = (char *) lfirst(l);
1217 
1218  status = ListenServerPort(AF_UNIX, NULL,
1219  (unsigned short) PostPortNumber,
1220  socketdir,
1221  ListenSockets,
1223  MAXLISTEN);
1224 
1225  if (status == STATUS_OK)
1226  {
1227  success++;
1228  /* record the first successful Unix socket in lockfile */
1229  if (success == 1)
1231  }
1232  else
1233  ereport(WARNING,
1234  (errmsg("could not create Unix-domain socket in directory \"%s\"",
1235  socketdir)));
1236  }
1237 
1238  if (!success && elemlist != NIL)
1239  ereport(FATAL,
1240  (errmsg("could not create any Unix-domain sockets")));
1241 
1242  list_free_deep(elemlist);
1243  pfree(rawstring);
1244  }
1245 
1246  /*
1247  * check that we have some socket to listen on
1248  */
1249  if (NumListenSockets == 0)
1250  ereport(FATAL,
1251  (errmsg("no socket created for listening")));
1252 
1253  /*
1254  * If no valid TCP ports, write an empty line for listen address,
1255  * indicating the Unix socket must be used. Note that this line is not
1256  * added to the lock file until there is a socket backing it.
1257  */
1258  if (!listen_addr_saved)
1260 
1261  /*
1262  * Record postmaster options. We delay this till now to avoid recording
1263  * bogus options (eg, unusable port number).
1264  */
1265  if (!CreateOptsFile(argc, argv, my_exec_path))
1266  ExitPostmaster(1);
1267 
1268  /*
1269  * Write the external PID file if requested
1270  */
1271  if (external_pid_file)
1272  {
1273  FILE *fpidfile = fopen(external_pid_file, "w");
1274 
1275  if (fpidfile)
1276  {
1277  fprintf(fpidfile, "%d\n", MyProcPid);
1278  fclose(fpidfile);
1279 
1280  /* Make PID file world readable */
1281  if (chmod(external_pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) != 0)
1282  write_stderr("%s: could not change permissions of external PID file \"%s\": %m\n",
1284  }
1285  else
1286  write_stderr("%s: could not write external PID file \"%s\": %m\n",
1288 
1290  }
1291 
1292  /*
1293  * Remove old temporary files. At this point there can be no other
1294  * Postgres processes running in this directory, so this should be safe.
1295  */
1297 
1298  /*
1299  * Initialize the autovacuum subsystem (again, no process start yet)
1300  */
1301  autovac_init();
1302 
1303  /*
1304  * Load configuration files for client authentication.
1305  */
1306  if (!load_hba())
1307  {
1308  /*
1309  * It makes no sense to continue if we fail to load the HBA file,
1310  * since there is no way to connect to the database in this case.
1311  */
1312  ereport(FATAL,
1313  /* translator: %s is a configuration file */
1314  (errmsg("could not load %s", HbaFileName)));
1315  }
1316  if (!load_ident())
1317  {
1318  /*
1319  * We can start up without the IDENT file, although it means that you
1320  * cannot log in using any of the authentication methods that need a
1321  * user name mapping. load_ident() already logged the details of error
1322  * to the log.
1323  */
1324  }
1325 
1326 #ifdef HAVE_PTHREAD_IS_THREADED_NP
1327 
1328  /*
1329  * On macOS, libintl replaces setlocale() with a version that calls
1330  * CFLocaleCopyCurrent() when its second argument is "" and every relevant
1331  * environment variable is unset or empty. CFLocaleCopyCurrent() makes
1332  * the process multithreaded. The postmaster calls sigprocmask() and
1333  * calls fork() without an immediate exec(), both of which have undefined
1334  * behavior in a multithreaded program. A multithreaded postmaster is the
1335  * normal case on Windows, which offers neither fork() nor sigprocmask().
1336  */
1337  if (pthread_is_threaded_np() != 0)
1338  ereport(FATAL,
1339  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1340  errmsg("postmaster became multithreaded during startup"),
1341  errhint("Set the LC_ALL environment variable to a valid locale.")));
1342 #endif
1343 
1344  /*
1345  * Remember postmaster startup time
1346  */
1348 
1349  /*
1350  * Report postmaster status in the postmaster.pid file, to allow pg_ctl to
1351  * see what's happening.
1352  */
1354 
1355  /* Start bgwriter and checkpointer so they can help with recovery */
1356  if (CheckpointerPID == 0)
1358  if (BgWriterPID == 0)
1360 
1361  /*
1362  * We're ready to rock and roll...
1363  */
1365  Assert(StartupPID != 0);
1367  pmState = PM_STARTUP;
1368 
1369  /* Some workers may be scheduled to start now */
1371 
1372  status = ServerLoop();
1373 
1374  /*
1375  * ServerLoop probably shouldn't ever return, but if it does, close down.
1376  */
1377  ExitPostmaster(status != STATUS_OK);
1378 
1379  abort(); /* not reached */
1380 }
void autovac_init(void)
Definition: autovacuum.c:3246
void pqinitmask(void)
Definition: pqsignal.c:41
sigset_t UnBlockSig
Definition: pqsignal.c:22
sigset_t BlockSig
Definition: pqsignal.c:23
bool CheckDateTokenTables(void)
Definition: datetime.c:4800
TimestampTz PgStartTime
Definition: timestamp.c:52
int secure_initialize(bool isServerStart)
Definition: be-secure.c:73
#define write_stderr(str)
Definition: parallel.c:184
#define STATUS_OK
Definition: c.h:1169
@ DestNone
Definition: dest.h:87
int Log_destination
Definition: elog.c:112
int errhint(const char *fmt,...)
Definition: elog.c:1317
char * Log_destination_string
Definition: elog.c:113
int errcode(int sqlerrcode)
Definition: elog.c:857
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define DEBUG3
Definition: elog.h:28
#define WARNING
Definition: elog.h:36
#define ERROR
Definition: elog.h:39
#define LOG_DESTINATION_STDERR
Definition: elog.h:492
void err(int eval, const char *fmt,...)
Definition: err.c:43
void RemovePgTempFilesInDir(const char *tmpdirname, bool missing_ok, bool unlink_all)
Definition: fd.c:3333
void RemovePgTempFiles(void)
Definition: fd.c:3274
void set_max_safe_fds(void)
Definition: fd.c:1044
#define PG_MODE_MASK_OWNER
Definition: file_perm.h:24
#define PG_TEMP_FILES_DIR
Definition: file_utils.h:62
bool IsBinaryUpgrade
Definition: globals.c:118
pid_t PostmasterPid
Definition: globals.c:103
char my_exec_path[MAXPGPATH]
Definition: globals.c:78
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4285
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:1786
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:6321
void InitializeGUCOptions(void)
Definition: guc.c:1532
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_privileged)
Definition: guc.c:4308
int GetConfigOptionFlags(const char *name, bool missing_ok)
Definition: guc.c:4405
#define GUC_RUNTIME_COMPUTED
Definition: guc.h:225
@ PGC_S_OVERRIDE
Definition: guc.h:119
@ PGC_S_ARGV
Definition: guc.h:113
@ PGC_SUSET
Definition: guc.h:74
@ PGC_POSTMASTER
Definition: guc.h:70
char * HbaFileName
Definition: guc_tables.c:541
char * external_pid_file
Definition: guc_tables.c:543
bool load_ident(void)
Definition: hba.c:2959
bool load_hba(void)
Definition: hba.c:2583
static struct @155 value
static bool success
Definition: initdb.c:186
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:309
void InitializeShmemGUCs(void)
Definition: ipci.c:369
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:199
void InitializeLatchSupport(void)
Definition: latch.c:232
void ApplyLauncherRegister(void)
Definition: launcher.c:918
void list_free(List *list)
Definition: list.c:1546
void list_free_deep(List *list)
Definition: list.c:1560
const char * progname
Definition: main.c:44
char * pstrdup(const char *in)
Definition: mcxt.c:1695
MemoryContext PostmasterContext
Definition: mcxt.c:151
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
@ B_CHECKPOINTER
Definition: miscadmin.h:357
@ B_STARTUP
Definition: miscadmin.h:358
@ B_BG_WRITER
Definition: miscadmin.h:356
void ChangeToDataDir(void)
Definition: miscinit.c:454
void process_shmem_requests(void)
Definition: miscinit.c:1871
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1511
void InitProcessLocalLatch(void)
Definition: miscinit.c:241
void process_shared_preload_libraries(void)
Definition: miscinit.c:1843
void checkDataDir(void)
Definition: miscinit.c:341
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1455
#define pg_hton16(x)
Definition: pg_bswap.h:120
PGDLLIMPORT int optind
Definition: getopt.c:50
PGDLLIMPORT int opterr
Definition: getopt.c:49
int getopt(int nargc, char *const *nargv, const char *ostr)
Definition: getopt.c:71
PGDLLIMPORT char * optarg
Definition: getopt.c:52
#define lfirst(lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:68
#define PM_STATUS_STARTING
Definition: pidfile.h:51
#define LOCK_FILE_LINE_LISTEN_ADDR
Definition: pidfile.h:42
#define LOCK_FILE_LINE_PM_STATUS
Definition: pidfile.h:44
#define LOCK_FILE_LINE_SOCKET_DIR
Definition: pidfile.h:41
pqsigfunc pqsignal(int signo, pqsigfunc func)
int pgsocket
Definition: port.h:29
#define fprintf
Definition: port.h:242
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3679
CommandDest whereToSendOutput
Definition: postgres.c:90
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3708
static const char * userDoption
Definition: postgres.c:161
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3750
pg_stack_base_t set_stack_base(void)
Definition: postgres.c:3481
void InitializeMaxBackends(void)
Definition: postinit.c:575
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:3668
static void handle_pm_shutdown_request_signal(SIGNAL_ARGS)
Definition: postmaster.c:2168
static void maybe_start_bgworkers(void)
Definition: postmaster.c:4409
static void CloseServerPorts(int status, Datum arg)
Definition: postmaster.c:1387
@ PM_STARTUP
Definition: postmaster.c:317
static void InitPostmasterDeathWatchHandle(void)
Definition: postmaster.c:4703
void InitProcessGlobals(void)
Definition: postmaster.c:2032
static void handle_pm_reload_request_signal(SIGNAL_ARGS)
Definition: postmaster.c:2085
static int ServerLoop(void)
Definition: postmaster.c:1624
int PostPortNumber
Definition: postmaster.c:190
static void checkControlFile(void)
Definition: postmaster.c:1487
bool enable_bonjour
Definition: postmaster.c:233
int ReservedConnections
Definition: postmaster.c:217
static pid_t StartChildProcess(BackendType type)
Definition: postmaster.c:3924
static void handle_pm_pmsignal_signal(SIGNAL_ARGS)
Definition: postmaster.c:2075
static pid_t CheckpointerPID
Definition: postmaster.c:243
static pid_t BgWriterPID
Definition: postmaster.c:242
char * Unix_socket_directories
Definition: postmaster.c:193
static bool CreateOptsFile(int argc, char *argv[], char *fullprogname)
Definition: postmaster.c:4101
static void handle_pm_child_exit_signal(SIGNAL_ARGS)
Definition: postmaster.c:2343
static void getInstallationPaths(const char *argv0)
Definition: postmaster.c:1433
@ STARTUP_RUNNING
Definition: postmaster.c:256
static void unlink_external_pid_file(int status, Datum arg)
Definition: postmaster.c:1421
static StartupStatusEnum StartupStatus
Definition: postmaster.c:261
#define MAXLISTEN
Definition: postmaster.c:220
static void dummy_handler(SIGNAL_ARGS)
Definition: postmaster.c:3860
static pid_t StartupPID
Definition: postmaster.c:241
bool EnableSSL
Definition: postmaster.c:225
static PMState pmState
Definition: postmaster.c:331
char * ListenAddresses
Definition: postmaster.c:196
int SuperuserReservedConnections
Definition: postmaster.c:216
char * bonjour_name
Definition: postmaster.c:234
static pid_t SysLoggerPID
Definition: postmaster.c:249
PGDLLIMPORT bool LoadedSSL
int ListenServerPort(int family, const char *hostName, unsigned short portNumber, const char *unixSocketDir, pgsocket ListenSockets[], int *NumListenSockets, int MaxListen)
Definition: pqcomm.c:417
char ** environ
void pgwin32_signal_initialize(void)
Definition: signal.c:79
Definition: pg_list.h:54
void RemoveLogrotateSignalFiles(void)
Definition: syslogger.c:1587
int SysLogger_Start(void)
Definition: syslogger.c:595
#define LOG_METAINFO_DATAFILE
Definition: syslogger.h:98
bool SplitDirectoriesString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3584
bool SplitGUCList(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3705
bool summarize_wal
#define S_IROTH
Definition: win32_port.h:313
#define SIGCHLD
Definition: win32_port.h:178
#define SIGHUP
Definition: win32_port.h:168
#define S_IRGRP
Definition: win32_port.h:301
#define SIGPIPE
Definition: win32_port.h:173
#define SIGQUIT
Definition: win32_port.h:169
#define S_IRUSR
Definition: win32_port.h:289
#define SIGUSR1
Definition: win32_port.h:180
#define SIGALRM
Definition: win32_port.h:174
#define SIGUSR2
Definition: win32_port.h:181
#define SIG_IGN
Definition: win32_port.h:165
#define S_IWUSR
Definition: win32_port.h:292
int XLogArchiveMode
Definition: xlog.c:119
int wal_level
Definition: xlog.c:131
void InitializeWalConsistencyChecking(void)
Definition: xlog.c:4751
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4813
@ ARCHIVE_MODE_OFF
Definition: xlog.h:63
@ WAL_LEVEL_MINIMAL
Definition: xlog.h:72
void RemovePromoteSignalFiles(void)

References AddToDataDirLockFile(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, ApplyLauncherRegister(), ARCHIVE_MODE_OFF, Assert, autovac_init(), B_BG_WRITER, B_CHECKPOINTER, B_STARTUP, BgWriterPID, BlockSig, bonjour_name, ChangeToDataDir(), checkControlFile(), checkDataDir(), CheckDateTokenTables(), CheckpointerPID, CloseServerPorts(), CreateDataDirLockFile(), CreateOptsFile(), CreateSharedMemoryAndSemaphores(), DEBUG3, DestNone, dummy_handler(), enable_bonjour, EnableSSL, environ, ereport, err(), errcode(), errcode_for_file_access(), errhint(), errmsg(), errmsg_internal(), ERROR, ExitPostmaster(), external_pid_file, FATAL, fprintf, get_stats_option_name(), GetConfigOption(), GetConfigOptionFlags(), GetCurrentTimestamp(), getInstallationPaths(), getopt(), GUC_RUNTIME_COMPUTED, handle_pm_child_exit_signal(), handle_pm_pmsignal_signal(), handle_pm_reload_request_signal(), handle_pm_shutdown_request_signal(), HbaFileName, InitializeGUCOptions(), InitializeLatchSupport(), InitializeMaxBackends(), InitializeShmemGUCs(), InitializeWalConsistencyChecking(), InitPostmasterDeathWatchHandle(), InitProcessGlobals(), InitProcessLocalLatch(), IsBinaryUpgrade, IsPostmasterEnvironment, lfirst, list_free(), list_free_deep(), ListenAddresses, ListenServerPort(), ListenSockets, load_hba(), load_ident(), LoadedSSL, LocalProcessControlFile(), LOCK_FILE_LINE_LISTEN_ADDR, LOCK_FILE_LINE_PM_STATUS, LOCK_FILE_LINE_SOCKET_DIR, LOG, Log_destination, LOG_DESTINATION_STDERR, Log_destination_string, LOG_METAINFO_DATAFILE, max_wal_senders, MaxConnections, MAXLISTEN, maybe_start_bgworkers(), MemoryContextSwitchTo(), my_exec_path, MyProcPid, name, NIL, NumListenSockets, on_proc_exit(), optarg, opterr, optind, palloc(), ParseLongOption(), pfree(), pg_hton16, PG_MODE_MASK_OWNER, PG_TEMP_FILES_DIR, PGC_POSTMASTER, PGC_S_ARGV, PGC_S_OVERRIDE, PGC_SUSET, PgStartTime, pgwin32_signal_initialize(), PM_STARTUP, PM_STATUS_STARTING, pmState, PostmasterContext, PostmasterPid, PostPortNumber, pqinitmask(), pqsignal(), process_shared_preload_libraries(), process_shmem_requests(), progname, pstrdup(), RemoveLogrotateSignalFiles(), RemovePgTempFiles(), RemovePgTempFilesInDir(), RemovePromoteSignalFiles(), ReservedConnections, S_IRGRP, S_IROTH, S_IRUSR, S_IWUSR, secure_initialize(), SelectConfigFiles(), ServerLoop(), set_debug_options(), set_max_safe_fds(), set_plan_disabling_options(), set_stack_base(), SetConfigOption(), SIG_IGN, SIGALRM, SIGCHLD, SIGHUP, SIGPIPE, SIGQUIT, SIGUSR1, SIGUSR2, SplitDirectoriesString(), SplitGUCList(), StartChildProcess(), STARTUP_RUNNING, StartupPID, StartupStatus, STATUS_OK, success, summarize_wal, SuperuserReservedConnections, SysLogger_Start(), SysLoggerPID, TopMemoryContext, UnBlockSig, Unix_socket_directories, unlink_external_pid_file(), userDoption, value, wal_level, WAL_LEVEL_MINIMAL, WARNING, whereToSendOutput, write_stderr, and XLogArchiveMode.

Referenced by main().

◆ PostmasterMarkPIDForWorkerNotify()

bool PostmasterMarkPIDForWorkerNotify ( int  pid)

Definition at line 4528 of file postmaster.c.

4529 {
4530  dlist_iter iter;
4531  Backend *bp;
4532 
4533  dlist_foreach(iter, &BackendList)
4534  {
4535  bp = dlist_container(Backend, elem, iter.cur);
4536  if (bp->pid == pid)
4537  {
4538  bp->bgworker_notify = true;
4539  return true;
4540  }
4541  }
4542  return false;
4543 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:623
#define dlist_container(type, membername, ptr)
Definition: ilist.h:593
static dlist_head BackendList
Definition: postmaster.c:179
bool bgworker_notify
Definition: postmaster.c:175
pid_t pid
Definition: postmaster.c:170
dlist_node * cur
Definition: ilist.h:179

References BackendList, bkend::bgworker_notify, dlist_iter::cur, dlist_container, dlist_foreach, and bkend::pid.

Referenced by BackgroundWorkerStateChange().

◆ processCancelRequest()

void processCancelRequest ( int  backendPID,
int32  cancelAuthCode 
)

Definition at line 1835 of file postmaster.c.

1836 {
1837  Backend *bp;
1838 
1839 #ifndef EXEC_BACKEND
1840  dlist_iter iter;
1841 #else
1842  int i;
1843 #endif
1844 
1845  /*
1846  * See if we have a matching backend. In the EXEC_BACKEND case, we can no
1847  * longer access the postmaster's own backend list, and must rely on the
1848  * duplicate array in shared memory.
1849  */
1850 #ifndef EXEC_BACKEND
1851  dlist_foreach(iter, &BackendList)
1852  {
1853  bp = dlist_container(Backend, elem, iter.cur);
1854 #else
1855  for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
1856  {
1857  bp = (Backend *) &ShmemBackendArray[i];
1858 #endif
1859  if (bp->pid == backendPID)
1860  {
1861  if (bp->cancel_key == cancelAuthCode)
1862  {
1863  /* Found a match; signal that backend to cancel current op */
1864  ereport(DEBUG2,
1865  (errmsg_internal("processing cancel request: sending SIGINT to process %d",
1866  backendPID)));
1867  signal_child(bp->pid, SIGINT);
1868  }
1869  else
1870  /* Right PID, wrong key: no way, Jose */
1871  ereport(LOG,
1872  (errmsg("wrong key in cancel request for process %d",
1873  backendPID)));
1874  return;
1875  }
1876 #ifndef EXEC_BACKEND /* make GNU Emacs 26.1 see brace balance */
1877  }
1878 #else
1879  }
1880 #endif
1881 
1882  /* No matching backend */
1883  ereport(LOG,
1884  (errmsg("PID %d in cancel request did not match any process",
1885  backendPID)));
1886 }
#define DEBUG2
Definition: elog.h:29
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:3421
int MaxLivePostmasterChildren(void)
Definition: postmaster.c:4145
int32 cancel_key
Definition: postmaster.c:171

References BackendList, bkend::cancel_key, dlist_iter::cur, DEBUG2, dlist_container, dlist_foreach, ereport, errmsg(), errmsg_internal(), i, LOG, MaxLivePostmasterChildren(), bkend::pid, and signal_child().

Referenced by ProcessStartupPacket().

Variable Documentation

◆ AuthenticationTimeout

PGDLLIMPORT int AuthenticationTimeout
extern

Definition at line 228 of file postmaster.c.

Referenced by BackendInitialize(), and PerformAuthentication().

◆ bonjour_name

PGDLLIMPORT char* bonjour_name
extern

Definition at line 234 of file postmaster.c.

Referenced by PostmasterMain().

◆ ClientAuthInProgress

◆ enable_bonjour

PGDLLIMPORT bool enable_bonjour
extern

Definition at line 233 of file postmaster.c.

Referenced by PostmasterMain().

◆ EnableSSL

PGDLLIMPORT bool EnableSSL
extern

◆ ListenAddresses

PGDLLIMPORT char* ListenAddresses
extern

Definition at line 196 of file postmaster.c.

Referenced by PostmasterMain().

◆ LoadedSSL

◆ Log_connections

PGDLLIMPORT bool Log_connections
extern

◆ log_hostname

PGDLLIMPORT bool log_hostname
extern

Definition at line 230 of file postmaster.c.

Referenced by BackendInitialize().

◆ MyClientSocket

PGDLLIMPORT struct ClientSocket* MyClientSocket
extern

Definition at line 48 of file globals.c.

Referenced by BackendMain(), and postmaster_child_launch().

◆ postmaster_alive_fds

◆ PostPortNumber

PGDLLIMPORT int PostPortNumber
extern

Definition at line 190 of file postmaster.c.

Referenced by CreateLockFile(), and PostmasterMain().

◆ PreAuthDelay

PGDLLIMPORT int PreAuthDelay
extern

Definition at line 227 of file postmaster.c.

Referenced by BackendInitialize().

◆ progname

◆ remove_temp_files_after_crash

PGDLLIMPORT bool remove_temp_files_after_crash
extern

Definition at line 236 of file postmaster.c.

Referenced by PostmasterStateMachine().

◆ ReservedConnections

PGDLLIMPORT int ReservedConnections
extern

Definition at line 217 of file postmaster.c.

Referenced by InitPostgres(), and PostmasterMain().

◆ restart_after_crash

PGDLLIMPORT bool restart_after_crash
extern

Definition at line 235 of file postmaster.c.

Referenced by PostmasterStateMachine().

◆ send_abort_for_crash

PGDLLIMPORT bool send_abort_for_crash
extern

Definition at line 237 of file postmaster.c.

Referenced by sigquit_child().

◆ send_abort_for_kill

PGDLLIMPORT bool send_abort_for_kill
extern

Definition at line 238 of file postmaster.c.

Referenced by ServerLoop().

◆ SuperuserReservedConnections

PGDLLIMPORT int SuperuserReservedConnections
extern

Definition at line 216 of file postmaster.c.

Referenced by InitPostgres(), and PostmasterMain().

◆ Unix_socket_directories

PGDLLIMPORT char* Unix_socket_directories
extern

Definition at line 193 of file postmaster.c.

Referenced by PostmasterMain().

◆ Unix_socket_group

PGDLLIMPORT char* Unix_socket_group
extern

Definition at line 106 of file pqcomm.c.

Referenced by Setup_AF_UNIX().

◆ Unix_socket_permissions

PGDLLIMPORT int Unix_socket_permissions
extern

Definition at line 105 of file pqcomm.c.

Referenced by Setup_AF_UNIX(), and show_unix_socket_permissions().