PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
postmaster.h File Reference
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)
 
int MaxLivePostmasterChildren (void)
 
int GetNumShmemAttachedBgworkers (void)
 
bool PostmasterMarkPIDForWorkerNotify (int)
 

Variables

bool EnableSSL
 
int ReservedBackends
 
int PostPortNumber
 
int Unix_socket_permissions
 
char * Unix_socket_group
 
char * Unix_socket_directories
 
char * ListenAddresses
 
bool ClientAuthInProgress
 
int PreAuthDelay
 
int AuthenticationTimeout
 
bool Log_connections
 
bool log_hostname
 
bool enable_bonjour
 
char * bonjour_name
 
bool restart_after_crash
 
int postmaster_alive_fds [2]
 
const char * progname
 

Macro Definition Documentation

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

Definition at line 44 of file postmaster.h.

Referenced by ClosePostmasterPorts().

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

Definition at line 42 of file postmaster.h.

Referenced by AddWaitEventToSet(), InitPostmasterDeathWatchHandle(), and PostmasterIsAlive().

Function Documentation

void ClosePostmasterPorts ( bool  am_syslogger)

Definition at line 2414 of file postmaster.c.

References close, ereport, errcode_for_file_access(), errmsg_internal(), FATAL, i, ListenSocket, MAXLISTEN, PGINVALID_SOCKET, postmaster_alive_fds, POSTMASTER_FD_OWN, StreamClose(), and syslogPipe.

Referenced by BackendStartup(), do_start_bgworker(), pgarch_start(), pgstat_start(), StartAutoVacLauncher(), StartAutoVacWorker(), StartChildProcess(), and SysLogger_Start().

2415 {
2416  int i;
2417 
2418 #ifndef WIN32
2419 
2420  /*
2421  * Close the write end of postmaster death watch pipe. It's important to
2422  * do this as early as possible, so that if postmaster dies, others won't
2423  * think that it's still running because we're holding the pipe open.
2424  */
2426  ereport(FATAL,
2428  errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
2430 #endif
2431 
2432  /* Close the listen sockets */
2433  for (i = 0; i < MAXLISTEN; i++)
2434  {
2435  if (ListenSocket[i] != PGINVALID_SOCKET)
2436  {
2439  }
2440  }
2441 
2442  /* If using syslogger, close the read side of the pipe */
2443  if (!am_syslogger)
2444  {
2445 #ifndef WIN32
2446  if (syslogPipe[0] >= 0)
2447  close(syslogPipe[0]);
2448  syslogPipe[0] = -1;
2449 #else
2450  if (syslogPipe[0])
2451  CloseHandle(syslogPipe[0]);
2452  syslogPipe[0] = 0;
2453 #endif
2454  }
2455 
2456 #ifdef USE_BONJOUR
2457  /* If using Bonjour, close the connection to the mDNS daemon */
2458  if (bonjour_sdref)
2459  close(DNSServiceRefSockFD(bonjour_sdref));
2460 #endif
2461 }
void StreamClose(pgsocket sock)
Definition: pqcomm.c:791
#define FATAL
Definition: elog.h:52
bool am_syslogger
Definition: syslogger.c:74
#define POSTMASTER_FD_OWN
Definition: postmaster.h:44
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
int postmaster_alive_fds[2]
Definition: postmaster.c:556
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:215
#define PGINVALID_SOCKET
Definition: port.h:24
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
int i
#define close(a)
Definition: win32.h:17
#define MAXLISTEN
Definition: postmaster.c:214
int syslogPipe[2]
Definition: syslogger.c:112
int GetNumShmemAttachedBgworkers ( void  )
int MaxLivePostmasterChildren ( void  )

Definition at line 5435 of file postmaster.c.

References autovacuum_max_workers, max_worker_processes, and MaxConnections.

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

5436 {
5437  return 2 * (MaxConnections + autovacuum_max_workers + 1 +
5439 }
int MaxConnections
Definition: globals.c:123
int autovacuum_max_workers
Definition: autovacuum.c:112
int max_worker_processes
Definition: globals.c:124
void PostmasterMain ( int  argc,
char *  argv[] 
)

Definition at line 566 of file postmaster.c.

References AddToDataDirLockFile(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), ApplyLauncherRegister(), ARCHIVE_MODE_OFF, Assert, autovac_init(), BlockSig, bonjour_name, ChangeToDataDir(), checkDataDir(), CheckDateTokenTables(), CloseServerPorts(), CreateDataDirLockFile(), CreateOptsFile(), DEBUG3, DestNone, dummy_handler(), elog, enable_bonjour, EnableSSL, environ, ereport, errcode(), errhint(), errmsg(), errmsg_internal(), ERROR, ExitPostmaster(), external_pid_file, ExtraOptions, FATAL, free, get_stats_option_name(), GetConfigOption(), GetCurrentTimestamp(), getInstallationPaths(), getopt(), gettimeofday(), i, InitializeGUCOptions(), InitializeMaxBackends(), InitPostmasterDeathWatchHandle(), IsBinaryUpgrade, IsPostmasterEnvironment, lfirst, list_free(), list_free_deep(), ListenAddresses, ListenSocket, load_hba(), load_ident(), LOCK_FILE_LINE_LISTEN_ADDR, LOCK_FILE_LINE_SOCKET_DIR, LOG, Log_destination, LOG_DESTINATION_STDERR, Log_destination_string, max_wal_senders, MaxConnections, MAXLISTEN, maybe_start_bgworker(), MemoryContextSwitchTo(), my_exec_path, MyProcPid, MyStartTime, name, NIL, NULL, on_proc_exit(), optarg, opterr, optind, ParseLongOption(), pfree(), PG_SETMASK, PGC_POSTMASTER, PGC_S_ARGV, PGINVALID_SOCKET, PgStartTime, pgstat_init(), PM_STARTUP, pmdie(), pmState, PostmasterContext, PostmasterPid, PostPortNumber, pqinitmask(), pqsignal(), process_shared_preload_libraries(), progname, pstrdup(), random_start_time, reaper(), Reinit, RemovePgTempFiles(), RemovePromoteSignalFiles(), ReservedBackends, reset_shared(), S_IRGRP, S_IROTH, S_IRWXG, S_IRWXO, secure_initialize(), SelectConfigFiles(), SendStop, ServerLoop(), set_debug_options(), set_max_safe_fds(), set_plan_disabling_options(), set_stack_base(), SetConfigOption(), SIG_IGN, SIGALRM, SIGCHLD, SIGHUP, SIGHUP_handler(), SIGPIPE, SIGQUIT, SIGTTIN, SIGTTOU, SIGUSR1, sigusr1_handler(), SIGUSR2, snprintf(), SplitDirectoriesString(), SplitIdentifierString(), srandom(), STARTUP_RUNNING, StartupDataBase, StartupPID, StartupStatus, status(), STATUS_OK, StreamServerPort(), strerror(), success, SysLogger_Start(), SysLoggerPID, TopMemoryContext, Unix_socket_directories, unlink_external_pid_file(), userDoption, value, wal_level, WAL_LEVEL_MINIMAL, WARNING, whereToSendOutput, write_stderr, and XLogArchiveMode.

Referenced by main().

567 {
568  int opt;
569  int status;
570  char *userDoption = NULL;
571  bool listen_addr_saved = false;
572  int i;
573  char *output_config_variable = NULL;
574 
575  MyProcPid = PostmasterPid = getpid();
576 
577  MyStartTime = time(NULL);
578 
580 
581  /*
582  * for security, no dir or file created can be group or other accessible
583  */
584  umask(S_IRWXG | S_IRWXO);
585 
586  /*
587  * Initialize random(3) so we don't get the same values in every run.
588  *
589  * Note: the seed is pretty predictable from externally-visible facts such
590  * as postmaster start time, so avoid using random() for security-critical
591  * random values during postmaster startup. At the time of first
592  * connection, PostmasterRandom will select a hopefully-more-random seed.
593  */
594  srandom((unsigned int) (MyProcPid ^ MyStartTime));
595 
596  /*
597  * By default, palloc() requests in the postmaster will be allocated in
598  * the PostmasterContext, which is space that can be recycled by backends.
599  * Allocated data that needs to be available to backends should be
600  * allocated in TopMemoryContext.
601  */
603  "Postmaster",
606 
607  /* Initialize paths to installation files */
608  getInstallationPaths(argv[0]);
609 
610  /*
611  * Set up signal handlers for the postmaster process.
612  *
613  * CAUTION: when changing this list, check for side-effects on the signal
614  * handling setup of child processes. See tcop/postgres.c,
615  * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/walwriter.c,
616  * postmaster/autovacuum.c, postmaster/pgarch.c, postmaster/pgstat.c,
617  * postmaster/syslogger.c, postmaster/bgworker.c and
618  * postmaster/checkpointer.c.
619  */
620  pqinitmask();
622 
623  pqsignal(SIGHUP, SIGHUP_handler); /* reread config file and have
624  * children do same */
625  pqsignal(SIGINT, pmdie); /* send SIGTERM and shut down */
626  pqsignal(SIGQUIT, pmdie); /* send SIGQUIT and die */
627  pqsignal(SIGTERM, pmdie); /* wait for children and shut down */
628  pqsignal(SIGALRM, SIG_IGN); /* ignored */
629  pqsignal(SIGPIPE, SIG_IGN); /* ignored */
630  pqsignal(SIGUSR1, sigusr1_handler); /* message from child process */
631  pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
632  pqsignal(SIGCHLD, reaper); /* handle child termination */
633  pqsignal(SIGTTIN, SIG_IGN); /* ignored */
634  pqsignal(SIGTTOU, SIG_IGN); /* ignored */
635  /* ignore SIGXFSZ, so that ulimit violations work like disk full */
636 #ifdef SIGXFSZ
637  pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
638 #endif
639 
640  /*
641  * Options setup
642  */
644 
645  opterr = 1;
646 
647  /*
648  * Parse command-line options. CAUTION: keep this in sync with
649  * tcop/postgres.c (the option sets should not conflict) and with the
650  * common help() function in main/main.c.
651  */
652  while ((opt = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:W:-:")) != -1)
653  {
654  switch (opt)
655  {
656  case 'B':
657  SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
658  break;
659 
660  case 'b':
661  /* Undocumented flag used for binary upgrades */
662  IsBinaryUpgrade = true;
663  break;
664 
665  case 'C':
666  output_config_variable = strdup(optarg);
667  break;
668 
669  case 'D':
670  userDoption = strdup(optarg);
671  break;
672 
673  case 'd':
675  break;
676 
677  case 'E':
678  SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
679  break;
680 
681  case 'e':
682  SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
683  break;
684 
685  case 'F':
686  SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
687  break;
688 
689  case 'f':
691  {
692  write_stderr("%s: invalid argument for option -f: \"%s\"\n",
693  progname, optarg);
694  ExitPostmaster(1);
695  }
696  break;
697 
698  case 'h':
699  SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
700  break;
701 
702  case 'i':
703  SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
704  break;
705 
706  case 'j':
707  /* only used by interactive backend */
708  break;
709 
710  case 'k':
711  SetConfigOption("unix_socket_directories", optarg, PGC_POSTMASTER, PGC_S_ARGV);
712  break;
713 
714  case 'l':
715  SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
716  break;
717 
718  case 'N':
719  SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
720  break;
721 
722  case 'n':
723  /* Don't reinit shared mem after abnormal exit */
724  Reinit = false;
725  break;
726 
727  case 'O':
728  SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
729  break;
730 
731  case 'o':
732  /* Other options to pass to the backend on the command line */
734  sizeof(ExtraOptions) - strlen(ExtraOptions),
735  " %s", optarg);
736  break;
737 
738  case 'P':
739  SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
740  break;
741 
742  case 'p':
744  break;
745 
746  case 'r':
747  /* only used by single-user backend */
748  break;
749 
750  case 'S':
752  break;
753 
754  case 's':
755  SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
756  break;
757 
758  case 'T':
759 
760  /*
761  * In the event that some backend dumps core, send SIGSTOP,
762  * rather than SIGQUIT, to all its peers. This lets the wily
763  * post_hacker collect core dumps from everyone.
764  */
765  SendStop = true;
766  break;
767 
768  case 't':
769  {
770  const char *tmp = get_stats_option_name(optarg);
771 
772  if (tmp)
773  {
775  }
776  else
777  {
778  write_stderr("%s: invalid argument for option -t: \"%s\"\n",
779  progname, optarg);
780  ExitPostmaster(1);
781  }
782  break;
783  }
784 
785  case 'W':
786  SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
787  break;
788 
789  case 'c':
790  case '-':
791  {
792  char *name,
793  *value;
794 
795  ParseLongOption(optarg, &name, &value);
796  if (!value)
797  {
798  if (opt == '-')
799  ereport(ERROR,
800  (errcode(ERRCODE_SYNTAX_ERROR),
801  errmsg("--%s requires a value",
802  optarg)));
803  else
804  ereport(ERROR,
805  (errcode(ERRCODE_SYNTAX_ERROR),
806  errmsg("-c %s requires a value",
807  optarg)));
808  }
809 
811  free(name);
812  if (value)
813  free(value);
814  break;
815  }
816 
817  default:
818  write_stderr("Try \"%s --help\" for more information.\n",
819  progname);
820  ExitPostmaster(1);
821  }
822  }
823 
824  /*
825  * Postmaster accepts no non-option switch arguments.
826  */
827  if (optind < argc)
828  {
829  write_stderr("%s: invalid argument: \"%s\"\n",
830  progname, argv[optind]);
831  write_stderr("Try \"%s --help\" for more information.\n",
832  progname);
833  ExitPostmaster(1);
834  }
835 
836  /*
837  * Locate the proper configuration files and data directory, and read
838  * postgresql.conf for the first time.
839  */
840  if (!SelectConfigFiles(userDoption, progname))
841  ExitPostmaster(2);
842 
843  if (output_config_variable != NULL)
844  {
845  /*
846  * "-C guc" was specified, so print GUC's value and exit. No extra
847  * permission check is needed because the user is reading inside the
848  * data dir.
849  */
850  const char *config_val = GetConfigOption(output_config_variable,
851  false, false);
852 
853  puts(config_val ? config_val : "");
854  ExitPostmaster(0);
855  }
856 
857  /* Verify that DataDir looks reasonable */
858  checkDataDir();
859 
860  /* And switch working directory into it */
861  ChangeToDataDir();
862 
863  /*
864  * Check for invalid combinations of GUC settings.
865  */
867  {
868  write_stderr("%s: superuser_reserved_connections must be less than max_connections\n", progname);
869  ExitPostmaster(1);
870  }
872  {
873  write_stderr("%s: max_wal_senders must be less than max_connections\n", progname);
874  ExitPostmaster(1);
875  }
877  ereport(ERROR,
878  (errmsg("WAL archival cannot be enabled when wal_level is \"minimal\"")));
880  ereport(ERROR,
881  (errmsg("WAL streaming (max_wal_senders > 0) requires wal_level \"replica\" or \"logical\"")));
882 
883  /*
884  * Other one-time internal sanity checks can go here, if they are fast.
885  * (Put any slow processing further down, after postmaster.pid creation.)
886  */
887  if (!CheckDateTokenTables())
888  {
889  write_stderr("%s: invalid datetoken tables, please fix\n", progname);
890  ExitPostmaster(1);
891  }
892 
893  /*
894  * Now that we are done processing the postmaster arguments, reset
895  * getopt(3) library so that it will work correctly in subprocesses.
896  */
897  optind = 1;
898 #ifdef HAVE_INT_OPTRESET
899  optreset = 1; /* some systems need this too */
900 #endif
901 
902  /* For debugging: display postmaster environment */
903  {
904  extern char **environ;
905  char **p;
906 
907  ereport(DEBUG3,
908  (errmsg_internal("%s: PostmasterMain: initial environment dump:",
909  progname)));
910  ereport(DEBUG3,
911  (errmsg_internal("-----------------------------------------")));
912  for (p = environ; *p; ++p)
913  ereport(DEBUG3,
914  (errmsg_internal("\t%s", *p)));
915  ereport(DEBUG3,
916  (errmsg_internal("-----------------------------------------")));
917  }
918 
919  /*
920  * Create lockfile for data directory.
921  *
922  * We want to do this before we try to grab the input sockets, because the
923  * data directory interlock is more reliable than the socket-file
924  * interlock (thanks to whoever decided to put socket files in /tmp :-().
925  * For the same reason, it's best to grab the TCP socket(s) before the
926  * Unix socket(s).
927  *
928  * Also note that this internally sets up the on_proc_exit function that
929  * is responsible for removing both data directory and socket lockfiles;
930  * so it must happen before opening sockets so that at exit, the socket
931  * lockfiles go away after CloseServerPorts runs.
932  */
933  CreateDataDirLockFile(true);
934 
935  /*
936  * Initialize SSL library, if specified.
937  */
938 #ifdef USE_SSL
939  if (EnableSSL)
940  {
941  (void) secure_initialize(true);
942  LoadedSSL = true;
943  }
944 #endif
945 
946  /*
947  * Register the apply launcher. Since it registers a background worker,
948  * it needs to be called before InitializeMaxBackends(), and it's probably
949  * a good idea to call it before any modules had chance to take the
950  * background worker slots.
951  */
953 
954  /*
955  * process any libraries that should be preloaded at postmaster start
956  */
958 
959  /*
960  * Now that loadable modules have had their chance to register background
961  * workers, calculate MaxBackends.
962  */
964 
965  /*
966  * Establish input sockets.
967  *
968  * First, mark them all closed, and set up an on_proc_exit function that's
969  * charged with closing the sockets again at postmaster shutdown.
970  */
971  for (i = 0; i < MAXLISTEN; i++)
973 
975 
976  if (ListenAddresses)
977  {
978  char *rawstring;
979  List *elemlist;
980  ListCell *l;
981  int success = 0;
982 
983  /* Need a modifiable copy of ListenAddresses */
984  rawstring = pstrdup(ListenAddresses);
985 
986  /* Parse string into list of hostnames */
987  if (!SplitIdentifierString(rawstring, ',', &elemlist))
988  {
989  /* syntax error in list */
990  ereport(FATAL,
991  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
992  errmsg("invalid list syntax in parameter \"%s\"",
993  "listen_addresses")));
994  }
995 
996  foreach(l, elemlist)
997  {
998  char *curhost = (char *) lfirst(l);
999 
1000  if (strcmp(curhost, "*") == 0)
1001  status = StreamServerPort(AF_UNSPEC, NULL,
1002  (unsigned short) PostPortNumber,
1003  NULL,
1005  else
1006  status = StreamServerPort(AF_UNSPEC, curhost,
1007  (unsigned short) PostPortNumber,
1008  NULL,
1009  ListenSocket, MAXLISTEN);
1010 
1011  if (status == STATUS_OK)
1012  {
1013  success++;
1014  /* record the first successful host addr in lockfile */
1015  if (!listen_addr_saved)
1016  {
1018  listen_addr_saved = true;
1019  }
1020  }
1021  else
1022  ereport(WARNING,
1023  (errmsg("could not create listen socket for \"%s\"",
1024  curhost)));
1025  }
1026 
1027  if (!success && elemlist != NIL)
1028  ereport(FATAL,
1029  (errmsg("could not create any TCP/IP sockets")));
1030 
1031  list_free(elemlist);
1032  pfree(rawstring);
1033  }
1034 
1035 #ifdef USE_BONJOUR
1036  /* Register for Bonjour only if we opened TCP socket(s) */
1037  if (enable_bonjour && ListenSocket[0] != PGINVALID_SOCKET)
1038  {
1039  DNSServiceErrorType err;
1040 
1041  /*
1042  * We pass 0 for interface_index, which will result in registering on
1043  * all "applicable" interfaces. It's not entirely clear from the
1044  * DNS-SD docs whether this would be appropriate if we have bound to
1045  * just a subset of the available network interfaces.
1046  */
1047  err = DNSServiceRegister(&bonjour_sdref,
1048  0,
1049  0,
1050  bonjour_name,
1051  "_postgresql._tcp.",
1052  NULL,
1053  NULL,
1054  htons(PostPortNumber),
1055  0,
1056  NULL,
1057  NULL,
1058  NULL);
1059  if (err != kDNSServiceErr_NoError)
1060  elog(LOG, "DNSServiceRegister() failed: error code %ld",
1061  (long) err);
1062 
1063  /*
1064  * We don't bother to read the mDNS daemon's reply, and we expect that
1065  * it will automatically terminate our registration when the socket is
1066  * closed at postmaster termination. So there's nothing more to be
1067  * done here. However, the bonjour_sdref is kept around so that
1068  * forked children can close their copies of the socket.
1069  */
1070  }
1071 #endif
1072 
1073 #ifdef HAVE_UNIX_SOCKETS
1075  {
1076  char *rawstring;
1077  List *elemlist;
1078  ListCell *l;
1079  int success = 0;
1080 
1081  /* Need a modifiable copy of Unix_socket_directories */
1082  rawstring = pstrdup(Unix_socket_directories);
1083 
1084  /* Parse string into list of directories */
1085  if (!SplitDirectoriesString(rawstring, ',', &elemlist))
1086  {
1087  /* syntax error in list */
1088  ereport(FATAL,
1089  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1090  errmsg("invalid list syntax in parameter \"%s\"",
1091  "unix_socket_directories")));
1092  }
1093 
1094  foreach(l, elemlist)
1095  {
1096  char *socketdir = (char *) lfirst(l);
1097 
1098  status = StreamServerPort(AF_UNIX, NULL,
1099  (unsigned short) PostPortNumber,
1100  socketdir,
1101  ListenSocket, MAXLISTEN);
1102 
1103  if (status == STATUS_OK)
1104  {
1105  success++;
1106  /* record the first successful Unix socket in lockfile */
1107  if (success == 1)
1109  }
1110  else
1111  ereport(WARNING,
1112  (errmsg("could not create Unix-domain socket in directory \"%s\"",
1113  socketdir)));
1114  }
1115 
1116  if (!success && elemlist != NIL)
1117  ereport(FATAL,
1118  (errmsg("could not create any Unix-domain sockets")));
1119 
1120  list_free_deep(elemlist);
1121  pfree(rawstring);
1122  }
1123 #endif
1124 
1125  /*
1126  * check that we have some socket to listen on
1127  */
1128  if (ListenSocket[0] == PGINVALID_SOCKET)
1129  ereport(FATAL,
1130  (errmsg("no socket created for listening")));
1131 
1132  /*
1133  * If no valid TCP ports, write an empty line for listen address,
1134  * indicating the Unix socket must be used. Note that this line is not
1135  * added to the lock file until there is a socket backing it.
1136  */
1137  if (!listen_addr_saved)
1139 
1140  /*
1141  * Set up shared memory and semaphores.
1142  */
1144 
1145  /*
1146  * Estimate number of openable files. This must happen after setting up
1147  * semaphores, because on some platforms semaphores count as open files.
1148  */
1149  set_max_safe_fds();
1150 
1151  /*
1152  * Set reference point for stack-depth checking.
1153  */
1154  set_stack_base();
1155 
1156  /*
1157  * Initialize pipe (or process handle on Windows) that allows children to
1158  * wake up from sleep on postmaster death.
1159  */
1161 
1162 #ifdef WIN32
1163 
1164  /*
1165  * Initialize I/O completion port used to deliver list of dead children.
1166  */
1167  win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
1168  if (win32ChildQueue == NULL)
1169  ereport(FATAL,
1170  (errmsg("could not create I/O completion port for child queue")));
1171 #endif
1172 
1173  /*
1174  * Record postmaster options. We delay this till now to avoid recording
1175  * bogus options (eg, NBuffers too high for available memory).
1176  */
1177  if (!CreateOptsFile(argc, argv, my_exec_path))
1178  ExitPostmaster(1);
1179 
1180 #ifdef EXEC_BACKEND
1181  /* Write out nondefault GUC settings for child processes to use */
1182  write_nondefault_variables(PGC_POSTMASTER);
1183 #endif
1184 
1185  /*
1186  * Write the external PID file if requested
1187  */
1188  if (external_pid_file)
1189  {
1190  FILE *fpidfile = fopen(external_pid_file, "w");
1191 
1192  if (fpidfile)
1193  {
1194  fprintf(fpidfile, "%d\n", MyProcPid);
1195  fclose(fpidfile);
1196 
1197  /* Make PID file world readable */
1198  if (chmod(external_pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) != 0)
1199  write_stderr("%s: could not change permissions of external PID file \"%s\": %s\n",
1201  }
1202  else
1203  write_stderr("%s: could not write external PID file \"%s\": %s\n",
1205 
1207  }
1208 
1209  /*
1210  * Remove old temporary files. At this point there can be no other
1211  * Postgres processes running in this directory, so this should be safe.
1212  */
1214 
1215  /*
1216  * Forcibly remove the files signaling a standby promotion request.
1217  * Otherwise, the existence of those files triggers a promotion too early,
1218  * whether a user wants that or not.
1219  *
1220  * This removal of files is usually unnecessary because they can exist
1221  * only during a few moments during a standby promotion. However there is
1222  * a race condition: if pg_ctl promote is executed and creates the files
1223  * during a promotion, the files can stay around even after the server is
1224  * brought up to new master. Then, if new standby starts by using the
1225  * backup taken from that master, the files can exist at the server
1226  * startup and should be removed in order to avoid an unexpected
1227  * promotion.
1228  *
1229  * Note that promotion signal files need to be removed before the startup
1230  * process is invoked. Because, after that, they can be used by
1231  * postmaster's SIGUSR1 signal handler.
1232  */
1234 
1235  /*
1236  * If enabled, start up syslogger collection subprocess
1237  */
1239 
1240  /*
1241  * Reset whereToSendOutput from DestDebug (its starting state) to
1242  * DestNone. This stops ereport from sending log messages to stderr unless
1243  * Log_destination permits. We don't do this until the postmaster is
1244  * fully launched, since startup failures may as well be reported to
1245  * stderr.
1246  *
1247  * If we are in fact disabling logging to stderr, first emit a log message
1248  * saying so, to provide a breadcrumb trail for users who may not remember
1249  * that their logging is configured to go somewhere else.
1250  */
1252  ereport(LOG,
1253  (errmsg("ending log output to stderr"),
1254  errhint("Future log output will go to log destination \"%s\".",
1256 
1258 
1259  /*
1260  * Initialize stats collection subsystem (this does NOT start the
1261  * collector process!)
1262  */
1263  pgstat_init();
1264 
1265  /*
1266  * Initialize the autovacuum subsystem (again, no process start yet)
1267  */
1268  autovac_init();
1269 
1270  /*
1271  * Load configuration files for client authentication.
1272  */
1273  if (!load_hba())
1274  {
1275  /*
1276  * It makes no sense to continue if we fail to load the HBA file,
1277  * since there is no way to connect to the database in this case.
1278  */
1279  ereport(FATAL,
1280  (errmsg("could not load pg_hba.conf")));
1281  }
1282  if (!load_ident())
1283  {
1284  /*
1285  * We can start up without the IDENT file, although it means that you
1286  * cannot log in using any of the authentication methods that need a
1287  * user name mapping. load_ident() already logged the details of error
1288  * to the log.
1289  */
1290  }
1291 
1292 #ifdef HAVE_PTHREAD_IS_THREADED_NP
1293 
1294  /*
1295  * On macOS, libintl replaces setlocale() with a version that calls
1296  * CFLocaleCopyCurrent() when its second argument is "" and every relevant
1297  * environment variable is unset or empty. CFLocaleCopyCurrent() makes
1298  * the process multithreaded. The postmaster calls sigprocmask() and
1299  * calls fork() without an immediate exec(), both of which have undefined
1300  * behavior in a multithreaded program. A multithreaded postmaster is the
1301  * normal case on Windows, which offers neither fork() nor sigprocmask().
1302  */
1303  if (pthread_is_threaded_np() != 0)
1304  ereport(FATAL,
1305  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1306  errmsg("postmaster became multithreaded during startup"),
1307  errhint("Set the LC_ALL environment variable to a valid locale.")));
1308 #endif
1309 
1310  /*
1311  * Remember postmaster startup time
1312  */
1314 #ifndef HAVE_STRONG_RANDOM
1315  /* RandomCancelKey wants its own copy */
1317 #endif
1318 
1319  /*
1320  * We're ready to rock and roll...
1321  */
1323  Assert(StartupPID != 0);
1325  pmState = PM_STARTUP;
1326 
1327  /* Some workers may be scheduled to start now */
1329 
1330  status = ServerLoop();
1331 
1332  /*
1333  * ServerLoop probably shouldn't ever return, but if it does, close down.
1334  */
1335  ExitPostmaster(status != STATUS_OK);
1336 
1337  abort(); /* not reached */
1338 }
pg_stack_base_t set_stack_base(void)
Definition: postgres.c:3043
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_superuser)
Definition: guc.c:6653
int secure_initialize(bool isServerStart)
Definition: be-secure.c:73
#define NIL
Definition: pg_list.h:69
bool IsPostmasterEnvironment
Definition: globals.c:99
bool EnableSSL
Definition: postmaster.c:233
static struct @76 value
#define SIGUSR1
Definition: win32.h:211
static StartupStatusEnum StartupStatus
Definition: postmaster.c:266
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:105
static void unlink_external_pid_file(int status, Datum arg)
Definition: postmaster.c:1381
int MyProcPid
Definition: globals.c:38
int errhint(const char *fmt,...)
Definition: elog.c:987
#define StartupDataBase()
Definition: postmaster.c:540
#define LOCK_FILE_LINE_LISTEN_ADDR
Definition: miscadmin.h:451
#define DEBUG3
Definition: elog.h:23
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1569
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:292
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1149
int wal_level
Definition: xlog.c:103
char * pstrdup(const char *in)
Definition: mcxt.c:1165
static void dummy_handler(SIGNAL_ARGS)
Definition: postmaster.c:5104
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:9327
pg_time_t MyStartTime
Definition: globals.c:39
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3220
#define SIGTTIN
Definition: win32.h:207
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define write_stderr(str)
Definition: parallel.c:182
static bool CreateOptsFile(int argc, char *argv[], char *fullprogname)
Definition: postmaster.c:5395
bool CheckDateTokenTables(void)
Definition: datetime.c:4464
int errcode(int sqlerrcode)
Definition: elog.c:575
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3262
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
int SysLogger_Start(void)
Definition: syslogger.c:511
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3191
#define LOG
Definition: elog.h:26
const char * progname
Definition: pg_standby.c:37
void list_free_deep(List *list)
Definition: list.c:1147
char * Unix_socket_directories
Definition: postmaster.c:197
bool IsBinaryUpgrade
Definition: globals.c:101
#define SIGQUIT
Definition: win32.h:197
int getopt(int nargc, char *const *nargv, const char *ostr)
Definition: getopt.c:72
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
bool load_ident(void)
Definition: hba.c:2727
void autovac_init(void)
Definition: autovacuum.c:2969
void pqinitmask(void)
Definition: pqsignal.c:41
static void CloseServerPorts(int status, Datum arg)
Definition: postmaster.c:1345
static void InitPostmasterDeathWatchHandle(void)
Definition: postmaster.c:6245
bool SplitDirectoriesString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3254
static void checkDataDir(void)
Definition: postmaster.c:1444
void pfree(void *pointer)
Definition: mcxt.c:992
#define SIG_IGN
Definition: win32.h:193
int optind
Definition: getopt.c:51
#define ERROR
Definition: elog.h:43
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1073
static pid_t StartupPID
Definition: postmaster.c:247
int PostPortNumber
Definition: postmaster.c:194
int ReservedBackends
Definition: postmaster.c:211
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:4903
#define FATAL
Definition: elog.h:52
char * external_pid_file
Definition: guc.c:467
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:145
#define S_IRGRP
Definition: win32.h:477
#define LOCK_FILE_LINE_SOCKET_DIR
Definition: miscadmin.h:450
static bool success
Definition: pg_basebackup.c:99
Definition: dest.h:88
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6629
bool load_hba(void)
Definition: hba.c:1945
char * bonjour_name
Definition: postmaster.c:243
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3129
int XLogArchiveMode
Definition: xlog.c:93
static pid_t SysLoggerPID
Definition: postmaster.c:255
#define S_IROTH
Definition: win32.h:481
void ChangeToDataDir(void)
Definition: miscinit.c:115
int opterr
Definition: getopt.c:50
static void getInstallationPaths(const char *argv0)
Definition: postmaster.c:1393
char * Log_destination_string
Definition: elog.c:107
char * ListenAddresses
Definition: postmaster.c:200
int StreamServerPort(int family, char *hostName, unsigned short portNumber, char *unixSocketDir, pgsocket ListenSocket[], int MaxListen)
Definition: pqcomm.c:311
#define ereport(elevel, rest)
Definition: elog.h:122
#define STATUS_OK
Definition: c.h:971
MemoryContext TopMemoryContext
Definition: mcxt.c:43
static void pmdie(SIGNAL_ARGS)
Definition: postmaster.c:2559
static void SIGHUP_handler(SIGNAL_ARGS)
Definition: postmaster.c:2486
bool enable_bonjour
Definition: postmaster.c:242
void RemovePromoteSignalFiles(void)
Definition: xlog.c:11948
int max_wal_senders
Definition: walsender.c:112
pid_t PostmasterPid
Definition: globals.c:86
#define WARNING
Definition: elog.h:40
char my_exec_path[MAXPGPATH]
Definition: globals.c:63
sigset_t BlockSig
Definition: pqsignal.c:22
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:215
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:440
static PMState pmState
Definition: postmaster.c:338
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:4646
void ApplyLauncherRegister(void)
Definition: launcher.c:485
#define PGINVALID_SOCKET
Definition: port.h:24
int MaxConnections
Definition: globals.c:123
TimestampTz PgStartTime
Definition: timestamp.c:48
#define SIGPIPE
Definition: win32.h:201
#define S_IRWXO
Definition: win32.h:484
#define SIGHUP
Definition: win32.h:196
#define LOG_DESTINATION_STDERR
Definition: elog.h:395
static void reset_shared(int port)
Definition: postmaster.c:2468
static bool Reinit
Definition: postmaster.c:229
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:168
#define free(a)
Definition: header.h:60
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
#define NULL
Definition: c.h:226
static char ExtraOptions[MAXPGPATH]
Definition: postmaster.c:220
static int ServerLoop(void)
Definition: postmaster.c:1638
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
void RemovePgTempFiles(void)
Definition: fd.c:2655
static void reaper(SIGNAL_ARGS)
Definition: postmaster.c:2729
void InitializeMaxBackends(void)
Definition: postinit.c:495
const char * name
Definition: encode.c:521
#define S_IRWXG
Definition: win32.h:480
#define SIGTTOU
Definition: win32.h:208
static const char * userDoption
Definition: postgres.c:159
void set_max_safe_fds(void)
Definition: fd.c:844
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * optarg
Definition: getopt.c:53
void list_free(List *list)
Definition: list.c:1133
int i
const char * strerror(int errnum)
Definition: strerror.c:19
static void sigusr1_handler(SIGNAL_ARGS)
Definition: postmaster.c:4936
void pgstat_init(void)
Definition: pgstat.c:320
void srandom(unsigned int seed)
Definition: srandom.c:22
int Log_destination
Definition: elog.c:106
static void maybe_start_bgworker(void)
Definition: postmaster.c:5685
char ** environ
#define elog
Definition: elog.h:219
CommandDest whereToSendOutput
Definition: postgres.c:86
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:222
#define SIGCHLD
Definition: win32.h:206
static int SendStop
Definition: postmaster.c:230
void process_shared_preload_libraries(void)
Definition: miscinit.c:1465
Definition: pg_list.h:45
#define MAXLISTEN
Definition: postmaster.c:214
#define SIGALRM
Definition: win32.h:202
static struct timeval random_start_time
Definition: postmaster.c:370
MemoryContext PostmasterContext
Definition: mcxt.c:45
#define SIGUSR2
Definition: win32.h:212
void InitializeGUCOptions(void)
Definition: guc.c:4424
bool PostmasterMarkPIDForWorkerNotify ( int  )

Definition at line 5781 of file postmaster.c.

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

Referenced by BackgroundWorkerStateChange().

5782 {
5783  dlist_iter iter;
5784  Backend *bp;
5785 
5786  dlist_foreach(iter, &BackendList)
5787  {
5788  bp = dlist_container(Backend, elem, iter.cur);
5789  if (bp->pid == pid)
5790  {
5791  bp->bgworker_notify = true;
5792  return true;
5793  }
5794  }
5795  return false;
5796 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
bool bgworker_notify
Definition: postmaster.c:179
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static dlist_head BackendList
Definition: postmaster.c:183
dlist_node * cur
Definition: ilist.h:161
pid_t pid
Definition: postmaster.c:168

Variable Documentation

int AuthenticationTimeout

Definition at line 236 of file postmaster.c.

Referenced by BackendInitialize(), and PerformAuthentication().

char* bonjour_name

Definition at line 243 of file postmaster.c.

Referenced by PostmasterMain().

bool enable_bonjour

Definition at line 242 of file postmaster.c.

Referenced by PostmasterMain().

bool EnableSSL

Definition at line 233 of file postmaster.c.

Referenced by parse_hba_line(), PostmasterMain(), and SIGHUP_handler().

char* ListenAddresses

Definition at line 200 of file postmaster.c.

Referenced by PostmasterMain().

bool Log_connections

Definition at line 239 of file postmaster.c.

Referenced by BackendInitialize(), and PerformAuthentication().

bool log_hostname

Definition at line 238 of file postmaster.c.

Referenced by BackendInitialize().

int postmaster_alive_fds[2]
int PostPortNumber

Definition at line 194 of file postmaster.c.

Referenced by CreateLockFile(), PostmasterMain(), and PostmasterStateMachine().

int PreAuthDelay

Definition at line 235 of file postmaster.c.

Referenced by BackendInitialize().

const char* progname

Definition at line 37 of file pg_standby.c.

Referenced by _check_database_version(), _connectDB(), AuxiliaryProcessMain(), BackendRun(), BaseBackup(), CheckCopyStreamStop(), checkDataDir(), CheckServerVersionForStreaming(), cleanup_directories_atexit(), CleanupPriorWALFiles(), close_destination_dir(), close_walfile(), connectDatabase(), ConnectDatabase(), CopyStreamPoll(), CopyStreamReceive(), CreateReplicationSlot(), CustomizableCleanupPriorWALFiles(), CustomizableInitialize(), dir_close(), dir_finish(), dir_open_for_write(), doConnect(), DropReplicationSlot(), escape_quotes(), FindStreamingStart(), GenerateRecoveryConf(), get_destination_dir(), get_opts(), get_progname(), GetConnection(), HandleCopyStream(), HandleEndOfCopyStream(), init_parallel_dump_utils(), Initialize(), LogStreamerMain(), main(), mark_file_as_archived(), open_walfile(), OutputFsync(), parse_max_rate(), PostgresMain(), PostmasterMain(), prepareToTerminate(), process_postgres_switches(), ProcessKeepaliveMsg(), ProcessXLogDataMsg(), reached_end_position(), ReadEndOfStreamingResult(), ReceiveAndUnpackTarFile(), ReceiveTarFile(), ReceiveXlogStream(), RunIdentifySystem(), sendFeedback(), set_dump_section(), SetWALFileNameForCleanup(), sigTermHandler(), StartLogStreamer(), stop_streaming(), StreamLog(), StreamLogicalLog(), syncTargetDirectory(), tablespace_list_append(), tar_finish(), usage(), verify_dir_is_empty_or_create(), vwrite_msg(), walkdir(), WriteRecoveryConf(), writeTarData(), and writeTimeLineHistoryFile().

int ReservedBackends

Definition at line 211 of file postmaster.c.

Referenced by InitPostgres(), and PostmasterMain().

bool restart_after_crash

Definition at line 244 of file postmaster.c.

Referenced by PostmasterStateMachine().

char* Unix_socket_directories

Definition at line 197 of file postmaster.c.

Referenced by PostmasterMain().

char* Unix_socket_group

Definition at line 103 of file pqcomm.c.

int Unix_socket_permissions

Definition at line 102 of file pqcomm.c.

Referenced by show_unix_socket_permissions().