PostgreSQL Source Code git master
postmaster.h File Reference
#include "lib/ilist.h"
#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.

Data Structures

struct  PMChild
 

Macros

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

Typedefs

typedef enum DispatchOption DispatchOption
 

Enumerations

enum  DispatchOption {
  DISPATCH_CHECK , DISPATCH_BOOT , DISPATCH_FORKCHILD , DISPATCH_DESCRIBE_CONFIG ,
  DISPATCH_SINGLE , DISPATCH_POSTMASTER
}
 

Functions

pg_noreturn void PostmasterMain (int argc, char *argv[])
 
void ClosePostmasterPorts (bool am_syslogger)
 
void InitProcessGlobals (void)
 
int MaxLivePostmasterChildren (void)
 
bool PostmasterMarkPIDForWorkerNotify (int)
 
pid_t postmaster_child_launch (BackendType child_type, int child_slot, void *startup_data, size_t startup_data_len, struct ClientSocket *client_sock)
 
const char * PostmasterChildName (BackendType child_type)
 
void InitPostmasterChildSlots (void)
 
PMChildAssignPostmasterChildSlot (BackendType btype)
 
PMChildAllocDeadEndChild (void)
 
bool ReleasePostmasterChildSlot (PMChild *pmchild)
 
PMChildFindPostmasterChildByPid (int pid)
 
DispatchOption parse_dispatch_option (const char *name)
 

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_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 redirection_done
 
PGDLLIMPORT bool LoadedSSL
 
PGDLLIMPORT struct ClientSocketMyClientSocket
 
PGDLLIMPORT dlist_head ActiveChildList
 

Macro Definition Documentation

◆ POSTMASTER_FD_OWN

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

Definition at line 84 of file postmaster.h.

◆ POSTMASTER_FD_WATCH

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

Definition at line 83 of file postmaster.h.

Typedef Documentation

◆ DispatchOption

Enumeration Type Documentation

◆ DispatchOption

Enumerator
DISPATCH_CHECK 
DISPATCH_BOOT 
DISPATCH_FORKCHILD 
DISPATCH_DESCRIBE_CONFIG 
DISPATCH_SINGLE 
DISPATCH_POSTMASTER 

Definition at line 132 of file postmaster.h.

134{
140 DISPATCH_POSTMASTER, /* must be last */
@ DISPATCH_SINGLE
Definition: postmaster.h:138
@ DISPATCH_DESCRIBE_CONFIG
Definition: postmaster.h:137
@ DISPATCH_BOOT
Definition: postmaster.h:135
@ DISPATCH_CHECK
Definition: postmaster.h:134
@ DISPATCH_FORKCHILD
Definition: postmaster.h:136
@ DISPATCH_POSTMASTER
Definition: postmaster.h:139

Function Documentation

◆ AllocDeadEndChild()

PMChild * AllocDeadEndChild ( void  )

Definition at line 224 of file pmchild.c.

225{
226 PMChild *pmchild;
227
228 elog(DEBUG2, "allocating dead-end child");
229
230 pmchild = (PMChild *) palloc_extended(sizeof(PMChild), MCXT_ALLOC_NO_OOM);
231 if (pmchild)
232 {
233 pmchild->pid = 0;
234 pmchild->child_slot = 0;
236 pmchild->rw = NULL;
237 pmchild->bgworker_notify = false;
238
240 }
241
242 return pmchild;
243}
#define DEBUG2
Definition: elog.h:29
#define elog(elevel,...)
Definition: elog.h:226
#define MCXT_ALLOC_NO_OOM
Definition: fe_memutils.h:29
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:347
void * palloc_extended(Size size, int flags)
Definition: mcxt.c:1417
@ B_DEAD_END_BACKEND
Definition: miscadmin.h:343
dlist_head ActiveChildList
Definition: pmchild.c:60
struct RegisteredBgWorker * rw
Definition: postmaster.h:45
bool bgworker_notify
Definition: postmaster.h:46
BackendType bkend_type
Definition: postmaster.h:44
dlist_node elem
Definition: postmaster.h:47
pid_t pid
Definition: postmaster.h:42
int child_slot
Definition: postmaster.h:43

References ActiveChildList, B_DEAD_END_BACKEND, PMChild::bgworker_notify, PMChild::bkend_type, PMChild::child_slot, DEBUG2, dlist_push_head(), PMChild::elem, elog, MCXT_ALLOC_NO_OOM, palloc_extended(), PMChild::pid, and PMChild::rw.

Referenced by BackendStartup().

◆ AssignPostmasterChildSlot()

PMChild * AssignPostmasterChildSlot ( BackendType  btype)

Definition at line 178 of file pmchild.c.

179{
180 dlist_head *freelist;
181 PMChild *pmchild;
182
183 if (pmchild_pools[btype].size == 0)
184 elog(ERROR, "cannot allocate a PMChild slot for backend type %d", btype);
185
186 freelist = &pmchild_pools[btype].freelist;
187 if (dlist_is_empty(freelist))
188 return NULL;
189
190 pmchild = dlist_container(PMChild, elem, dlist_pop_head_node(freelist));
191 pmchild->pid = 0;
192 pmchild->bkend_type = btype;
193 pmchild->rw = NULL;
194 pmchild->bgworker_notify = true;
195
196 /*
197 * pmchild->child_slot for each entry was initialized when the array of
198 * slots was allocated. Sanity check it.
199 */
200 if (!(pmchild->child_slot >= pmchild_pools[btype].first_slotno &&
201 pmchild->child_slot < pmchild_pools[btype].first_slotno + pmchild_pools[btype].size))
202 {
203 elog(ERROR, "pmchild freelist for backend type %d is corrupt",
204 pmchild->bkend_type);
205 }
206
208
209 /* Update the status in the shared memory array */
211
212 elog(DEBUG2, "assigned pm child slot %d for %s",
213 pmchild->child_slot, PostmasterChildName(btype));
214
215 return pmchild;
216}
#define ERROR
Definition: elog.h:39
static dlist_node * dlist_pop_head_node(dlist_head *head)
Definition: ilist.h:450
static bool dlist_is_empty(const dlist_head *head)
Definition: ilist.h:336
#define dlist_container(type, membername, ptr)
Definition: ilist.h:593
const char * PostmasterChildName(BackendType child_type)
static PMChildPool pmchild_pools[BACKEND_NUM_TYPES]
Definition: pmchild.c:54
void MarkPostmasterChildSlotAssigned(int slot)
Definition: pmsignal.c:230
int first_slotno
Definition: pmchild.c:50
int size
Definition: pmchild.c:48
dlist_head freelist
Definition: pmchild.c:51

References ActiveChildList, PMChild::bgworker_notify, PMChild::bkend_type, PMChild::child_slot, DEBUG2, dlist_container, dlist_is_empty(), dlist_pop_head_node(), dlist_push_head(), PMChild::elem, elog, ERROR, PMChildPool::first_slotno, PMChildPool::freelist, MarkPostmasterChildSlotAssigned(), PMChild::pid, pmchild_pools, PostmasterChildName(), PMChild::rw, and PMChildPool::size.

Referenced by BackendStartup(), StartBackgroundWorker(), StartChildProcess(), and StartSysLogger().

◆ ClosePostmasterPorts()

void ClosePostmasterPorts ( bool  am_syslogger)

Definition at line 1866 of file postmaster.c.

1867{
1868 /* Release resources held by the postmaster's WaitEventSet. */
1869 if (pm_wait_set)
1870 {
1872 pm_wait_set = NULL;
1873 }
1874
1875#ifndef WIN32
1876
1877 /*
1878 * Close the write end of postmaster death watch pipe. It's important to
1879 * do this as early as possible, so that if postmaster dies, others won't
1880 * think that it's still running because we're holding the pipe open.
1881 */
1883 ereport(FATAL,
1885 errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
1887 /* Notify fd.c that we released one pipe FD. */
1889#endif
1890
1891 /*
1892 * Close the postmaster's listen sockets. These aren't tracked by fd.c,
1893 * so we don't call ReleaseExternalFD() here.
1894 *
1895 * The listen sockets are marked as FD_CLOEXEC, so this isn't needed in
1896 * EXEC_BACKEND mode.
1897 */
1898#ifndef EXEC_BACKEND
1899 if (ListenSockets)
1900 {
1901 for (int i = 0; i < NumListenSockets; i++)
1902 {
1903 if (closesocket(ListenSockets[i]) != 0)
1904 elog(LOG, "could not close listen socket: %m");
1905 }
1907 }
1908 NumListenSockets = 0;
1909 ListenSockets = NULL;
1910#endif
1911
1912 /*
1913 * If using syslogger, close the read side of the pipe. We don't bother
1914 * tracking this in fd.c, either.
1915 */
1916 if (!am_syslogger)
1917 {
1918#ifndef WIN32
1919 if (syslogPipe[0] >= 0)
1920 close(syslogPipe[0]);
1921 syslogPipe[0] = -1;
1922#else
1923 if (syslogPipe[0])
1924 CloseHandle(syslogPipe[0]);
1925 syslogPipe[0] = 0;
1926#endif
1927 }
1928
1929#ifdef USE_BONJOUR
1930 /* If using Bonjour, close the connection to the mDNS daemon */
1931 if (bonjour_sdref)
1932 close(DNSServiceRefSockFD(bonjour_sdref));
1933#endif
1934}
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1170
int errcode_for_file_access(void)
Definition: elog.c:886
#define LOG
Definition: elog.h:31
#define FATAL
Definition: elog.h:41
#define ereport(elevel,...)
Definition: elog.h:150
void ReleaseExternalFD(void)
Definition: fd.c:1238
#define close(a)
Definition: win32.h:12
int i
Definition: isn.c:77
void pfree(void *pointer)
Definition: mcxt.c:1594
#define closesocket
Definition: port.h:398
static pgsocket * ListenSockets
Definition: postmaster.c:235
static int NumListenSockets
Definition: postmaster.c:234
int postmaster_alive_fds[2]
Definition: postmaster.c:483
static WaitEventSet * pm_wait_set
Definition: postmaster.c:399
#define POSTMASTER_FD_OWN
Definition: postmaster.h:84
int syslogPipe[2]
Definition: syslogger.c:114
void FreeWaitEventSetAfterFork(WaitEventSet *set)
Definition: waiteventset.c:524

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

◆ FindPostmasterChildByPid()

PMChild * FindPostmasterChildByPid ( int  pid)

Definition at line 290 of file pmchild.c.

291{
292 dlist_iter iter;
293
295 {
296 PMChild *bp = dlist_container(PMChild, elem, iter.cur);
297
298 if (bp->pid == pid)
299 return bp;
300 }
301 return NULL;
302}
#define dlist_foreach(iter, lhead)
Definition: ilist.h:623
dlist_node * cur
Definition: ilist.h:179

References ActiveChildList, dlist_iter::cur, dlist_container, dlist_foreach, and PMChild::pid.

Referenced by process_pm_child_exit().

◆ InitPostmasterChildSlots()

void InitPostmasterChildSlots ( void  )

Definition at line 97 of file pmchild.c.

98{
99 int slotno;
100 PMChild *slots;
101
102 /*
103 * We allow more connections here than we can have backends because some
104 * might still be authenticating; they might fail auth, or some existing
105 * backend might exit before the auth cycle is completed. The exact
106 * MaxConnections limit is enforced when a new backend tries to join the
107 * PGPROC array.
108 *
109 * WAL senders start out as regular backends, so they share the same pool.
110 */
112
116
117 /*
118 * There can be only one of each of these running at a time. They each
119 * get their own pool of just one entry.
120 */
131
132 /* The rest of the pmchild_pools are left at zero size */
133
134 /* Count the total number of slots */
136 for (int i = 0; i < BACKEND_NUM_TYPES; i++)
138
139 /* Allocate enough slots, and make sure Valgrind doesn't complain */
140 slots = palloc(num_pmchild_slots * sizeof(PMChild));
141#ifdef USE_VALGRIND
142 pmchild_array = slots;
143#endif
144
145 /* Initialize them */
146 slotno = 0;
147 for (int btype = 0; btype < BACKEND_NUM_TYPES; btype++)
148 {
149 pmchild_pools[btype].first_slotno = slotno + 1;
150 dlist_init(&pmchild_pools[btype].freelist);
151
152 for (int j = 0; j < pmchild_pools[btype].size; j++)
153 {
154 slots[slotno].pid = 0;
155 slots[slotno].child_slot = slotno + 1;
156 slots[slotno].bkend_type = B_INVALID;
157 slots[slotno].rw = NULL;
158 slots[slotno].bgworker_notify = false;
159 dlist_push_tail(&pmchild_pools[btype].freelist, &slots[slotno].elem);
160 slotno++;
161 }
162 }
163 Assert(slotno == num_pmchild_slots);
164
165 /* Initialize other structures */
167}
int autovacuum_worker_slots
Definition: autovacuum.c:118
int MaxConnections
Definition: globals.c:143
int max_worker_processes
Definition: globals.c:144
Assert(PointerIsAligned(start, uint64))
static void dlist_init(dlist_head *head)
Definition: ilist.h:314
static void dlist_push_tail(dlist_head *head, dlist_node *node)
Definition: ilist.h:364
int j
Definition: isn.c:78
void * palloc(Size size)
Definition: mcxt.c:1365
#define BACKEND_NUM_TYPES
Definition: miscadmin.h:377
@ B_WAL_SUMMARIZER
Definition: miscadmin.h:367
@ B_WAL_WRITER
Definition: miscadmin.h:368
@ B_WAL_RECEIVER
Definition: miscadmin.h:366
@ B_CHECKPOINTER
Definition: miscadmin.h:363
@ B_IO_WORKER
Definition: miscadmin.h:364
@ B_LOGGER
Definition: miscadmin.h:374
@ B_STARTUP
Definition: miscadmin.h:365
@ B_BG_WORKER
Definition: miscadmin.h:346
@ B_INVALID
Definition: miscadmin.h:339
@ B_BG_WRITER
Definition: miscadmin.h:362
@ B_BACKEND
Definition: miscadmin.h:342
@ B_ARCHIVER
Definition: miscadmin.h:361
@ B_AUTOVAC_LAUNCHER
Definition: miscadmin.h:344
@ B_SLOTSYNC_WORKER
Definition: miscadmin.h:348
@ B_AUTOVAC_WORKER
Definition: miscadmin.h:345
NON_EXEC_STATIC int num_pmchild_slots
Definition: pmchild.c:55
#define MAX_IO_WORKERS
Definition: proc.h:462
int max_wal_senders
Definition: walsender.c:129

References ActiveChildList, Assert(), autovacuum_worker_slots, B_ARCHIVER, B_AUTOVAC_LAUNCHER, B_AUTOVAC_WORKER, B_BACKEND, B_BG_WORKER, B_BG_WRITER, B_CHECKPOINTER, B_INVALID, B_IO_WORKER, B_LOGGER, B_SLOTSYNC_WORKER, B_STARTUP, B_WAL_RECEIVER, B_WAL_SUMMARIZER, B_WAL_WRITER, BACKEND_NUM_TYPES, PMChild::bgworker_notify, PMChild::bkend_type, PMChild::child_slot, dlist_init(), dlist_push_tail(), PMChildPool::first_slotno, i, j, MAX_IO_WORKERS, max_wal_senders, max_worker_processes, MaxConnections, num_pmchild_slots, palloc(), PMChild::pid, pmchild_pools, PMChild::rw, and PMChildPool::size.

Referenced by BootstrapModeMain(), PostgresSingleUserMain(), and PostmasterMain().

◆ InitProcessGlobals()

void InitProcessGlobals ( void  )

Definition at line 1943 of file postmaster.c.

1944{
1947
1948 /*
1949 * Set a different global seed in every process. We want something
1950 * unpredictable, so if possible, use high-quality random bits for the
1951 * seed. Otherwise, fall back to a seed based on timestamp and PID.
1952 */
1954 {
1955 uint64 rseed;
1956
1957 /*
1958 * Since PIDs and timestamps tend to change more frequently in their
1959 * least significant bits, shift the timestamp left to allow a larger
1960 * total number of seeds in a given time period. Since that would
1961 * leave only 20 bits of the timestamp that cycle every ~1 second,
1962 * also mix in some higher bits.
1963 */
1964 rseed = ((uint64) MyProcPid) ^
1965 ((uint64) MyStartTimestamp << 12) ^
1966 ((uint64) MyStartTimestamp >> 20);
1967
1969 }
1970
1971 /*
1972 * Also make sure that we've set a good seed for random(3). Use of that
1973 * is deprecated in core Postgres, but extensions might use it.
1974 */
1975#ifndef WIN32
1977#endif
1978}
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1645
pg_time_t timestamptz_to_time_t(TimestampTz t)
Definition: timestamp.c:1842
uint64_t uint64
Definition: c.h:542
#define unlikely(x)
Definition: c.h:407
int MyProcPid
Definition: globals.c:47
TimestampTz MyStartTimestamp
Definition: globals.c:49
pg_time_t MyStartTime
Definition: globals.c:48
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 81 of file pmchild.c.

82{
83 if (num_pmchild_slots == 0)
84 elog(ERROR, "PM child array not initialized yet");
85 return num_pmchild_slots;
86}

References elog, ERROR, and num_pmchild_slots.

Referenced by PMSignalShmemInit(), and PMSignalShmemSize().

◆ parse_dispatch_option()

DispatchOption parse_dispatch_option ( const char *  name)

Definition at line 244 of file main.c.

245{
246 for (int i = 0; i < lengthof(DispatchOptionNames); i++)
247 {
248 /*
249 * Unlike the other dispatch options, "forkchild" takes an argument,
250 * so we just look for the prefix for that one. For non-EXEC_BACKEND
251 * builds, we never want to return DISPATCH_FORKCHILD, so skip over it
252 * in that case.
253 */
254 if (i == DISPATCH_FORKCHILD)
255 {
256#ifdef EXEC_BACKEND
259 return DISPATCH_FORKCHILD;
260#endif
261 continue;
262 }
263
264 if (strcmp(DispatchOptionNames[i], name) == 0)
265 return (DispatchOption) i;
266 }
267
268 /* no match means this is a postmaster */
269 return DISPATCH_POSTMASTER;
270}
#define lengthof(array)
Definition: c.h:790
static const char *const DispatchOptionNames[]
Definition: main.c:48
DispatchOption
Definition: postmaster.h:133
const char * name

References DISPATCH_FORKCHILD, DISPATCH_POSTMASTER, DispatchOptionNames, i, lengthof, and name.

Referenced by BootstrapModeMain(), main(), PostmasterMain(), and process_postgres_switches().

◆ postmaster_child_launch()

pid_t postmaster_child_launch ( BackendType  child_type,
int  child_slot,
void *  startup_data,
size_t  startup_data_len,
struct ClientSocket client_sock 
)

Definition at line 207 of file launch_backend.c.

210{
211 pid_t pid;
212
214
215 /* Capture time Postmaster initiates process creation for logging */
216 if (IsExternalConnectionBackend(child_type))
217 ((BackendStartupData *) startup_data)->fork_started = GetCurrentTimestamp();
218
219#ifdef EXEC_BACKEND
220 pid = internal_forkexec(child_process_kinds[child_type].name, child_slot,
221 startup_data, startup_data_len, client_sock);
222 /* the child process will arrive in SubPostmasterMain */
223#else /* !EXEC_BACKEND */
224 pid = fork_process();
225 if (pid == 0) /* child */
226 {
227 /* Capture and transfer timings that may be needed for logging */
228 if (IsExternalConnectionBackend(child_type))
229 {
231 ((BackendStartupData *) startup_data)->socket_created;
233 ((BackendStartupData *) startup_data)->fork_started;
235 }
236
237 /* Close the postmaster's sockets */
238 ClosePostmasterPorts(child_type == B_LOGGER);
239
240 /* Detangle from postmaster */
242
243 /* Detach shared memory if not needed. */
244 if (!child_process_kinds[child_type].shmem_attach)
245 {
248 }
249
250 /*
251 * Enter the Main function with TopMemoryContext. The startup data is
252 * allocated in PostmasterContext, so we cannot release it here yet.
253 * The Main function will do it after it's done handling the startup
254 * data.
255 */
257
258 MyPMChildSlot = child_slot;
259 if (client_sock)
260 {
262 memcpy(MyClientSocket, client_sock, sizeof(ClientSocket));
263 }
264
265 /*
266 * Run the appropriate Main function
267 */
268 child_process_kinds[child_type].main_fn(startup_data, startup_data_len);
269 pg_unreachable(); /* main_fn never returns */
270 }
271#endif /* EXEC_BACKEND */
272 return pid;
273}
ConnectionTiming conn_timing
#define pg_unreachable()
Definition: c.h:336
void dsm_detach_all(void)
Definition: dsm.c:775
pid_t fork_process(void)
Definition: fork_process.c:33
struct ClientSocket * MyClientSocket
Definition: globals.c:50
int MyPMChildSlot
Definition: globals.c:54
bool IsUnderPostmaster
Definition: globals.c:120
bool IsPostmasterEnvironment
Definition: globals.c:119
static child_process_kind child_process_kinds[]
MemoryContext TopMemoryContext
Definition: mcxt.c:166
#define IsExternalConnectionBackend(backend_type)
Definition: miscadmin.h:405
void InitPostmasterChild(void)
Definition: miscinit.c:96
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:1866
TimestampTz socket_create
TimestampTz fork_start
TimestampTz fork_end
void(* main_fn)(const void *startup_data, size_t startup_data_len)
void PGSharedMemoryDetach(void)
Definition: sysv_shmem.c:970

References Assert(), B_LOGGER, child_process_kinds, ClosePostmasterPorts(), conn_timing, dsm_detach_all(), ConnectionTiming::fork_end, fork_process(), ConnectionTiming::fork_start, GetCurrentTimestamp(), InitPostmasterChild(), IsExternalConnectionBackend, IsPostmasterEnvironment, IsUnderPostmaster, child_process_kind::main_fn, MemoryContextSwitchTo(), MyClientSocket, MyPMChildSlot, name, palloc(), pg_unreachable, PGSharedMemoryDetach(), ConnectionTiming::socket_create, and TopMemoryContext.

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

◆ PostmasterChildName()

const char * PostmasterChildName ( BackendType  child_type)

Definition at line 189 of file launch_backend.c.

190{
191 return child_process_kinds[child_type].name;
192}

References child_process_kinds, and child_process_kind::name.

Referenced by AssignPostmasterChildSlot(), and StartChildProcess().

◆ PostmasterMain()

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

Definition at line 493 of file postmaster.c.

494{
495 int opt;
496 int status;
497 char *userDoption = NULL;
498 bool listen_addr_saved = false;
499 char *output_config_variable = NULL;
500
502
504
506
507 /*
508 * Start our win32 signal implementation
509 */
510#ifdef WIN32
512#endif
513
514 /*
515 * We should not be creating any files or directories before we check the
516 * data directory (see checkDataDir()), but just in case set the umask to
517 * the most restrictive (owner-only) permissions.
518 *
519 * checkDataDir() will reset the umask based on the data directory
520 * permissions.
521 */
522 umask(PG_MODE_MASK_OWNER);
523
524 /*
525 * By default, palloc() requests in the postmaster will be allocated in
526 * the PostmasterContext, which is space that can be recycled by backends.
527 * Allocated data that needs to be available to backends should be
528 * allocated in TopMemoryContext.
529 */
531 "Postmaster",
534
535 /* Initialize paths to installation files */
536 getInstallationPaths(argv[0]);
537
538 /*
539 * Set up signal handlers for the postmaster process.
540 *
541 * CAUTION: when changing this list, check for side-effects on the signal
542 * handling setup of child processes. See tcop/postgres.c,
543 * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/walwriter.c,
544 * postmaster/autovacuum.c, postmaster/pgarch.c, postmaster/syslogger.c,
545 * postmaster/bgworker.c and postmaster/checkpointer.c.
546 */
547 pqinitmask();
548 sigprocmask(SIG_SETMASK, &BlockSig, NULL);
549
554 pqsignal(SIGALRM, SIG_IGN); /* ignored */
555 pqsignal(SIGPIPE, SIG_IGN); /* ignored */
557 pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
559
560 /* This may configure SIGURG, depending on platform. */
563
564 /*
565 * No other place in Postgres should touch SIGTTIN/SIGTTOU handling. We
566 * ignore those signals in a postmaster environment, so that there is no
567 * risk of a child process freezing up due to writing to stderr. But for
568 * a standalone backend, their default handling is reasonable. Hence, all
569 * child processes should just allow the inherited settings to stand.
570 */
571#ifdef SIGTTIN
572 pqsignal(SIGTTIN, SIG_IGN); /* ignored */
573#endif
574#ifdef SIGTTOU
575 pqsignal(SIGTTOU, SIG_IGN); /* ignored */
576#endif
577
578 /* ignore SIGXFSZ, so that ulimit violations work like disk full */
579#ifdef SIGXFSZ
580 pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
581#endif
582
583 /* Begin accepting signals. */
584 sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
585
586 /*
587 * Options setup
588 */
590
591 opterr = 1;
592
593 /*
594 * Parse command-line options. CAUTION: keep this in sync with
595 * tcop/postgres.c (the option sets should not conflict) and with the
596 * common help() function in main/main.c.
597 */
598 while ((opt = getopt(argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:OPp:r:S:sTt:W:-:")) != -1)
599 {
600 switch (opt)
601 {
602 case 'B':
603 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
604 break;
605
606 case 'b':
607 /* Undocumented flag used for binary upgrades */
608 IsBinaryUpgrade = true;
609 break;
610
611 case 'C':
612 output_config_variable = strdup(optarg);
613 break;
614
615 case '-':
616
617 /*
618 * Error if the user misplaced a special must-be-first option
619 * for dispatching to a subprogram. parse_dispatch_option()
620 * returns DISPATCH_POSTMASTER if it doesn't find a match, so
621 * error for anything else.
622 */
625 (errcode(ERRCODE_SYNTAX_ERROR),
626 errmsg("--%s must be first argument", optarg)));
627
628 /* FALLTHROUGH */
629 case 'c':
630 {
631 char *name,
632 *value;
633
635 if (!value)
636 {
637 if (opt == '-')
639 (errcode(ERRCODE_SYNTAX_ERROR),
640 errmsg("--%s requires a value",
641 optarg)));
642 else
644 (errcode(ERRCODE_SYNTAX_ERROR),
645 errmsg("-c %s requires a value",
646 optarg)));
647 }
648
650 pfree(name);
651 pfree(value);
652 break;
653 }
654
655 case 'D':
656 userDoption = strdup(optarg);
657 break;
658
659 case 'd':
661 break;
662
663 case 'E':
664 SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
665 break;
666
667 case 'e':
668 SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
669 break;
670
671 case 'F':
672 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
673 break;
674
675 case 'f':
677 {
678 write_stderr("%s: invalid argument for option -f: \"%s\"\n",
681 }
682 break;
683
684 case 'h':
685 SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
686 break;
687
688 case 'i':
689 SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
690 break;
691
692 case 'j':
693 /* only used by interactive backend */
694 break;
695
696 case 'k':
697 SetConfigOption("unix_socket_directories", optarg, PGC_POSTMASTER, PGC_S_ARGV);
698 break;
699
700 case 'l':
702 break;
703
704 case 'N':
705 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
706 break;
707
708 case 'O':
709 SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
710 break;
711
712 case 'P':
713 SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
714 break;
715
716 case 'p':
718 break;
719
720 case 'r':
721 /* only used by single-user backend */
722 break;
723
724 case 'S':
726 break;
727
728 case 's':
729 SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
730 break;
731
732 case 'T':
733
734 /*
735 * This option used to be defined as sending SIGSTOP after a
736 * backend crash, but sending SIGABRT seems more useful.
737 */
738 SetConfigOption("send_abort_for_crash", "true", PGC_POSTMASTER, PGC_S_ARGV);
739 break;
740
741 case 't':
742 {
743 const char *tmp = get_stats_option_name(optarg);
744
745 if (tmp)
746 {
748 }
749 else
750 {
751 write_stderr("%s: invalid argument for option -t: \"%s\"\n",
754 }
755 break;
756 }
757
758 case 'W':
759 SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
760 break;
761
762 default:
763 write_stderr("Try \"%s --help\" for more information.\n",
764 progname);
766 }
767 }
768
769 /*
770 * Postmaster accepts no non-option switch arguments.
771 */
772 if (optind < argc)
773 {
774 write_stderr("%s: invalid argument: \"%s\"\n",
775 progname, argv[optind]);
776 write_stderr("Try \"%s --help\" for more information.\n",
777 progname);
779 }
780
781 /*
782 * Locate the proper configuration files and data directory, and read
783 * postgresql.conf for the first time.
784 */
787
788 if (output_config_variable != NULL)
789 {
790 /*
791 * If this is a runtime-computed GUC, it hasn't yet been initialized,
792 * and the present value is not useful. However, this is a convenient
793 * place to print the value for most GUCs because it is safe to run
794 * postmaster startup to this point even if the server is already
795 * running. For the handful of runtime-computed GUCs that we cannot
796 * provide meaningful values for yet, we wait until later in
797 * postmaster startup to print the value. We won't be able to use -C
798 * on running servers for those GUCs, but using this option now would
799 * lead to incorrect results for them.
800 */
801 int flags = GetConfigOptionFlags(output_config_variable, true);
802
803 if ((flags & GUC_RUNTIME_COMPUTED) == 0)
804 {
805 /*
806 * "-C guc" was specified, so print GUC's value and exit. No
807 * extra permission check is needed because the user is reading
808 * inside the data dir.
809 */
810 const char *config_val = GetConfigOption(output_config_variable,
811 false, false);
812
813 puts(config_val ? config_val : "");
815 }
816
817 /*
818 * A runtime-computed GUC will be printed later on. As we initialize
819 * a server startup sequence, silence any log messages that may show
820 * up in the output generated. FATAL and more severe messages are
821 * useful to show, even if one would only expect at least PANIC. LOG
822 * entries are hidden.
823 */
824 SetConfigOption("log_min_messages", "FATAL", PGC_SUSET,
826 }
827
828 /* Verify that DataDir looks reasonable */
829 checkDataDir();
830
831 /* Check that pg_control exists */
833
834 /* And switch working directory into it */
836
837 /*
838 * Check for invalid combinations of GUC settings.
839 */
841 {
842 write_stderr("%s: \"superuser_reserved_connections\" (%d) plus \"reserved_connections\" (%d) must be less than \"max_connections\" (%d)\n",
843 progname,
847 }
850 (errmsg("WAL archival cannot be enabled when \"wal_level\" is \"minimal\"")));
853 (errmsg("WAL streaming (\"max_wal_senders\" > 0) requires \"wal_level\" to be \"replica\" or \"logical\"")));
856 (errmsg("WAL cannot be summarized when \"wal_level\" is \"minimal\"")));
859 (errmsg("replication slot synchronization (\"sync_replication_slots\" = on) requires \"wal_level\" >= \"logical\"")));
860
861 /*
862 * Other one-time internal sanity checks can go here, if they are fast.
863 * (Put any slow processing further down, after postmaster.pid creation.)
864 */
866 {
867 write_stderr("%s: invalid datetoken tables, please fix\n", progname);
869 }
870
871 /*
872 * Now that we are done processing the postmaster arguments, reset
873 * getopt(3) library so that it will work correctly in subprocesses.
874 */
875 optind = 1;
876#ifdef HAVE_INT_OPTRESET
877 optreset = 1; /* some systems need this too */
878#endif
879
880 /* For debugging: display postmaster environment */
882 {
883#if !defined(WIN32)
884 extern char **environ;
885#endif
886 char **p;
888
889 initStringInfo(&si);
890
891 appendStringInfoString(&si, "initial environment dump:");
892 for (p = environ; *p; ++p)
893 appendStringInfo(&si, "\n%s", *p);
894
896 pfree(si.data);
897 }
898
899 /*
900 * Create lockfile for data directory.
901 *
902 * We want to do this before we try to grab the input sockets, because the
903 * data directory interlock is more reliable than the socket-file
904 * interlock (thanks to whoever decided to put socket files in /tmp :-().
905 * For the same reason, it's best to grab the TCP socket(s) before the
906 * Unix socket(s).
907 *
908 * Also note that this internally sets up the on_proc_exit function that
909 * is responsible for removing both data directory and socket lockfiles;
910 * so it must happen before opening sockets so that at exit, the socket
911 * lockfiles go away after CloseServerPorts runs.
912 */
914
915 /*
916 * Read the control file (for error checking and config info).
917 *
918 * Since we verify the control file's CRC, this has a useful side effect
919 * on machines where we need a run-time test for CRC support instructions.
920 * The postmaster will do the test once at startup, and then its child
921 * processes will inherit the correct function pointer and not need to
922 * repeat the test.
923 */
925
926 /*
927 * Register the apply launcher. It's probably a good idea to call this
928 * before any modules had a chance to take the background worker slots.
929 */
931
932 /*
933 * process any libraries that should be preloaded at postmaster start
934 */
936
937 /*
938 * Initialize SSL library, if specified.
939 */
940#ifdef USE_SSL
941 if (EnableSSL)
942 {
943 (void) secure_initialize(true);
944 LoadedSSL = true;
945 }
946#endif
947
948 /*
949 * Now that loadable modules have had their chance to alter any GUCs,
950 * calculate MaxBackends and initialize the machinery to track child
951 * processes.
952 */
955
956 /*
957 * Calculate the size of the PGPROC fast-path lock arrays.
958 */
960
961 /*
962 * Give preloaded libraries a chance to request additional shared memory.
963 */
965
966 /*
967 * Now that loadable modules have had their chance to request additional
968 * shared memory, determine the value of any runtime-computed GUCs that
969 * depend on the amount of shared memory required.
970 */
972
973 /*
974 * Now that modules have been loaded, we can process any custom resource
975 * managers specified in the wal_consistency_checking GUC.
976 */
978
979 /*
980 * If -C was specified with a runtime-computed GUC, we held off printing
981 * the value earlier, as the GUC was not yet initialized. We handle -C
982 * for most GUCs before we lock the data directory so that the option may
983 * be used on a running server. However, a handful of GUCs are runtime-
984 * computed and do not have meaningful values until after locking the data
985 * directory, and we cannot safely calculate their values earlier on a
986 * running server. At this point, such GUCs should be properly
987 * initialized, and we haven't yet set up shared memory, so this is a good
988 * time to handle the -C option for these special GUCs.
989 */
990 if (output_config_variable != NULL)
991 {
992 const char *config_val = GetConfigOption(output_config_variable,
993 false, false);
994
995 puts(config_val ? config_val : "");
997 }
998
999 /*
1000 * Set up shared memory and semaphores.
1001 *
1002 * Note: if using SysV shmem and/or semas, each postmaster startup will
1003 * normally choose the same IPC keys. This helps ensure that we will
1004 * clean up dead IPC objects if the postmaster crashes and is restarted.
1005 */
1007
1008 /*
1009 * Estimate number of openable files. This must happen after setting up
1010 * semaphores, because on some platforms semaphores count as open files.
1011 */
1013
1014 /*
1015 * Initialize pipe (or process handle on Windows) that allows children to
1016 * wake up from sleep on postmaster death.
1017 */
1019
1020#ifdef WIN32
1021
1022 /*
1023 * Initialize I/O completion port used to deliver list of dead children.
1024 */
1025 win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
1026 if (win32ChildQueue == NULL)
1027 ereport(FATAL,
1028 (errmsg("could not create I/O completion port for child queue")));
1029#endif
1030
1031#ifdef EXEC_BACKEND
1032 /* Write out nondefault GUC settings for child processes to use */
1033 write_nondefault_variables(PGC_POSTMASTER);
1034
1035 /*
1036 * Clean out the temp directory used to transmit parameters to child
1037 * processes (see internal_forkexec). We must do this before launching
1038 * any child processes, else we have a race condition: we could remove a
1039 * parameter file before the child can read it. It should be safe to do
1040 * so now, because we verified earlier that there are no conflicting
1041 * Postgres processes in this data directory.
1042 */
1044#endif
1045
1046 /*
1047 * Forcibly remove the files signaling a standby promotion request.
1048 * Otherwise, the existence of those files triggers a promotion too early,
1049 * whether a user wants that or not.
1050 *
1051 * This removal of files is usually unnecessary because they can exist
1052 * only during a few moments during a standby promotion. However there is
1053 * a race condition: if pg_ctl promote is executed and creates the files
1054 * during a promotion, the files can stay around even after the server is
1055 * brought up to be the primary. Then, if a new standby starts by using
1056 * the backup taken from the new primary, the files can exist at server
1057 * startup and must be removed in order to avoid an unexpected promotion.
1058 *
1059 * Note that promotion signal files need to be removed before the startup
1060 * process is invoked. Because, after that, they can be used by
1061 * postmaster's SIGUSR1 signal handler.
1062 */
1064
1065 /* Do the same for logrotate signal file */
1067
1068 /* Remove any outdated file holding the current log filenames. */
1069 if (unlink(LOG_METAINFO_DATAFILE) < 0 && errno != ENOENT)
1070 ereport(LOG,
1072 errmsg("could not remove file \"%s\": %m",
1074
1075 /*
1076 * If enabled, start up syslogger collection subprocess
1077 */
1080
1081 /*
1082 * Reset whereToSendOutput from DestDebug (its starting state) to
1083 * DestNone. This stops ereport from sending log messages to stderr unless
1084 * Log_destination permits. We don't do this until the postmaster is
1085 * fully launched, since startup failures may as well be reported to
1086 * stderr.
1087 *
1088 * If we are in fact disabling logging to stderr, first emit a log message
1089 * saying so, to provide a breadcrumb trail for users who may not remember
1090 * that their logging is configured to go somewhere else.
1091 */
1093 ereport(LOG,
1094 (errmsg("ending log output to stderr"),
1095 errhint("Future log output will go to log destination \"%s\".",
1097
1099
1100 /*
1101 * Report server startup in log. While we could emit this much earlier,
1102 * it seems best to do so after starting the log collector, if we intend
1103 * to use one.
1104 */
1105 ereport(LOG,
1106 (errmsg("starting %s", PG_VERSION_STR)));
1107
1108 /*
1109 * Establish input sockets.
1110 *
1111 * First set up an on_proc_exit function that's charged with closing the
1112 * sockets again at postmaster shutdown.
1113 */
1116
1117 if (ListenAddresses)
1118 {
1119 char *rawstring;
1120 List *elemlist;
1121 ListCell *l;
1122 int success = 0;
1123
1124 /* Need a modifiable copy of ListenAddresses */
1125 rawstring = pstrdup(ListenAddresses);
1126
1127 /* Parse string into list of hostnames */
1128 if (!SplitGUCList(rawstring, ',', &elemlist))
1129 {
1130 /* syntax error in list */
1131 ereport(FATAL,
1132 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1133 errmsg("invalid list syntax in parameter \"%s\"",
1134 "listen_addresses")));
1135 }
1136
1137 foreach(l, elemlist)
1138 {
1139 char *curhost = (char *) lfirst(l);
1140
1141 if (strcmp(curhost, "*") == 0)
1142 status = ListenServerPort(AF_UNSPEC, NULL,
1143 (unsigned short) PostPortNumber,
1144 NULL,
1147 MAXLISTEN);
1148 else
1149 status = ListenServerPort(AF_UNSPEC, curhost,
1150 (unsigned short) PostPortNumber,
1151 NULL,
1154 MAXLISTEN);
1155
1156 if (status == STATUS_OK)
1157 {
1158 success++;
1159 /* record the first successful host addr in lockfile */
1160 if (!listen_addr_saved)
1161 {
1163 listen_addr_saved = true;
1164 }
1165 }
1166 else
1168 (errmsg("could not create listen socket for \"%s\"",
1169 curhost)));
1170 }
1171
1172 if (!success && elemlist != NIL)
1173 ereport(FATAL,
1174 (errmsg("could not create any TCP/IP sockets")));
1175
1176 list_free(elemlist);
1177 pfree(rawstring);
1178 }
1179
1180#ifdef USE_BONJOUR
1181 /* Register for Bonjour only if we opened TCP socket(s) */
1183 {
1184 DNSServiceErrorType err;
1185
1186 /*
1187 * We pass 0 for interface_index, which will result in registering on
1188 * all "applicable" interfaces. It's not entirely clear from the
1189 * DNS-SD docs whether this would be appropriate if we have bound to
1190 * just a subset of the available network interfaces.
1191 */
1192 err = DNSServiceRegister(&bonjour_sdref,
1193 0,
1194 0,
1196 "_postgresql._tcp.",
1197 NULL,
1198 NULL,
1200 0,
1201 NULL,
1202 NULL,
1203 NULL);
1204 if (err != kDNSServiceErr_NoError)
1205 ereport(LOG,
1206 (errmsg("DNSServiceRegister() failed: error code %ld",
1207 (long) err)));
1208
1209 /*
1210 * We don't bother to read the mDNS daemon's reply, and we expect that
1211 * it will automatically terminate our registration when the socket is
1212 * closed at postmaster termination. So there's nothing more to be
1213 * done here. However, the bonjour_sdref is kept around so that
1214 * forked children can close their copies of the socket.
1215 */
1216 }
1217#endif
1218
1220 {
1221 char *rawstring;
1222 List *elemlist;
1223 ListCell *l;
1224 int success = 0;
1225
1226 /* Need a modifiable copy of Unix_socket_directories */
1227 rawstring = pstrdup(Unix_socket_directories);
1228
1229 /* Parse string into list of directories */
1230 if (!SplitDirectoriesString(rawstring, ',', &elemlist))
1231 {
1232 /* syntax error in list */
1233 ereport(FATAL,
1234 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1235 errmsg("invalid list syntax in parameter \"%s\"",
1236 "unix_socket_directories")));
1237 }
1238
1239 foreach(l, elemlist)
1240 {
1241 char *socketdir = (char *) lfirst(l);
1242
1243 status = ListenServerPort(AF_UNIX, NULL,
1244 (unsigned short) PostPortNumber,
1245 socketdir,
1248 MAXLISTEN);
1249
1250 if (status == STATUS_OK)
1251 {
1252 success++;
1253 /* record the first successful Unix socket in lockfile */
1254 if (success == 1)
1256 }
1257 else
1259 (errmsg("could not create Unix-domain socket in directory \"%s\"",
1260 socketdir)));
1261 }
1262
1263 if (!success && elemlist != NIL)
1264 ereport(FATAL,
1265 (errmsg("could not create any Unix-domain sockets")));
1266
1267 list_free_deep(elemlist);
1268 pfree(rawstring);
1269 }
1270
1271 /*
1272 * check that we have some socket to listen on
1273 */
1274 if (NumListenSockets == 0)
1275 ereport(FATAL,
1276 (errmsg("no socket created for listening")));
1277
1278 /*
1279 * If no valid TCP ports, write an empty line for listen address,
1280 * indicating the Unix socket must be used. Note that this line is not
1281 * added to the lock file until there is a socket backing it.
1282 */
1283 if (!listen_addr_saved)
1285
1286 /*
1287 * Record postmaster options. We delay this till now to avoid recording
1288 * bogus options (eg, unusable port number).
1289 */
1290 if (!CreateOptsFile(argc, argv, my_exec_path))
1291 ExitPostmaster(1);
1292
1293 /*
1294 * Write the external PID file if requested
1295 */
1297 {
1298 FILE *fpidfile = fopen(external_pid_file, "w");
1299
1300 if (fpidfile)
1301 {
1302 fprintf(fpidfile, "%d\n", MyProcPid);
1303 fclose(fpidfile);
1304
1305 /* Make PID file world readable */
1306 if (chmod(external_pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) != 0)
1307 write_stderr("%s: could not change permissions of external PID file \"%s\": %m\n",
1309 }
1310 else
1311 write_stderr("%s: could not write external PID file \"%s\": %m\n",
1313
1315 }
1316
1317 /*
1318 * Remove old temporary files. At this point there can be no other
1319 * Postgres processes running in this directory, so this should be safe.
1320 */
1322
1323 /*
1324 * Initialize the autovacuum subsystem (again, no process start yet)
1325 */
1326 autovac_init();
1327
1328 /*
1329 * Load configuration files for client authentication.
1330 */
1331 if (!load_hba())
1332 {
1333 /*
1334 * It makes no sense to continue if we fail to load the HBA file,
1335 * since there is no way to connect to the database in this case.
1336 */
1337 ereport(FATAL,
1338 /* translator: %s is a configuration file */
1339 (errmsg("could not load %s", HbaFileName)));
1340 }
1341 if (!load_ident())
1342 {
1343 /*
1344 * We can start up without the IDENT file, although it means that you
1345 * cannot log in using any of the authentication methods that need a
1346 * user name mapping. load_ident() already logged the details of error
1347 * to the log.
1348 */
1349 }
1350
1351#ifdef HAVE_PTHREAD_IS_THREADED_NP
1352
1353 /*
1354 * On macOS, libintl replaces setlocale() with a version that calls
1355 * CFLocaleCopyCurrent() when its second argument is "" and every relevant
1356 * environment variable is unset or empty. CFLocaleCopyCurrent() makes
1357 * the process multithreaded. The postmaster calls sigprocmask() and
1358 * calls fork() without an immediate exec(), both of which have undefined
1359 * behavior in a multithreaded program. A multithreaded postmaster is the
1360 * normal case on Windows, which offers neither fork() nor sigprocmask().
1361 * Currently, macOS is the only platform having pthread_is_threaded_np(),
1362 * so we need not worry whether this HINT is appropriate elsewhere.
1363 */
1364 if (pthread_is_threaded_np() != 0)
1365 ereport(FATAL,
1366 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1367 errmsg("postmaster became multithreaded during startup"),
1368 errhint("Set the LC_ALL environment variable to a valid locale.")));
1369#endif
1370
1371 /*
1372 * Remember postmaster startup time
1373 */
1375
1376 /*
1377 * Report postmaster status in the postmaster.pid file, to allow pg_ctl to
1378 * see what's happening.
1379 */
1381
1383
1384 /* Make sure we can perform I/O while starting up. */
1386
1387 /* Start bgwriter and checkpointer so they can help with recovery */
1388 if (CheckpointerPMChild == NULL)
1390 if (BgWriterPMChild == NULL)
1392
1393 /*
1394 * We're ready to rock and roll...
1395 */
1397 Assert(StartupPMChild != NULL);
1399
1400 /* Some workers may be scheduled to start now */
1402
1403 status = ServerLoop();
1404
1405 /*
1406 * ServerLoop probably shouldn't ever return, but if it does, close down.
1407 */
1408 ExitPostmaster(status != STATUS_OK);
1409
1410 abort(); /* not reached */
1411}
void autovac_init(void)
Definition: autovacuum.c:3368
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:4933
TimestampTz PgStartTime
Definition: timestamp.c:54
int secure_initialize(bool isServerStart)
Definition: be-secure.c:75
#define write_stderr(str)
Definition: parallel.c:186
#define STATUS_OK
Definition: c.h:1157
#define fprintf(file, fmt, msg)
Definition: cubescan.l:21
@ DestNone
Definition: dest.h:87
int Log_destination
Definition: elog.c:111
int errhint(const char *fmt,...)
Definition: elog.c:1330
bool message_level_is_interesting(int elevel)
Definition: elog.c:273
char * Log_destination_string
Definition: elog.c:112
int errcode(int sqlerrcode)
Definition: elog.c:863
int errmsg(const char *fmt,...)
Definition: elog.c:1080
#define DEBUG3
Definition: elog.h:28
#define WARNING
Definition: elog.h:36
#define LOG_DESTINATION_STDERR
Definition: elog.h:485
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:3395
void RemovePgTempFiles(void)
Definition: fd.c:3335
void set_max_safe_fds(void)
Definition: fd.c:1041
#define PG_MODE_MASK_OWNER
Definition: file_perm.h:24
#define PG_TEMP_FILES_DIR
Definition: file_utils.h:63
bool IsBinaryUpgrade
Definition: globals.c:121
pid_t PostmasterPid
Definition: globals.c:106
char my_exec_path[MAXPGPATH]
Definition: globals.c:81
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4196
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_privileged)
Definition: guc.c:4219
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:1655
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:6205
void InitializeGUCOptions(void)
Definition: guc.c:1407
int GetConfigOptionFlags(const char *name, bool missing_ok)
Definition: guc.c:4316
#define GUC_RUNTIME_COMPUTED
Definition: guc.h:229
@ PGC_S_OVERRIDE
Definition: guc.h:123
@ PGC_S_ARGV
Definition: guc.h:117
@ PGC_SUSET
Definition: guc.h:78
@ PGC_POSTMASTER
Definition: guc.h:74
char * HbaFileName
Definition: guc_tables.c:557
char * external_pid_file
Definition: guc_tables.c:559
bool load_ident(void)
Definition: hba.c:3036
bool load_hba(void)
Definition: hba.c:2642
static struct @171 value
static bool success
Definition: initdb.c:187
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:309
void InitializeShmemGUCs(void)
Definition: ipci.c:340
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:190
void ApplyLauncherRegister(void)
Definition: launcher.c:997
void list_free(List *list)
Definition: list.c:1546
void list_free_deep(List *list)
Definition: list.c:1560
DispatchOption parse_dispatch_option(const char *name)
Definition: main.c:244
const char * progname
Definition: main.c:44
char * pstrdup(const char *in)
Definition: mcxt.c:1759
MemoryContext PostmasterContext
Definition: mcxt.c:168
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
void ChangeToDataDir(void)
Definition: miscinit.c:409
void process_shmem_requests(void)
Definition: miscinit.c:1879
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1519
void InitProcessLocalLatch(void)
Definition: miscinit.c:235
void process_shared_preload_libraries(void)
Definition: miscinit.c:1851
void checkDataDir(void)
Definition: miscinit.c:296
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1463
#define pg_hton16(x)
Definition: pg_bswap.h:120
PGDLLIMPORT int optind
Definition: getopt.c:51
PGDLLIMPORT int opterr
Definition: getopt.c:50
int getopt(int nargc, char *const *nargv, const char *ostr)
Definition: getopt.c:72
PGDLLIMPORT char * optarg
Definition: getopt.c:53
#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
void InitPostmasterChildSlots(void)
Definition: pmchild.c:97
#define pqsignal
Definition: port.h:552
int pgsocket
Definition: port.h:29
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3685
CommandDest whereToSendOutput
Definition: postgres.c:92
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3717
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3759
static const char * userDoption
Definition: postgres.c:154
void InitializeMaxBackends(void)
Definition: postinit.c:550
void InitializeFastPathLocks(void)
Definition: postinit.c:575
static void handle_pm_shutdown_request_signal(SIGNAL_ARGS)
Definition: postmaster.c:2058
static void maybe_start_bgworkers(void)
Definition: postmaster.c:4242
static void CloseServerPorts(int status, Datum arg)
Definition: postmaster.c:1418
@ PM_STARTUP
Definition: postmaster.c:337
static void InitPostmasterDeathWatchHandle(void)
Definition: postmaster.c:4589
void InitProcessGlobals(void)
Definition: postmaster.c:1943
static void handle_pm_reload_request_signal(SIGNAL_ARGS)
Definition: postmaster.c:1995
static void StartSysLogger(void)
Definition: postmaster.c:4017
static int ServerLoop(void)
Definition: postmaster.c:1663
int PostPortNumber
Definition: postmaster.c:203
static PMChild * BgWriterPMChild
Definition: postmaster.c:261
static void checkControlFile(void)
Definition: postmaster.c:1518
bool enable_bonjour
Definition: postmaster.c:245
static PMChild * StartChildProcess(BackendType type)
Definition: postmaster.c:3971
int ReservedConnections
Definition: postmaster.c:230
static void handle_pm_pmsignal_signal(SIGNAL_ARGS)
Definition: postmaster.c:1985
static void maybe_adjust_io_workers(void)
Definition: postmaster.c:4381
static void UpdatePMState(PMState newState)
Definition: postmaster.c:3280
static PMChild * StartupPMChild
Definition: postmaster.c:260
char * Unix_socket_directories
Definition: postmaster.c:206
static bool CreateOptsFile(int argc, char *argv[], char *fullprogname)
Definition: postmaster.c:4092
static pg_noreturn void ExitPostmaster(int status)
Definition: postmaster.c:3664
static void handle_pm_child_exit_signal(SIGNAL_ARGS)
Definition: postmaster.c:2233
static void getInstallationPaths(const char *argv0)
Definition: postmaster.c:1464
@ STARTUP_RUNNING
Definition: postmaster.c:275
static void unlink_external_pid_file(int status, Datum arg)
Definition: postmaster.c:1452
static StartupStatusEnum StartupStatus
Definition: postmaster.c:280
#define MAXLISTEN
Definition: postmaster.c:233
static void dummy_handler(SIGNAL_ARGS)
Definition: postmaster.c:3919
bool EnableSSL
Definition: postmaster.c:238
static PMChild * CheckpointerPMChild
Definition: postmaster.c:262
char * ListenAddresses
Definition: postmaster.c:209
int SuperuserReservedConnections
Definition: postmaster.c:229
char * bonjour_name
Definition: postmaster.c:246
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:418
char ** environ
void pgwin32_signal_initialize(void)
Definition: signal.c:79
bool sync_replication_slots
Definition: slotsync.c:106
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:145
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:230
void initStringInfo(StringInfo str)
Definition: stringinfo.c:97
Definition: pg_list.h:54
void RemoveLogrotateSignalFiles(void)
Definition: syslogger.c:1588
bool Logging_collector
Definition: syslogger.c:70
#define LOG_METAINFO_DATAFILE
Definition: syslogger.h:102
bool SplitDirectoriesString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:2871
bool SplitGUCList(char *rawstring, char separator, List **namelist)
Definition: varlena.c:2992
void InitializeWaitEventSupport(void)
Definition: waiteventset.c:241
bool summarize_wal
#define S_IROTH
Definition: win32_port.h:303
#define SIGCHLD
Definition: win32_port.h:168
#define SIGHUP
Definition: win32_port.h:158
#define S_IRGRP
Definition: win32_port.h:291
#define SIGPIPE
Definition: win32_port.h:163
#define SIGQUIT
Definition: win32_port.h:159
#define S_IRUSR
Definition: win32_port.h:279
#define SIGUSR1
Definition: win32_port.h:170
#define SIGALRM
Definition: win32_port.h:164
#define SIGUSR2
Definition: win32_port.h:171
#define S_IWUSR
Definition: win32_port.h:282
int XLogArchiveMode
Definition: xlog.c:121
int wal_level
Definition: xlog.c:133
void InitializeWalConsistencyChecking(void)
Definition: xlog.c:4840
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4902
@ ARCHIVE_MODE_OFF
Definition: xlog.h:65
@ WAL_LEVEL_LOGICAL
Definition: xlog.h:76
@ WAL_LEVEL_MINIMAL
Definition: xlog.h:74
void RemovePromoteSignalFiles(void)

References AddToDataDirLockFile(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, appendStringInfo(), appendStringInfoString(), ApplyLauncherRegister(), ARCHIVE_MODE_OFF, Assert(), autovac_init(), B_BG_WRITER, B_CHECKPOINTER, B_STARTUP, BgWriterPMChild, BlockSig, bonjour_name, ChangeToDataDir(), checkControlFile(), checkDataDir(), CheckDateTokenTables(), CheckpointerPMChild, CloseServerPorts(), CreateDataDirLockFile(), CreateOptsFile(), CreateSharedMemoryAndSemaphores(), StringInfoData::data, DEBUG3, DestNone, DISPATCH_POSTMASTER, 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, InitializeFastPathLocks(), InitializeGUCOptions(), InitializeMaxBackends(), InitializeShmemGUCs(), InitializeWaitEventSupport(), InitializeWalConsistencyChecking(), InitPostmasterChildSlots(), InitPostmasterDeathWatchHandle(), InitProcessGlobals(), InitProcessLocalLatch(), initStringInfo(), 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, Logging_collector, max_wal_senders, MaxConnections, MAXLISTEN, maybe_adjust_io_workers(), maybe_start_bgworkers(), MemoryContextSwitchTo(), message_level_is_interesting(), my_exec_path, MyProcPid, name, NIL, NumListenSockets, on_proc_exit(), optarg, opterr, optind, palloc(), parse_dispatch_option(), 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, 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(), SetConfigOption(), SIGALRM, SIGCHLD, SIGHUP, SIGPIPE, SIGQUIT, SIGUSR1, SIGUSR2, SplitDirectoriesString(), SplitGUCList(), StartChildProcess(), StartSysLogger(), STARTUP_RUNNING, StartupPMChild, StartupStatus, STATUS_OK, success, summarize_wal, SuperuserReservedConnections, sync_replication_slots, TopMemoryContext, UnBlockSig, Unix_socket_directories, unlink_external_pid_file(), UpdatePMState(), userDoption, value, wal_level, WAL_LEVEL_LOGICAL, WAL_LEVEL_MINIMAL, WARNING, whereToSendOutput, write_stderr, and XLogArchiveMode.

Referenced by main().

◆ PostmasterMarkPIDForWorkerNotify()

bool PostmasterMarkPIDForWorkerNotify ( int  pid)

Definition at line 4454 of file postmaster.c.

4455{
4456 dlist_iter iter;
4457 PMChild *bp;
4458
4460 {
4461 bp = dlist_container(PMChild, elem, iter.cur);
4462 if (bp->pid == pid)
4463 {
4464 bp->bgworker_notify = true;
4465 return true;
4466 }
4467 }
4468 return false;
4469}

References ActiveChildList, PMChild::bgworker_notify, dlist_iter::cur, dlist_container, dlist_foreach, and PMChild::pid.

Referenced by BackgroundWorkerStateChange().

◆ ReleasePostmasterChildSlot()

bool ReleasePostmasterChildSlot ( PMChild pmchild)

Definition at line 252 of file pmchild.c.

253{
254 dlist_delete(&pmchild->elem);
255 if (pmchild->bkend_type == B_DEAD_END_BACKEND)
256 {
257 elog(DEBUG2, "releasing dead-end backend");
258 pfree(pmchild);
259 return true;
260 }
261 else
262 {
263 PMChildPool *pool;
264
265 elog(DEBUG2, "releasing pm child slot %d", pmchild->child_slot);
266
267 /* WAL senders start out as regular backends, and share the pool */
268 if (pmchild->bkend_type == B_WAL_SENDER)
269 pool = &pmchild_pools[B_BACKEND];
270 else
271 pool = &pmchild_pools[pmchild->bkend_type];
272
273 /* sanity check that we return the entry to the right pool */
274 if (!(pmchild->child_slot >= pool->first_slotno &&
275 pmchild->child_slot < pool->first_slotno + pool->size))
276 {
277 elog(ERROR, "pmchild freelist for backend type %d is corrupt",
278 pmchild->bkend_type);
279 }
280
281 dlist_push_head(&pool->freelist, &pmchild->elem);
283 }
284}
static void dlist_delete(dlist_node *node)
Definition: ilist.h:405
@ B_WAL_SENDER
Definition: miscadmin.h:347
bool MarkPostmasterChildSlotUnassigned(int slot)
Definition: pmsignal.c:249

References B_BACKEND, B_DEAD_END_BACKEND, B_WAL_SENDER, PMChild::bkend_type, PMChild::child_slot, DEBUG2, dlist_delete(), dlist_push_head(), PMChild::elem, elog, ERROR, PMChildPool::first_slotno, PMChildPool::freelist, MarkPostmasterChildSlotUnassigned(), pfree(), pmchild_pools, and PMChildPool::size.

Referenced by BackendStartup(), CleanupBackend(), maybe_reap_io_worker(), process_pm_child_exit(), StartBackgroundWorker(), StartChildProcess(), and StartSysLogger().

Variable Documentation

◆ ActiveChildList

◆ AuthenticationTimeout

PGDLLIMPORT int AuthenticationTimeout
extern

Definition at line 241 of file postmaster.c.

Referenced by BackendInitialize(), and PerformAuthentication().

◆ bonjour_name

PGDLLIMPORT char* bonjour_name
extern

Definition at line 246 of file postmaster.c.

Referenced by PostmasterMain().

◆ ClientAuthInProgress

◆ enable_bonjour

PGDLLIMPORT bool enable_bonjour
extern

Definition at line 245 of file postmaster.c.

Referenced by PostmasterMain().

◆ EnableSSL

PGDLLIMPORT bool EnableSSL
extern

◆ ListenAddresses

PGDLLIMPORT char* ListenAddresses
extern

Definition at line 209 of file postmaster.c.

Referenced by PostmasterMain().

◆ LoadedSSL

◆ log_hostname

PGDLLIMPORT bool log_hostname
extern

Definition at line 243 of file postmaster.c.

Referenced by BackendInitialize().

◆ MyClientSocket

PGDLLIMPORT struct ClientSocket* MyClientSocket
extern

Definition at line 50 of file globals.c.

Referenced by BackendMain(), and postmaster_child_launch().

◆ postmaster_alive_fds

◆ PostPortNumber

PGDLLIMPORT int PostPortNumber
extern

Definition at line 203 of file postmaster.c.

Referenced by CreateLockFile(), and PostmasterMain().

◆ PreAuthDelay

PGDLLIMPORT int PreAuthDelay
extern

Definition at line 240 of file postmaster.c.

Referenced by BackendInitialize().

◆ progname

◆ redirection_done

PGDLLIMPORT bool redirection_done
extern

◆ remove_temp_files_after_crash

PGDLLIMPORT bool remove_temp_files_after_crash
extern

Definition at line 248 of file postmaster.c.

Referenced by PostmasterStateMachine().

◆ ReservedConnections

PGDLLIMPORT int ReservedConnections
extern

Definition at line 230 of file postmaster.c.

Referenced by InitPostgres(), and PostmasterMain().

◆ restart_after_crash

PGDLLIMPORT bool restart_after_crash
extern

Definition at line 247 of file postmaster.c.

Referenced by PostmasterStateMachine().

◆ send_abort_for_crash

PGDLLIMPORT bool send_abort_for_crash
extern

Definition at line 256 of file postmaster.c.

Referenced by HandleFatalError().

◆ send_abort_for_kill

PGDLLIMPORT bool send_abort_for_kill
extern

Definition at line 257 of file postmaster.c.

Referenced by ServerLoop().

◆ SuperuserReservedConnections

PGDLLIMPORT int SuperuserReservedConnections
extern

Definition at line 229 of file postmaster.c.

Referenced by InitPostgres(), and PostmasterMain().

◆ Unix_socket_directories

PGDLLIMPORT char* Unix_socket_directories
extern

Definition at line 206 of file postmaster.c.

Referenced by PostmasterMain().

◆ Unix_socket_group

PGDLLIMPORT char* Unix_socket_group
extern

Definition at line 107 of file pqcomm.c.

Referenced by Setup_AF_UNIX().

◆ Unix_socket_permissions

PGDLLIMPORT int Unix_socket_permissions
extern

Definition at line 106 of file pqcomm.c.

Referenced by Setup_AF_UNIX(), and show_unix_socket_permissions().