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 2451 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().

2452 {
2453  int i;
2454 
2455 #ifndef WIN32
2456 
2457  /*
2458  * Close the write end of postmaster death watch pipe. It's important to
2459  * do this as early as possible, so that if postmaster dies, others won't
2460  * think that it's still running because we're holding the pipe open.
2461  */
2463  ereport(FATAL,
2465  errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
2467 #endif
2468 
2469  /* Close the listen sockets */
2470  for (i = 0; i < MAXLISTEN; i++)
2471  {
2472  if (ListenSocket[i] != PGINVALID_SOCKET)
2473  {
2476  }
2477  }
2478 
2479  /* If using syslogger, close the read side of the pipe */
2480  if (!am_syslogger)
2481  {
2482 #ifndef WIN32
2483  if (syslogPipe[0] >= 0)
2484  close(syslogPipe[0]);
2485  syslogPipe[0] = -1;
2486 #else
2487  if (syslogPipe[0])
2488  CloseHandle(syslogPipe[0]);
2489  syslogPipe[0] = 0;
2490 #endif
2491  }
2492 
2493 #ifdef USE_BONJOUR
2494  /* If using Bonjour, close the connection to the mDNS daemon */
2495  if (bonjour_sdref)
2496  close(DNSServiceRefSockFD(bonjour_sdref));
2497 #endif
2498 }
void StreamClose(pgsocket sock)
Definition: pqcomm.c:844
#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:562
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:12
#define MAXLISTEN
Definition: postmaster.c:214
int syslogPipe[2]
Definition: syslogger.c:112
int GetNumShmemAttachedBgworkers ( void  )
int MaxLivePostmasterChildren ( void  )

Definition at line 5530 of file postmaster.c.

References autovacuum_max_workers, max_worker_processes, and MaxConnections.

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

5531 {
5532  return 2 * (MaxConnections + autovacuum_max_workers + 1 +
5534 }
int MaxConnections
Definition: globals.c:123
int autovacuum_max_workers
Definition: autovacuum.c:115
int max_worker_processes
Definition: globals.c:124
void PostmasterMain ( int  argc,
char *  argv[] 
)

Definition at line 572 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(), errcode_for_file_access(), 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(), 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, MyStartTime, name, NIL, on_proc_exit(), optarg, opterr, optind, ParseLongOption(), pfree(), pg_hton16, PG_SETMASK, PGC_POSTMASTER, PGC_S_ARGV, PGINVALID_SOCKET, PgStartTime, pgstat_init(), PM_STARTUP, PM_STATUS_STARTING, pmdie(), pmState, PostmasterContext, PostmasterPid, PostPortNumber, pqinitmask(), pqsignal(), pqsignal_no_restart(), 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().

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

Definition at line 5924 of file postmaster.c.

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

Referenced by BackgroundWorkerStateChange().

5925 {
5926  dlist_iter iter;
5927  Backend *bp;
5928 
5929  dlist_foreach(iter, &BackendList)
5930  {
5931  bp = dlist_container(Backend, elem, iter.cur);
5932  if (bp->pid == pid)
5933  {
5934  bp->bgworker_notify = true;
5935  return true;
5936  }
5937  }
5938  return false;
5939 }
#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(), _CloseArchive(), _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(), RetrieveWalSegSize(), RunIdentifySystem(), sendFeedback(), set_dump_section(), SetWALFileNameForCleanup(), SetWALSegSize(), 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 122 of file pqcomm.c.

int Unix_socket_permissions

Definition at line 121 of file pqcomm.c.

Referenced by show_unix_socket_permissions().