PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
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, const 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 208 of file pmchild.c.

209{
210 PMChild *pmchild;
211
212 elog(DEBUG2, "allocating dead-end child");
213
214 pmchild = (PMChild *) palloc_extended(sizeof(PMChild), MCXT_ALLOC_NO_OOM);
215 if (pmchild)
216 {
217 pmchild->pid = 0;
218 pmchild->child_slot = 0;
220 pmchild->rw = NULL;
221 pmchild->bgworker_notify = false;
222
224 }
225
226 return pmchild;
227}
#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:1991
@ 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 162 of file pmchild.c.

163{
164 dlist_head *freelist;
165 PMChild *pmchild;
166
167 if (pmchild_pools[btype].size == 0)
168 elog(ERROR, "cannot allocate a PMChild slot for backend type %d", btype);
169
170 freelist = &pmchild_pools[btype].freelist;
171 if (dlist_is_empty(freelist))
172 return NULL;
173
174 pmchild = dlist_container(PMChild, elem, dlist_pop_head_node(freelist));
175 pmchild->pid = 0;
176 pmchild->bkend_type = btype;
177 pmchild->rw = NULL;
178 pmchild->bgworker_notify = true;
179
180 /*
181 * pmchild->child_slot for each entry was initialized when the array of
182 * slots was allocated. Sanity check it.
183 */
184 if (!(pmchild->child_slot >= pmchild_pools[btype].first_slotno &&
185 pmchild->child_slot < pmchild_pools[btype].first_slotno + pmchild_pools[btype].size))
186 {
187 elog(ERROR, "pmchild freelist for backend type %d is corrupt",
188 pmchild->bkend_type);
189 }
190
192
193 /* Update the status in the shared memory array */
195
196 elog(DEBUG2, "assigned pm child slot %d for %s",
197 pmchild->child_slot, PostmasterChildName(btype));
198
199 return pmchild;
200}
#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 1855 of file postmaster.c.

1856{
1857 /* Release resources held by the postmaster's WaitEventSet. */
1858 if (pm_wait_set)
1859 {
1861 pm_wait_set = NULL;
1862 }
1863
1864#ifndef WIN32
1865
1866 /*
1867 * Close the write end of postmaster death watch pipe. It's important to
1868 * do this as early as possible, so that if postmaster dies, others won't
1869 * think that it's still running because we're holding the pipe open.
1870 */
1872 ereport(FATAL,
1874 errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
1876 /* Notify fd.c that we released one pipe FD. */
1878#endif
1879
1880 /*
1881 * Close the postmaster's listen sockets. These aren't tracked by fd.c,
1882 * so we don't call ReleaseExternalFD() here.
1883 *
1884 * The listen sockets are marked as FD_CLOEXEC, so this isn't needed in
1885 * EXEC_BACKEND mode.
1886 */
1887#ifndef EXEC_BACKEND
1888 if (ListenSockets)
1889 {
1890 for (int i = 0; i < NumListenSockets; i++)
1891 {
1892 if (closesocket(ListenSockets[i]) != 0)
1893 elog(LOG, "could not close listen socket: %m");
1894 }
1896 }
1897 NumListenSockets = 0;
1898 ListenSockets = NULL;
1899#endif
1900
1901 /*
1902 * If using syslogger, close the read side of the pipe. We don't bother
1903 * tracking this in fd.c, either.
1904 */
1905 if (!am_syslogger)
1906 {
1907#ifndef WIN32
1908 if (syslogPipe[0] >= 0)
1909 close(syslogPipe[0]);
1910 syslogPipe[0] = -1;
1911#else
1912 if (syslogPipe[0])
1913 CloseHandle(syslogPipe[0]);
1914 syslogPipe[0] = 0;
1915#endif
1916 }
1917
1918#ifdef USE_BONJOUR
1919 /* If using Bonjour, close the connection to the mDNS daemon */
1920 if (bonjour_sdref)
1921 close(DNSServiceRefSockFD(bonjour_sdref));
1922#endif
1923}
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1158
int errcode_for_file_access(void)
Definition: elog.c:877
#define LOG
Definition: elog.h:31
#define FATAL
Definition: elog.h:41
#define ereport(elevel,...)
Definition: elog.h:149
void ReleaseExternalFD(void)
Definition: fd.c:1241
#define close(a)
Definition: win32.h:12
int i
Definition: isn.c:77
void pfree(void *pointer)
Definition: mcxt.c:2146
#define closesocket
Definition: port.h:377
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:523

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 274 of file pmchild.c.

275{
276 dlist_iter iter;
277
279 {
280 PMChild *bp = dlist_container(PMChild, elem, iter.cur);
281
282 if (bp->pid == pid)
283 return bp;
284 }
285 return NULL;
286}
#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 86 of file pmchild.c.

87{
88 int slotno;
89 PMChild *slots;
90
91 /*
92 * We allow more connections here than we can have backends because some
93 * might still be authenticating; they might fail auth, or some existing
94 * backend might exit before the auth cycle is completed. The exact
95 * MaxConnections limit is enforced when a new backend tries to join the
96 * PGPROC array.
97 *
98 * WAL senders start out as regular backends, so they share the same pool.
99 */
101
105
106 /*
107 * There can be only one of each of these running at a time. They each
108 * get their own pool of just one entry.
109 */
120
121 /* The rest of the pmchild_pools are left at zero size */
122
123 /* Count the total number of slots */
125 for (int i = 0; i < BACKEND_NUM_TYPES; i++)
127
128 /* Initialize them */
129 slots = palloc(num_pmchild_slots * sizeof(PMChild));
130 slotno = 0;
131 for (int btype = 0; btype < BACKEND_NUM_TYPES; btype++)
132 {
133 pmchild_pools[btype].first_slotno = slotno + 1;
134 dlist_init(&pmchild_pools[btype].freelist);
135
136 for (int j = 0; j < pmchild_pools[btype].size; j++)
137 {
138 slots[slotno].pid = 0;
139 slots[slotno].child_slot = slotno + 1;
140 slots[slotno].bkend_type = B_INVALID;
141 slots[slotno].rw = NULL;
142 slots[slotno].bgworker_notify = false;
143 dlist_push_tail(&pmchild_pools[btype].freelist, &slots[slotno].elem);
144 slotno++;
145 }
146 }
147 Assert(slotno == num_pmchild_slots);
148
149 /* Initialize other structures */
151}
int autovacuum_worker_slots
Definition: autovacuum.c:119
int MaxConnections
Definition: globals.c:144
int max_worker_processes
Definition: globals.c:145
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:1939
#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:446
int max_wal_senders
Definition: walsender.c:126

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 1932 of file postmaster.c.

1933{
1936
1937 /*
1938 * Set a different global seed in every process. We want something
1939 * unpredictable, so if possible, use high-quality random bits for the
1940 * seed. Otherwise, fall back to a seed based on timestamp and PID.
1941 */
1943 {
1944 uint64 rseed;
1945
1946 /*
1947 * Since PIDs and timestamps tend to change more frequently in their
1948 * least significant bits, shift the timestamp left to allow a larger
1949 * total number of seeds in a given time period. Since that would
1950 * leave only 20 bits of the timestamp that cycle every ~1 second,
1951 * also mix in some higher bits.
1952 */
1953 rseed = ((uint64) MyProcPid) ^
1954 ((uint64) MyStartTimestamp << 12) ^
1955 ((uint64) MyStartTimestamp >> 20);
1956
1958 }
1959
1960 /*
1961 * Also make sure that we've set a good seed for random(3). Use of that
1962 * is deprecated in core Postgres, but extensions might use it.
1963 */
1964#ifndef WIN32
1966#endif
1967}
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:503
#define unlikely(x)
Definition: c.h:347
int MyProcPid
Definition: globals.c:48
TimestampTz MyStartTimestamp
Definition: globals.c:50
pg_time_t MyStartTime
Definition: globals.c:49
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 70 of file pmchild.c.

71{
72 if (num_pmchild_slots == 0)
73 elog(ERROR, "PM child array not initialized yet");
74 return num_pmchild_slots;
75}

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 240 of file main.c.

241{
242 for (int i = 0; i < lengthof(DispatchOptionNames); i++)
243 {
244 /*
245 * Unlike the other dispatch options, "forkchild" takes an argument,
246 * so we just look for the prefix for that one. For non-EXEC_BACKEND
247 * builds, we never want to return DISPATCH_FORKCHILD, so skip over it
248 * in that case.
249 */
250 if (i == DISPATCH_FORKCHILD)
251 {
252#ifdef EXEC_BACKEND
255 return DISPATCH_FORKCHILD;
256#endif
257 continue;
258 }
259
260 if (strcmp(DispatchOptionNames[i], name) == 0)
261 return (DispatchOption) i;
262 }
263
264 /* no match means this is a postmaster */
265 return DISPATCH_POSTMASTER;
266}
#define lengthof(array)
Definition: c.h:759
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,
const void *  startup_data,
size_t  startup_data_len,
struct ClientSocket client_sock 
)

Definition at line 229 of file launch_backend.c.

232{
233 pid_t pid;
234
236
237 /* Capture time Postmaster initiates process creation for logging */
238 if (IsExternalConnectionBackend(child_type))
239 ((BackendStartupData *) startup_data)->fork_started = GetCurrentTimestamp();
240
241#ifdef EXEC_BACKEND
242 pid = internal_forkexec(child_process_kinds[child_type].name, child_slot,
243 startup_data, startup_data_len, client_sock);
244 /* the child process will arrive in SubPostmasterMain */
245#else /* !EXEC_BACKEND */
246 pid = fork_process();
247 if (pid == 0) /* child */
248 {
249 /* Capture and transfer timings that may be needed for logging */
250 if (IsExternalConnectionBackend(child_type))
251 {
253 ((BackendStartupData *) startup_data)->socket_created;
255 ((BackendStartupData *) startup_data)->fork_started;
257 }
258
259 /* Close the postmaster's sockets */
260 ClosePostmasterPorts(child_type == B_LOGGER);
261
262 /* Detangle from postmaster */
264
265 /* Detach shared memory if not needed. */
266 if (!child_process_kinds[child_type].shmem_attach)
267 {
270 }
271
272 /*
273 * Enter the Main function with TopMemoryContext. The startup data is
274 * allocated in PostmasterContext, so we cannot release it here yet.
275 * The Main function will do it after it's done handling the startup
276 * data.
277 */
279
280 MyPMChildSlot = child_slot;
281 if (client_sock)
282 {
284 memcpy(MyClientSocket, client_sock, sizeof(ClientSocket));
285 }
286
287 /*
288 * Run the appropriate Main function
289 */
290 child_process_kinds[child_type].main_fn(startup_data, startup_data_len);
291 pg_unreachable(); /* main_fn never returns */
292 }
293#endif /* EXEC_BACKEND */
294 return pid;
295}
ConnectionTiming conn_timing
#define pg_unreachable()
Definition: c.h:332
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:51
int MyPMChildSlot
Definition: globals.c:55
bool IsUnderPostmaster
Definition: globals.c:121
bool IsPostmasterEnvironment
Definition: globals.c:120
static child_process_kind child_process_kinds[]
MemoryContext TopMemoryContext
Definition: mcxt.c:165
#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:1855
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 211 of file launch_backend.c.

212{
213 return child_process_kinds[child_type].name;
214}

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\"")));
857
858 /*
859 * Other one-time internal sanity checks can go here, if they are fast.
860 * (Put any slow processing further down, after postmaster.pid creation.)
861 */
863 {
864 write_stderr("%s: invalid datetoken tables, please fix\n", progname);
866 }
867
868 /*
869 * Now that we are done processing the postmaster arguments, reset
870 * getopt(3) library so that it will work correctly in subprocesses.
871 */
872 optind = 1;
873#ifdef HAVE_INT_OPTRESET
874 optreset = 1; /* some systems need this too */
875#endif
876
877 /* For debugging: display postmaster environment */
879 {
880#if !defined(WIN32) || defined(_MSC_VER)
881 extern char **environ;
882#endif
883 char **p;
885
886 initStringInfo(&si);
887
888 appendStringInfoString(&si, "initial environment dump:");
889 for (p = environ; *p; ++p)
890 appendStringInfo(&si, "\n%s", *p);
891
893 pfree(si.data);
894 }
895
896 /*
897 * Create lockfile for data directory.
898 *
899 * We want to do this before we try to grab the input sockets, because the
900 * data directory interlock is more reliable than the socket-file
901 * interlock (thanks to whoever decided to put socket files in /tmp :-().
902 * For the same reason, it's best to grab the TCP socket(s) before the
903 * Unix socket(s).
904 *
905 * Also note that this internally sets up the on_proc_exit function that
906 * is responsible for removing both data directory and socket lockfiles;
907 * so it must happen before opening sockets so that at exit, the socket
908 * lockfiles go away after CloseServerPorts runs.
909 */
911
912 /*
913 * Read the control file (for error checking and config info).
914 *
915 * Since we verify the control file's CRC, this has a useful side effect
916 * on machines where we need a run-time test for CRC support instructions.
917 * The postmaster will do the test once at startup, and then its child
918 * processes will inherit the correct function pointer and not need to
919 * repeat the test.
920 */
922
923 /*
924 * Register the apply launcher. It's probably a good idea to call this
925 * before any modules had a chance to take the background worker slots.
926 */
928
929 /*
930 * process any libraries that should be preloaded at postmaster start
931 */
933
934 /*
935 * Initialize SSL library, if specified.
936 */
937#ifdef USE_SSL
938 if (EnableSSL)
939 {
940 (void) secure_initialize(true);
941 LoadedSSL = true;
942 }
943#endif
944
945 /*
946 * Now that loadable modules have had their chance to alter any GUCs,
947 * calculate MaxBackends and initialize the machinery to track child
948 * processes.
949 */
952
953 /*
954 * Calculate the size of the PGPROC fast-path lock arrays.
955 */
957
958 /*
959 * Give preloaded libraries a chance to request additional shared memory.
960 */
962
963 /*
964 * Now that loadable modules have had their chance to request additional
965 * shared memory, determine the value of any runtime-computed GUCs that
966 * depend on the amount of shared memory required.
967 */
969
970 /*
971 * Now that modules have been loaded, we can process any custom resource
972 * managers specified in the wal_consistency_checking GUC.
973 */
975
976 /*
977 * If -C was specified with a runtime-computed GUC, we held off printing
978 * the value earlier, as the GUC was not yet initialized. We handle -C
979 * for most GUCs before we lock the data directory so that the option may
980 * be used on a running server. However, a handful of GUCs are runtime-
981 * computed and do not have meaningful values until after locking the data
982 * directory, and we cannot safely calculate their values earlier on a
983 * running server. At this point, such GUCs should be properly
984 * initialized, and we haven't yet set up shared memory, so this is a good
985 * time to handle the -C option for these special GUCs.
986 */
987 if (output_config_variable != NULL)
988 {
989 const char *config_val = GetConfigOption(output_config_variable,
990 false, false);
991
992 puts(config_val ? config_val : "");
994 }
995
996 /*
997 * Set up shared memory and semaphores.
998 *
999 * Note: if using SysV shmem and/or semas, each postmaster startup will
1000 * normally choose the same IPC keys. This helps ensure that we will
1001 * clean up dead IPC objects if the postmaster crashes and is restarted.
1002 */
1004
1005 /*
1006 * Estimate number of openable files. This must happen after setting up
1007 * semaphores, because on some platforms semaphores count as open files.
1008 */
1010
1011 /*
1012 * Initialize pipe (or process handle on Windows) that allows children to
1013 * wake up from sleep on postmaster death.
1014 */
1016
1017#ifdef WIN32
1018
1019 /*
1020 * Initialize I/O completion port used to deliver list of dead children.
1021 */
1022 win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
1023 if (win32ChildQueue == NULL)
1024 ereport(FATAL,
1025 (errmsg("could not create I/O completion port for child queue")));
1026#endif
1027
1028#ifdef EXEC_BACKEND
1029 /* Write out nondefault GUC settings for child processes to use */
1030 write_nondefault_variables(PGC_POSTMASTER);
1031
1032 /*
1033 * Clean out the temp directory used to transmit parameters to child
1034 * processes (see internal_forkexec). We must do this before launching
1035 * any child processes, else we have a race condition: we could remove a
1036 * parameter file before the child can read it. It should be safe to do
1037 * so now, because we verified earlier that there are no conflicting
1038 * Postgres processes in this data directory.
1039 */
1041#endif
1042
1043 /*
1044 * Forcibly remove the files signaling a standby promotion request.
1045 * Otherwise, the existence of those files triggers a promotion too early,
1046 * whether a user wants that or not.
1047 *
1048 * This removal of files is usually unnecessary because they can exist
1049 * only during a few moments during a standby promotion. However there is
1050 * a race condition: if pg_ctl promote is executed and creates the files
1051 * during a promotion, the files can stay around even after the server is
1052 * brought up to be the primary. Then, if a new standby starts by using
1053 * the backup taken from the new primary, the files can exist at server
1054 * startup and must be removed in order to avoid an unexpected promotion.
1055 *
1056 * Note that promotion signal files need to be removed before the startup
1057 * process is invoked. Because, after that, they can be used by
1058 * postmaster's SIGUSR1 signal handler.
1059 */
1061
1062 /* Do the same for logrotate signal file */
1064
1065 /* Remove any outdated file holding the current log filenames. */
1066 if (unlink(LOG_METAINFO_DATAFILE) < 0 && errno != ENOENT)
1067 ereport(LOG,
1069 errmsg("could not remove file \"%s\": %m",
1071
1072 /*
1073 * If enabled, start up syslogger collection subprocess
1074 */
1077
1078 /*
1079 * Reset whereToSendOutput from DestDebug (its starting state) to
1080 * DestNone. This stops ereport from sending log messages to stderr unless
1081 * Log_destination permits. We don't do this until the postmaster is
1082 * fully launched, since startup failures may as well be reported to
1083 * stderr.
1084 *
1085 * If we are in fact disabling logging to stderr, first emit a log message
1086 * saying so, to provide a breadcrumb trail for users who may not remember
1087 * that their logging is configured to go somewhere else.
1088 */
1090 ereport(LOG,
1091 (errmsg("ending log output to stderr"),
1092 errhint("Future log output will go to log destination \"%s\".",
1094
1096
1097 /*
1098 * Report server startup in log. While we could emit this much earlier,
1099 * it seems best to do so after starting the log collector, if we intend
1100 * to use one.
1101 */
1102 ereport(LOG,
1103 (errmsg("starting %s", PG_VERSION_STR)));
1104
1105 /*
1106 * Establish input sockets.
1107 *
1108 * First set up an on_proc_exit function that's charged with closing the
1109 * sockets again at postmaster shutdown.
1110 */
1113
1114 if (ListenAddresses)
1115 {
1116 char *rawstring;
1117 List *elemlist;
1118 ListCell *l;
1119 int success = 0;
1120
1121 /* Need a modifiable copy of ListenAddresses */
1122 rawstring = pstrdup(ListenAddresses);
1123
1124 /* Parse string into list of hostnames */
1125 if (!SplitGUCList(rawstring, ',', &elemlist))
1126 {
1127 /* syntax error in list */
1128 ereport(FATAL,
1129 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1130 errmsg("invalid list syntax in parameter \"%s\"",
1131 "listen_addresses")));
1132 }
1133
1134 foreach(l, elemlist)
1135 {
1136 char *curhost = (char *) lfirst(l);
1137
1138 if (strcmp(curhost, "*") == 0)
1139 status = ListenServerPort(AF_UNSPEC, NULL,
1140 (unsigned short) PostPortNumber,
1141 NULL,
1144 MAXLISTEN);
1145 else
1146 status = ListenServerPort(AF_UNSPEC, curhost,
1147 (unsigned short) PostPortNumber,
1148 NULL,
1151 MAXLISTEN);
1152
1153 if (status == STATUS_OK)
1154 {
1155 success++;
1156 /* record the first successful host addr in lockfile */
1157 if (!listen_addr_saved)
1158 {
1160 listen_addr_saved = true;
1161 }
1162 }
1163 else
1165 (errmsg("could not create listen socket for \"%s\"",
1166 curhost)));
1167 }
1168
1169 if (!success && elemlist != NIL)
1170 ereport(FATAL,
1171 (errmsg("could not create any TCP/IP sockets")));
1172
1173 list_free(elemlist);
1174 pfree(rawstring);
1175 }
1176
1177#ifdef USE_BONJOUR
1178 /* Register for Bonjour only if we opened TCP socket(s) */
1180 {
1181 DNSServiceErrorType err;
1182
1183 /*
1184 * We pass 0 for interface_index, which will result in registering on
1185 * all "applicable" interfaces. It's not entirely clear from the
1186 * DNS-SD docs whether this would be appropriate if we have bound to
1187 * just a subset of the available network interfaces.
1188 */
1189 err = DNSServiceRegister(&bonjour_sdref,
1190 0,
1191 0,
1193 "_postgresql._tcp.",
1194 NULL,
1195 NULL,
1197 0,
1198 NULL,
1199 NULL,
1200 NULL);
1201 if (err != kDNSServiceErr_NoError)
1202 ereport(LOG,
1203 (errmsg("DNSServiceRegister() failed: error code %ld",
1204 (long) err)));
1205
1206 /*
1207 * We don't bother to read the mDNS daemon's reply, and we expect that
1208 * it will automatically terminate our registration when the socket is
1209 * closed at postmaster termination. So there's nothing more to be
1210 * done here. However, the bonjour_sdref is kept around so that
1211 * forked children can close their copies of the socket.
1212 */
1213 }
1214#endif
1215
1217 {
1218 char *rawstring;
1219 List *elemlist;
1220 ListCell *l;
1221 int success = 0;
1222
1223 /* Need a modifiable copy of Unix_socket_directories */
1224 rawstring = pstrdup(Unix_socket_directories);
1225
1226 /* Parse string into list of directories */
1227 if (!SplitDirectoriesString(rawstring, ',', &elemlist))
1228 {
1229 /* syntax error in list */
1230 ereport(FATAL,
1231 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1232 errmsg("invalid list syntax in parameter \"%s\"",
1233 "unix_socket_directories")));
1234 }
1235
1236 foreach(l, elemlist)
1237 {
1238 char *socketdir = (char *) lfirst(l);
1239
1240 status = ListenServerPort(AF_UNIX, NULL,
1241 (unsigned short) PostPortNumber,
1242 socketdir,
1245 MAXLISTEN);
1246
1247 if (status == STATUS_OK)
1248 {
1249 success++;
1250 /* record the first successful Unix socket in lockfile */
1251 if (success == 1)
1253 }
1254 else
1256 (errmsg("could not create Unix-domain socket in directory \"%s\"",
1257 socketdir)));
1258 }
1259
1260 if (!success && elemlist != NIL)
1261 ereport(FATAL,
1262 (errmsg("could not create any Unix-domain sockets")));
1263
1264 list_free_deep(elemlist);
1265 pfree(rawstring);
1266 }
1267
1268 /*
1269 * check that we have some socket to listen on
1270 */
1271 if (NumListenSockets == 0)
1272 ereport(FATAL,
1273 (errmsg("no socket created for listening")));
1274
1275 /*
1276 * If no valid TCP ports, write an empty line for listen address,
1277 * indicating the Unix socket must be used. Note that this line is not
1278 * added to the lock file until there is a socket backing it.
1279 */
1280 if (!listen_addr_saved)
1282
1283 /*
1284 * Record postmaster options. We delay this till now to avoid recording
1285 * bogus options (eg, unusable port number).
1286 */
1287 if (!CreateOptsFile(argc, argv, my_exec_path))
1288 ExitPostmaster(1);
1289
1290 /*
1291 * Write the external PID file if requested
1292 */
1294 {
1295 FILE *fpidfile = fopen(external_pid_file, "w");
1296
1297 if (fpidfile)
1298 {
1299 fprintf(fpidfile, "%d\n", MyProcPid);
1300 fclose(fpidfile);
1301
1302 /* Make PID file world readable */
1303 if (chmod(external_pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) != 0)
1304 write_stderr("%s: could not change permissions of external PID file \"%s\": %m\n",
1306 }
1307 else
1308 write_stderr("%s: could not write external PID file \"%s\": %m\n",
1310
1312 }
1313
1314 /*
1315 * Remove old temporary files. At this point there can be no other
1316 * Postgres processes running in this directory, so this should be safe.
1317 */
1319
1320 /*
1321 * Initialize the autovacuum subsystem (again, no process start yet)
1322 */
1323 autovac_init();
1324
1325 /*
1326 * Load configuration files for client authentication.
1327 */
1328 if (!load_hba())
1329 {
1330 /*
1331 * It makes no sense to continue if we fail to load the HBA file,
1332 * since there is no way to connect to the database in this case.
1333 */
1334 ereport(FATAL,
1335 /* translator: %s is a configuration file */
1336 (errmsg("could not load %s", HbaFileName)));
1337 }
1338 if (!load_ident())
1339 {
1340 /*
1341 * We can start up without the IDENT file, although it means that you
1342 * cannot log in using any of the authentication methods that need a
1343 * user name mapping. load_ident() already logged the details of error
1344 * to the log.
1345 */
1346 }
1347
1348#ifdef HAVE_PTHREAD_IS_THREADED_NP
1349
1350 /*
1351 * On macOS, libintl replaces setlocale() with a version that calls
1352 * CFLocaleCopyCurrent() when its second argument is "" and every relevant
1353 * environment variable is unset or empty. CFLocaleCopyCurrent() makes
1354 * the process multithreaded. The postmaster calls sigprocmask() and
1355 * calls fork() without an immediate exec(), both of which have undefined
1356 * behavior in a multithreaded program. A multithreaded postmaster is the
1357 * normal case on Windows, which offers neither fork() nor sigprocmask().
1358 * Currently, macOS is the only platform having pthread_is_threaded_np(),
1359 * so we need not worry whether this HINT is appropriate elsewhere.
1360 */
1361 if (pthread_is_threaded_np() != 0)
1362 ereport(FATAL,
1363 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1364 errmsg("postmaster became multithreaded during startup"),
1365 errhint("Set the LC_ALL environment variable to a valid locale.")));
1366#endif
1367
1368 /*
1369 * Remember postmaster startup time
1370 */
1372
1373 /*
1374 * Report postmaster status in the postmaster.pid file, to allow pg_ctl to
1375 * see what's happening.
1376 */
1378
1380
1381 /* Make sure we can perform I/O while starting up. */
1383
1384 /* Start bgwriter and checkpointer so they can help with recovery */
1385 if (CheckpointerPMChild == NULL)
1387 if (BgWriterPMChild == NULL)
1389
1390 /*
1391 * We're ready to rock and roll...
1392 */
1394 Assert(StartupPMChild != NULL);
1396
1397 /* Some workers may be scheduled to start now */
1399
1400 status = ServerLoop();
1401
1402 /*
1403 * ServerLoop probably shouldn't ever return, but if it does, close down.
1404 */
1405 ExitPostmaster(status != STATUS_OK);
1406
1407 abort(); /* not reached */
1408}
void autovac_init(void)
Definition: autovacuum.c:3306
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:4927
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:1140
#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:1318
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:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#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:3398
void RemovePgTempFiles(void)
Definition: fd.c:3338
void set_max_safe_fds(void)
Definition: fd.c:1044
#define PG_MODE_MASK_OWNER
Definition: file_perm.h:24
#define PG_TEMP_FILES_DIR
Definition: file_utils.h:63
bool IsBinaryUpgrade
Definition: globals.c:122
pid_t PostmasterPid
Definition: globals.c:107
char my_exec_path[MAXPGPATH]
Definition: globals.c:82
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4332
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_privileged)
Definition: guc.c:4355
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:1784
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:6363
void InitializeGUCOptions(void)
Definition: guc.c:1530
int GetConfigOptionFlags(const char *name, bool missing_ok)
Definition: guc.c:4452
#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:556
char * external_pid_file
Definition: guc_tables.c:558
bool load_ident(void)
Definition: hba.c:3021
bool load_hba(void)
Definition: hba.c:2645
static struct @165 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:358
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:202
void ApplyLauncherRegister(void)
Definition: launcher.c:915
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:240
const char * progname
Definition: main.c:44
char * pstrdup(const char *in)
Definition: mcxt.c:2321
MemoryContext PostmasterContext
Definition: mcxt.c:167
#define AllocSetContextCreate
Definition: memutils.h:149
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:180
void ChangeToDataDir(void)
Definition: miscinit.c:460
void process_shmem_requests(void)
Definition: miscinit.c:1930
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1570
void InitProcessLocalLatch(void)
Definition: miscinit.c:235
void process_shared_preload_libraries(void)
Definition: miscinit.c:1902
void checkDataDir(void)
Definition: miscinit.c:347
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1514
#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:86
#define pqsignal
Definition: port.h:531
int pgsocket
Definition: port.h:29
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3684
CommandDest whereToSendOutput
Definition: postgres.c:91
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3713
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3755
static const char * userDoption
Definition: postgres.c:153
void InitializeMaxBackends(void)
Definition: postinit.c:555
void InitializeFastPathLocks(void)
Definition: postinit.c:587
static void handle_pm_shutdown_request_signal(SIGNAL_ARGS)
Definition: postmaster.c:2047
static void maybe_start_bgworkers(void)
Definition: postmaster.c:4224
static void CloseServerPorts(int status, Datum arg)
Definition: postmaster.c:1415
@ PM_STARTUP
Definition: postmaster.c:337
static void InitPostmasterDeathWatchHandle(void)
Definition: postmaster.c:4571
void InitProcessGlobals(void)
Definition: postmaster.c:1932
static void handle_pm_reload_request_signal(SIGNAL_ARGS)
Definition: postmaster.c:1984
static void StartSysLogger(void)
Definition: postmaster.c:3999
static int ServerLoop(void)
Definition: postmaster.c:1652
int PostPortNumber
Definition: postmaster.c:203
static PMChild * BgWriterPMChild
Definition: postmaster.c:261
static void checkControlFile(void)
Definition: postmaster.c:1515
bool enable_bonjour
Definition: postmaster.c:245
static PMChild * StartChildProcess(BackendType type)
Definition: postmaster.c:3953
int ReservedConnections
Definition: postmaster.c:230
static void handle_pm_pmsignal_signal(SIGNAL_ARGS)
Definition: postmaster.c:1974
static void maybe_adjust_io_workers(void)
Definition: postmaster.c:4363
static void UpdatePMState(PMState newState)
Definition: postmaster.c:3262
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:4074
static pg_noreturn void ExitPostmaster(int status)
Definition: postmaster.c:3646
static void handle_pm_child_exit_signal(SIGNAL_ARGS)
Definition: postmaster.c:2222
static void getInstallationPaths(const char *argv0)
Definition: postmaster.c:1461
@ STARTUP_RUNNING
Definition: postmaster.c:275
static void unlink_external_pid_file(int status, Datum arg)
Definition: postmaster.c:1449
static StartupStatusEnum StartupStatus
Definition: postmaster.c:280
#define MAXLISTEN
Definition: postmaster.c:233
static void dummy_handler(SIGNAL_ARGS)
Definition: postmaster.c:3901
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
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:3652
bool SplitGUCList(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3773
void InitializeWaitEventSupport(void)
Definition: waiteventset.c:240
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:119
int wal_level
Definition: xlog.c:131
void InitializeWalConsistencyChecking(void)
Definition: xlog.c:4965
void LocalProcessControlFile(bool reset)
Definition: xlog.c:5027
@ ARCHIVE_MODE_OFF
Definition: xlog.h:65
@ 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, TopMemoryContext, UnBlockSig, Unix_socket_directories, unlink_external_pid_file(), UpdatePMState(), userDoption, value, wal_level, WAL_LEVEL_MINIMAL, WARNING, whereToSendOutput, write_stderr, and XLogArchiveMode.

Referenced by main().

◆ PostmasterMarkPIDForWorkerNotify()

bool PostmasterMarkPIDForWorkerNotify ( int  pid)

Definition at line 4436 of file postmaster.c.

4437{
4438 dlist_iter iter;
4439 PMChild *bp;
4440
4442 {
4443 bp = dlist_container(PMChild, elem, iter.cur);
4444 if (bp->pid == pid)
4445 {
4446 bp->bgworker_notify = true;
4447 return true;
4448 }
4449 }
4450 return false;
4451}

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 236 of file pmchild.c.

237{
238 dlist_delete(&pmchild->elem);
239 if (pmchild->bkend_type == B_DEAD_END_BACKEND)
240 {
241 elog(DEBUG2, "releasing dead-end backend");
242 pfree(pmchild);
243 return true;
244 }
245 else
246 {
247 PMChildPool *pool;
248
249 elog(DEBUG2, "releasing pm child slot %d", pmchild->child_slot);
250
251 /* WAL senders start out as regular backends, and share the pool */
252 if (pmchild->bkend_type == B_WAL_SENDER)
253 pool = &pmchild_pools[B_BACKEND];
254 else
255 pool = &pmchild_pools[pmchild->bkend_type];
256
257 /* sanity check that we return the entry to the right pool */
258 if (!(pmchild->child_slot >= pool->first_slotno &&
259 pmchild->child_slot < pool->first_slotno + pool->size))
260 {
261 elog(ERROR, "pmchild freelist for backend type %d is corrupt",
262 pmchild->bkend_type);
263 }
264
265 dlist_push_head(&pool->freelist, &pmchild->elem);
267 }
268}
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 51 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().