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 */
 
#define MAX_BACKENDS   0x3FFFF
 

Typedefs

typedef enum DispatchOption DispatchOption
 

Enumerations

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

Functions

void PostmasterMain (int argc, char *argv[]) pg_attribute_noreturn()
 
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, char *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_connections
 
PGDLLIMPORT bool log_hostname
 
PGDLLIMPORT bool enable_bonjour
 
PGDLLIMPORT char * bonjour_name
 
PGDLLIMPORT bool restart_after_crash
 
PGDLLIMPORT bool remove_temp_files_after_crash
 
PGDLLIMPORT bool send_abort_for_crash
 
PGDLLIMPORT bool send_abort_for_kill
 
PGDLLIMPORT int postmaster_alive_fds [2]
 
PGDLLIMPORT const char * progname
 
PGDLLIMPORT bool redirection_done
 
PGDLLIMPORT bool LoadedSSL
 
PGDLLIMPORT struct ClientSocketMyClientSocket
 
dlist_head ActiveChildList
 

Macro Definition Documentation

◆ MAX_BACKENDS

#define MAX_BACKENDS   0x3FFFF

Definition at line 138 of file postmaster.h.

◆ POSTMASTER_FD_OWN

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

Definition at line 85 of file postmaster.h.

◆ POSTMASTER_FD_WATCH

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

Definition at line 84 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 145 of file postmaster.h.

147{
153 DISPATCH_POSTMASTER, /* must be last */
@ DISPATCH_SINGLE
Definition: postmaster.h:151
@ DISPATCH_DESCRIBE_CONFIG
Definition: postmaster.h:150
@ DISPATCH_BOOT
Definition: postmaster.h:148
@ DISPATCH_CHECK
Definition: postmaster.h:147
@ DISPATCH_FORKCHILD
Definition: postmaster.h:149
@ DISPATCH_POSTMASTER
Definition: postmaster.h:152

Function Documentation

◆ AllocDeadEndChild()

PMChild * AllocDeadEndChild ( void  )

Definition at line 207 of file pmchild.c.

208{
209 PMChild *pmchild;
210
211 elog(DEBUG2, "allocating dead-end child");
212
213 pmchild = (PMChild *) palloc_extended(sizeof(PMChild), MCXT_ALLOC_NO_OOM);
214 if (pmchild)
215 {
216 pmchild->pid = 0;
217 pmchild->child_slot = 0;
219 pmchild->rw = NULL;
220 pmchild->bgworker_notify = false;
221
223 }
224
225 return pmchild;
226}
#define DEBUG2
Definition: elog.h:29
#define elog(elevel,...)
Definition: elog.h:225
#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:1368
@ B_DEAD_END_BACKEND
Definition: miscadmin.h:342
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 161 of file pmchild.c.

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

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

◆ ClosePostmasterPorts()

void ClosePostmasterPorts ( bool  am_syslogger)

Definition at line 1842 of file postmaster.c.

1843{
1844 /* Release resources held by the postmaster's WaitEventSet. */
1845 if (pm_wait_set)
1846 {
1848 pm_wait_set = NULL;
1849 }
1850
1851#ifndef WIN32
1852
1853 /*
1854 * Close the write end of postmaster death watch pipe. It's important to
1855 * do this as early as possible, so that if postmaster dies, others won't
1856 * think that it's still running because we're holding the pipe open.
1857 */
1859 ereport(FATAL,
1861 errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
1863 /* Notify fd.c that we released one pipe FD. */
1865#endif
1866
1867 /*
1868 * Close the postmaster's listen sockets. These aren't tracked by fd.c,
1869 * so we don't call ReleaseExternalFD() here.
1870 *
1871 * The listen sockets are marked as FD_CLOEXEC, so this isn't needed in
1872 * EXEC_BACKEND mode.
1873 */
1874#ifndef EXEC_BACKEND
1875 if (ListenSockets)
1876 {
1877 for (int i = 0; i < NumListenSockets; i++)
1878 {
1879 if (closesocket(ListenSockets[i]) != 0)
1880 elog(LOG, "could not close listen socket: %m");
1881 }
1883 }
1884 NumListenSockets = 0;
1885 ListenSockets = NULL;
1886#endif
1887
1888 /*
1889 * If using syslogger, close the read side of the pipe. We don't bother
1890 * tracking this in fd.c, either.
1891 */
1892 if (!am_syslogger)
1893 {
1894#ifndef WIN32
1895 if (syslogPipe[0] >= 0)
1896 close(syslogPipe[0]);
1897 syslogPipe[0] = -1;
1898#else
1899 if (syslogPipe[0])
1900 CloseHandle(syslogPipe[0]);
1901 syslogPipe[0] = 0;
1902#endif
1903 }
1904
1905#ifdef USE_BONJOUR
1906 /* If using Bonjour, close the connection to the mDNS daemon */
1907 if (bonjour_sdref)
1908 close(DNSServiceRefSockFD(bonjour_sdref));
1909#endif
1910}
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
int errcode_for_file_access(void)
Definition: elog.c:876
#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:1238
#define close(a)
Definition: win32.h:12
int i
Definition: isn.c:72
void FreeWaitEventSetAfterFork(WaitEventSet *set)
Definition: latch.c:911
void pfree(void *pointer)
Definition: mcxt.c:1521
#define closesocket
Definition: port.h:377
static pgsocket * ListenSockets
Definition: postmaster.c:231
static int NumListenSockets
Definition: postmaster.c:230
int postmaster_alive_fds[2]
Definition: postmaster.c:473
static WaitEventSet * pm_wait_set
Definition: postmaster.c:395
#define POSTMASTER_FD_OWN
Definition: postmaster.h:85
int syslogPipe[2]
Definition: syslogger.c:114

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

274{
275 dlist_iter iter;
276
278 {
279 PMChild *bp = dlist_container(PMChild, elem, iter.cur);
280
281 if (bp->pid == pid)
282 return bp;
283 }
284 return NULL;
285}
#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
104
105 /*
106 * There can be only one of each of these running at a time. They each
107 * get their own pool of just one entry.
108 */
119
120 /* The rest of the pmchild_pools are left at zero size */
121
122 /* Count the total number of slots */
124 for (int i = 0; i < BACKEND_NUM_TYPES; i++)
126
127 /* Initialize them */
128 slots = palloc(num_pmchild_slots * sizeof(PMChild));
129 slotno = 0;
130 for (int btype = 0; btype < BACKEND_NUM_TYPES; btype++)
131 {
132 pmchild_pools[btype].first_slotno = slotno + 1;
133 dlist_init(&pmchild_pools[btype].freelist);
134
135 for (int j = 0; j < pmchild_pools[btype].size; j++)
136 {
137 slots[slotno].pid = 0;
138 slots[slotno].child_slot = slotno + 1;
139 slots[slotno].bkend_type = B_INVALID;
140 slots[slotno].rw = NULL;
141 slots[slotno].bgworker_notify = false;
142 dlist_push_tail(&pmchild_pools[btype].freelist, &slots[slotno].elem);
143 slotno++;
144 }
145 }
146 Assert(slotno == num_pmchild_slots);
147
148 /* Initialize other structures */
150}
int autovacuum_worker_slots
Definition: autovacuum.c:118
#define Assert(condition)
Definition: c.h:815
int MaxConnections
Definition: globals.c:142
int max_worker_processes
Definition: globals.c:143
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:73
void * palloc(Size size)
Definition: mcxt.c:1317
#define BACKEND_NUM_TYPES
Definition: miscadmin.h:375
@ B_WAL_SUMMARIZER
Definition: miscadmin.h:365
@ B_WAL_WRITER
Definition: miscadmin.h:366
@ B_WAL_RECEIVER
Definition: miscadmin.h:364
@ B_CHECKPOINTER
Definition: miscadmin.h:362
@ B_LOGGER
Definition: miscadmin.h:372
@ B_STARTUP
Definition: miscadmin.h:363
@ B_BG_WORKER
Definition: miscadmin.h:345
@ B_INVALID
Definition: miscadmin.h:338
@ B_BG_WRITER
Definition: miscadmin.h:361
@ B_BACKEND
Definition: miscadmin.h:341
@ B_ARCHIVER
Definition: miscadmin.h:360
@ B_AUTOVAC_LAUNCHER
Definition: miscadmin.h:343
@ B_SLOTSYNC_WORKER
Definition: miscadmin.h:347
@ B_AUTOVAC_WORKER
Definition: miscadmin.h:344
NON_EXEC_STATIC int num_pmchild_slots
Definition: pmchild.c:55
int max_wal_senders
Definition: walsender.c:121

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_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_wal_senders, max_worker_processes, MaxConnections, num_pmchild_slots, palloc(), PMChild::pid, pmchild_pools, PMChild::rw, PMChildPool::size, and size.

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

◆ InitProcessGlobals()

void InitProcessGlobals ( void  )

Definition at line 1919 of file postmaster.c.

1920{
1923
1924 /*
1925 * Set a different global seed in every process. We want something
1926 * unpredictable, so if possible, use high-quality random bits for the
1927 * seed. Otherwise, fall back to a seed based on timestamp and PID.
1928 */
1930 {
1931 uint64 rseed;
1932
1933 /*
1934 * Since PIDs and timestamps tend to change more frequently in their
1935 * least significant bits, shift the timestamp left to allow a larger
1936 * total number of seeds in a given time period. Since that would
1937 * leave only 20 bits of the timestamp that cycle every ~1 second,
1938 * also mix in some higher bits.
1939 */
1940 rseed = ((uint64) MyProcPid) ^
1941 ((uint64) MyStartTimestamp << 12) ^
1942 ((uint64) MyStartTimestamp >> 20);
1943
1945 }
1946
1947 /*
1948 * Also make sure that we've set a good seed for random(3). Use of that
1949 * is deprecated in core Postgres, but extensions might use it.
1950 */
1951#ifndef WIN32
1953#endif
1954}
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1644
pg_time_t timestamptz_to_time_t(TimestampTz t)
Definition: timestamp.c:1823
uint64_t uint64
Definition: c.h:489
#define unlikely(x)
Definition: c.h:333
int MyProcPid
Definition: globals.c:46
TimestampTz MyStartTimestamp
Definition: globals.c:48
pg_time_t MyStartTime
Definition: globals.c:47
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 243 of file main.c.

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

Definition at line 227 of file launch_backend.c.

230{
231 pid_t pid;
232
234
235#ifdef EXEC_BACKEND
236 pid = internal_forkexec(child_process_kinds[child_type].name, child_slot,
237 startup_data, startup_data_len, client_sock);
238 /* the child process will arrive in SubPostmasterMain */
239#else /* !EXEC_BACKEND */
240 pid = fork_process();
241 if (pid == 0) /* child */
242 {
243 /* Close the postmaster's sockets */
244 ClosePostmasterPorts(child_type == B_LOGGER);
245
246 /* Detangle from postmaster */
248
249 /* Detach shared memory if not needed. */
250 if (!child_process_kinds[child_type].shmem_attach)
251 {
254 }
255
256 /*
257 * Enter the Main function with TopMemoryContext. The startup data is
258 * allocated in PostmasterContext, so we cannot release it here yet.
259 * The Main function will do it after it's done handling the startup
260 * data.
261 */
263
264 MyPMChildSlot = child_slot;
265 if (client_sock)
266 {
268 memcpy(MyClientSocket, client_sock, sizeof(ClientSocket));
269 }
270
271 /*
272 * Run the appropriate Main function
273 */
274 child_process_kinds[child_type].main_fn(startup_data, startup_data_len);
275 pg_unreachable(); /* main_fn never returns */
276 }
277#endif /* EXEC_BACKEND */
278 return pid;
279}
#define pg_unreachable()
Definition: c.h:318
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:49
int MyPMChildSlot
Definition: globals.c:53
bool IsUnderPostmaster
Definition: globals.c:119
bool IsPostmasterEnvironment
Definition: globals.c:118
static child_process_kind child_process_kinds[]
MemoryContext TopMemoryContext
Definition: mcxt.c:149
void InitPostmasterChild(void)
Definition: miscinit.c:96
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:1842
void(* main_fn)(char *startup_data, size_t startup_data_len) pg_attribute_noreturn()
void PGSharedMemoryDetach(void)
Definition: sysv_shmem.c:970

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

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

◆ PostmasterChildName()

const char * PostmasterChildName ( BackendType  child_type)

Definition at line 209 of file launch_backend.c.

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

References child_process_kinds, and child_process_kind::name.

Referenced by AssignPostmasterChildSlot(), and StartChildProcess().

◆ PostmasterMain()

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

Definition at line 483 of file postmaster.c.

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

4275{
4276 dlist_iter iter;
4277 PMChild *bp;
4278
4280 {
4281 bp = dlist_container(PMChild, elem, iter.cur);
4282 if (bp->pid == pid)
4283 {
4284 bp->bgworker_notify = true;
4285 return true;
4286 }
4287 }
4288 return false;
4289}

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

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

Variable Documentation

◆ ActiveChildList

◆ AuthenticationTimeout

PGDLLIMPORT int AuthenticationTimeout
extern

Definition at line 237 of file postmaster.c.

Referenced by BackendInitialize(), and PerformAuthentication().

◆ bonjour_name

PGDLLIMPORT char* bonjour_name
extern

Definition at line 243 of file postmaster.c.

Referenced by PostmasterMain().

◆ ClientAuthInProgress

◆ enable_bonjour

PGDLLIMPORT bool enable_bonjour
extern

Definition at line 242 of file postmaster.c.

Referenced by PostmasterMain().

◆ EnableSSL

PGDLLIMPORT bool EnableSSL
extern

◆ ListenAddresses

PGDLLIMPORT char* ListenAddresses
extern

Definition at line 205 of file postmaster.c.

Referenced by PostmasterMain().

◆ LoadedSSL

◆ Log_connections

PGDLLIMPORT bool Log_connections
extern

◆ log_hostname

PGDLLIMPORT bool log_hostname
extern

Definition at line 239 of file postmaster.c.

Referenced by BackendInitialize().

◆ MyClientSocket

PGDLLIMPORT struct ClientSocket* MyClientSocket
extern

Definition at line 49 of file globals.c.

Referenced by BackendMain(), and postmaster_child_launch().

◆ postmaster_alive_fds

◆ PostPortNumber

PGDLLIMPORT int PostPortNumber
extern

Definition at line 199 of file postmaster.c.

Referenced by CreateLockFile(), and PostmasterMain().

◆ PreAuthDelay

PGDLLIMPORT int PreAuthDelay
extern

Definition at line 236 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 245 of file postmaster.c.

Referenced by PostmasterStateMachine().

◆ ReservedConnections

PGDLLIMPORT int ReservedConnections
extern

Definition at line 226 of file postmaster.c.

Referenced by InitPostgres(), and PostmasterMain().

◆ restart_after_crash

PGDLLIMPORT bool restart_after_crash
extern

Definition at line 244 of file postmaster.c.

Referenced by PostmasterStateMachine().

◆ send_abort_for_crash

PGDLLIMPORT bool send_abort_for_crash
extern

Definition at line 253 of file postmaster.c.

Referenced by HandleFatalError().

◆ send_abort_for_kill

PGDLLIMPORT bool send_abort_for_kill
extern

Definition at line 254 of file postmaster.c.

Referenced by ServerLoop().

◆ SuperuserReservedConnections

PGDLLIMPORT int SuperuserReservedConnections
extern

Definition at line 225 of file postmaster.c.

Referenced by InitPostgres(), and PostmasterMain().

◆ Unix_socket_directories

PGDLLIMPORT char* Unix_socket_directories
extern

Definition at line 202 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().