PostgreSQL Source Code  git master
postinit.c File Reference
#include "postgres.h"
#include <ctype.h>
#include <fcntl.h>
#include <unistd.h>
#include "access/genam.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/session.h"
#include "access/tableam.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "access/xloginsert.h"
#include "catalog/namespace.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_database.h"
#include "catalog/pg_db_role_setting.h"
#include "catalog/pg_tablespace.h"
#include "libpq/auth.h"
#include "libpq/libpq-be.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "postmaster/autovacuum.h"
#include "postmaster/postmaster.h"
#include "replication/slot.h"
#include "replication/slotsync.h"
#include "replication/walsender.h"
#include "storage/bufmgr.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/lmgr.h"
#include "storage/proc.h"
#include "storage/procarray.h"
#include "storage/procsignal.h"
#include "storage/sinvaladt.h"
#include "storage/smgr.h"
#include "storage/sync.h"
#include "tcop/tcopprot.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/guc_hooks.h"
#include "utils/memutils.h"
#include "utils/pg_locale.h"
#include "utils/portal.h"
#include "utils/ps_status.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/timeout.h"
Include dependency graph for postinit.c:

Go to the source code of this file.

Functions

static HeapTuple GetDatabaseTuple (const char *dbname)
 
static HeapTuple GetDatabaseTupleByOid (Oid dboid)
 
static void PerformAuthentication (Port *port)
 
static void CheckMyDatabase (const char *name, bool am_superuser, bool override_allow_connections)
 
static void ShutdownPostgres (int code, Datum arg)
 
static void StatementTimeoutHandler (void)
 
static void LockTimeoutHandler (void)
 
static void IdleInTransactionSessionTimeoutHandler (void)
 
static void TransactionTimeoutHandler (void)
 
static void IdleSessionTimeoutHandler (void)
 
static void IdleStatsUpdateTimeoutHandler (void)
 
static void ClientCheckTimeoutHandler (void)
 
static bool ThereIsAtLeastOneRole (void)
 
static void process_startup_options (Port *port, bool am_superuser)
 
static void process_settings (Oid databaseid, Oid roleid)
 
void pg_split_opts (char **argv, int *argcp, const char *optstr)
 
void InitializeMaxBackends (void)
 
void BaseInit (void)
 
void InitPostgres (const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
 

Function Documentation

◆ BaseInit()

void BaseInit ( void  )

Definition at line 569 of file postinit.c.

570 {
571  Assert(MyProc != NULL);
572 
573  /*
574  * Initialize our input/output/debugging file descriptors.
575  */
576  DebugFileOpen();
577 
578  /*
579  * Initialize file access. Done early so other subsystems can access
580  * files.
581  */
582  InitFileAccess();
583 
584  /*
585  * Initialize statistics reporting. This needs to happen early to ensure
586  * that pgstat's shutdown callback runs after the shutdown callbacks of
587  * all subsystems that can produce stats (like e.g. transaction commits
588  * can).
589  */
591 
592  /* Do local initialization of storage and buffer managers */
593  InitSync();
594  smgrinit();
596 
597  /*
598  * Initialize temporary file access after pgstat, so that the temporary
599  * file shutdown hook can report temporary file statistics.
600  */
602 
603  /*
604  * Initialize local buffers for WAL record construction, in case we ever
605  * try to insert XLOG.
606  */
607  InitXLogInsert();
608 
609  /* Initialize lock manager's local structs */
611 
612  /*
613  * Initialize replication slots after pgstat. The exit hook might need to
614  * drop ephemeral slots, which in turn triggers stats reporting.
615  */
617 }
void InitBufferManagerAccess(void)
Definition: bufmgr.c:3558
#define Assert(condition)
Definition: c.h:858
void DebugFileOpen(void)
Definition: elog.c:2108
void InitFileAccess(void)
Definition: fd.c:903
void InitTemporaryFileAccess(void)
Definition: fd.c:933
void InitLockManagerAccess(void)
Definition: lock.c:451
void pgstat_initialize(void)
Definition: pgstat.c:607
void ReplicationSlotInitialize(void)
Definition: slot.c:224
void smgrinit(void)
Definition: smgr.c:154
PGPROC * MyProc
Definition: proc.c:67
void InitSync(void)
Definition: sync.c:124
void InitXLogInsert(void)
Definition: xloginsert.c:1348

References Assert, DebugFileOpen(), InitBufferManagerAccess(), InitFileAccess(), InitLockManagerAccess(), InitSync(), InitTemporaryFileAccess(), InitXLogInsert(), MyProc, pgstat_initialize(), ReplicationSlotInitialize(), and smgrinit().

Referenced by AutoVacWorkerMain(), AuxiliaryProcessMainCommon(), BackgroundWorkerMain(), BootstrapModeMain(), PostgresMain(), and ReplSlotSyncWorkerMain().

◆ CheckMyDatabase()

static void CheckMyDatabase ( const char *  name,
bool  am_superuser,
bool  override_allow_connections 
)
static

Definition at line 313 of file postinit.c.

314 {
315  HeapTuple tup;
316  Form_pg_database dbform;
317  Datum datum;
318  bool isnull;
319  char *collate;
320  char *ctype;
321 
322  /* Fetch our pg_database row normally, via syscache */
323  tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
324  if (!HeapTupleIsValid(tup))
325  elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
326  dbform = (Form_pg_database) GETSTRUCT(tup);
327 
328  /* This recheck is strictly paranoia */
329  if (strcmp(name, NameStr(dbform->datname)) != 0)
330  ereport(FATAL,
331  (errcode(ERRCODE_UNDEFINED_DATABASE),
332  errmsg("database \"%s\" has disappeared from pg_database",
333  name),
334  errdetail("Database OID %u now seems to belong to \"%s\".",
335  MyDatabaseId, NameStr(dbform->datname))));
336 
337  /*
338  * Check permissions to connect to the database.
339  *
340  * These checks are not enforced when in standalone mode, so that there is
341  * a way to recover from disabling all access to all databases, for
342  * example "UPDATE pg_database SET datallowconn = false;".
343  *
344  * We do not enforce them for autovacuum worker processes either.
345  */
347  {
348  /*
349  * Check that the database is currently allowing connections.
350  */
351  if (!dbform->datallowconn && !override_allow_connections)
352  ereport(FATAL,
353  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
354  errmsg("database \"%s\" is not currently accepting connections",
355  name)));
356 
357  /*
358  * Check privilege to connect to the database. (The am_superuser test
359  * is redundant, but since we have the flag, might as well check it
360  * and save a few cycles.)
361  */
362  if (!am_superuser &&
363  object_aclcheck(DatabaseRelationId, MyDatabaseId, GetUserId(),
365  ereport(FATAL,
366  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
367  errmsg("permission denied for database \"%s\"", name),
368  errdetail("User does not have CONNECT privilege.")));
369 
370  /*
371  * Check connection limit for this database.
372  *
373  * There is a race condition here --- we create our PGPROC before
374  * checking for other PGPROCs. If two backends did this at about the
375  * same time, they might both think they were over the limit, while
376  * ideally one should succeed and one fail. Getting that to work
377  * exactly seems more trouble than it is worth, however; instead we
378  * just document that the connection limit is approximate.
379  */
380  if (dbform->datconnlimit >= 0 &&
381  !am_superuser &&
382  CountDBConnections(MyDatabaseId) > dbform->datconnlimit)
383  ereport(FATAL,
384  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
385  errmsg("too many connections for database \"%s\"",
386  name)));
387  }
388 
389  /*
390  * OK, we're golden. Next to-do item is to save the encoding info out of
391  * the pg_database tuple.
392  */
393  SetDatabaseEncoding(dbform->encoding);
394  /* Record it as a GUC internal option, too */
395  SetConfigOption("server_encoding", GetDatabaseEncodingName(),
397  /* If we have no other source of client_encoding, use server encoding */
398  SetConfigOption("client_encoding", GetDatabaseEncodingName(),
400 
401  /* assign locale variables */
402  datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datcollate);
403  collate = TextDatumGetCString(datum);
404  datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datctype);
405  ctype = TextDatumGetCString(datum);
406 
407  if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
408  ereport(FATAL,
409  (errmsg("database locale is incompatible with operating system"),
410  errdetail("The database was initialized with LC_COLLATE \"%s\", "
411  " which is not recognized by setlocale().", collate),
412  errhint("Recreate the database with another locale or install the missing locale.")));
413 
414  if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
415  ereport(FATAL,
416  (errmsg("database locale is incompatible with operating system"),
417  errdetail("The database was initialized with LC_CTYPE \"%s\", "
418  " which is not recognized by setlocale().", ctype),
419  errhint("Recreate the database with another locale or install the missing locale.")));
420 
421  if (strcmp(ctype, "C") == 0 ||
422  strcmp(ctype, "POSIX") == 0)
423  database_ctype_is_c = true;
424 
426 
427  /*
428  * Check collation version. See similar code in
429  * pg_newlocale_from_collation(). Note that here we warn instead of error
430  * in any case, so that we don't prevent connecting.
431  */
432  datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_datcollversion,
433  &isnull);
434  if (!isnull)
435  {
436  char *actual_versionstr;
437  char *collversionstr;
438  char *locale;
439 
440  collversionstr = TextDatumGetCString(datum);
441 
442  if (dbform->datlocprovider == COLLPROVIDER_LIBC)
443  locale = collate;
444  else
445  {
446  datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datlocale);
447  locale = TextDatumGetCString(datum);
448  }
449 
450  actual_versionstr = get_collation_actual_version(dbform->datlocprovider, locale);
451  if (!actual_versionstr)
452  /* should not happen */
453  elog(WARNING,
454  "database \"%s\" has no actual collation version, but a version was recorded",
455  name);
456  else if (strcmp(actual_versionstr, collversionstr) != 0)
458  (errmsg("database \"%s\" has a collation version mismatch",
459  name),
460  errdetail("The database was created using collation version %s, "
461  "but the operating system provides version %s.",
462  collversionstr, actual_versionstr),
463  errhint("Rebuild all objects in this database that use the default collation and run "
464  "ALTER DATABASE %s REFRESH COLLATION VERSION, "
465  "or build PostgreSQL with the right library version.",
467  }
468 
469  ReleaseSysCache(tup);
470 }
@ ACLCHECK_OK
Definition: acl.h:183
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:3886
#define TextDatumGetCString(d)
Definition: builtins.h:98
#define NameStr(name)
Definition: c.h:746
int errdetail(const char *fmt,...)
Definition: elog.c:1203
int errhint(const char *fmt,...)
Definition: elog.c:1317
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define FATAL
Definition: elog.h:41
#define WARNING
Definition: elog.h:36
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
#define ereport(elevel,...)
Definition: elog.h:149
bool IsUnderPostmaster
Definition: globals.c:119
Oid MyDatabaseId
Definition: globals.c:93
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4291
@ PGC_S_DYNAMIC_DEFAULT
Definition: guc.h:110
@ PGC_INTERNAL
Definition: guc.h:69
@ PGC_BACKEND
Definition: guc.h:73
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
static char * locale
Definition: initdb.c:140
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1267
void SetDatabaseEncoding(int encoding)
Definition: mbutils.c:1161
#define AmAutoVacuumWorkerProcess()
Definition: miscadmin.h:372
Oid GetUserId(void)
Definition: miscinit.c:514
#define ACL_CONNECT
Definition: parsenodes.h:87
FormData_pg_database * Form_pg_database
Definition: pg_database.h:96
bool database_ctype_is_c
Definition: pg_locale.c:118
char * get_collation_actual_version(char collprovider, const char *collcollate)
Definition: pg_locale.c:1659
char * pg_perm_setlocale(int category, const char *locale)
Definition: pg_locale.c:236
void init_database_collation(void)
Definition: pg_locale.c:1422
uintptr_t Datum
Definition: postgres.h:64
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
int CountDBConnections(Oid databaseid)
Definition: procarray.c:3633
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:12835
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:266
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:218
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:479
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition: syscache.c:510
const char * name

References ACL_CONNECT, ACLCHECK_OK, AmAutoVacuumWorkerProcess, CountDBConnections(), database_ctype_is_c, elog, ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, FATAL, get_collation_actual_version(), GetDatabaseEncodingName(), GETSTRUCT, GetUserId(), HeapTupleIsValid, init_database_collation(), IsUnderPostmaster, locale, MyDatabaseId, name, NameStr, object_aclcheck(), ObjectIdGetDatum(), pg_perm_setlocale(), PGC_BACKEND, PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT, quote_identifier(), ReleaseSysCache(), SearchSysCache1(), SetConfigOption(), SetDatabaseEncoding(), SysCacheGetAttr(), SysCacheGetAttrNotNull(), TextDatumGetCString, and WARNING.

Referenced by InitPostgres().

◆ ClientCheckTimeoutHandler()

static void ClientCheckTimeoutHandler ( void  )
static

Definition at line 1368 of file postinit.c.

1369 {
1371  InterruptPending = true;
1372  SetLatch(MyLatch);
1373 }
volatile sig_atomic_t InterruptPending
Definition: globals.c:31
struct Latch * MyLatch
Definition: globals.c:62
volatile sig_atomic_t CheckClientConnectionPending
Definition: globals.c:34
void SetLatch(Latch *latch)
Definition: latch.c:632

References CheckClientConnectionPending, InterruptPending, MyLatch, and SetLatch().

Referenced by InitPostgres().

◆ GetDatabaseTuple()

static HeapTuple GetDatabaseTuple ( const char *  dbname)
static

Definition at line 101 of file postinit.c.

102 {
103  HeapTuple tuple;
104  Relation relation;
105  SysScanDesc scan;
106  ScanKeyData key[1];
107 
108  /*
109  * form a scan key
110  */
111  ScanKeyInit(&key[0],
112  Anum_pg_database_datname,
113  BTEqualStrategyNumber, F_NAMEEQ,
115 
116  /*
117  * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
118  * built the critical shared relcache entries (i.e., we're starting up
119  * without a shared relcache cache file).
120  */
121  relation = table_open(DatabaseRelationId, AccessShareLock);
122  scan = systable_beginscan(relation, DatabaseNameIndexId,
124  NULL,
125  1, key);
126 
127  tuple = systable_getnext(scan);
128 
129  /* Must copy tuple before releasing buffer */
130  if (HeapTupleIsValid(tuple))
131  tuple = heap_copytuple(tuple);
132 
133  /* all done */
134  systable_endscan(scan);
135  table_close(relation, AccessShareLock);
136 
137  return tuple;
138 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:602
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:509
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:385
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:776
#define AccessShareLock
Definition: lockdefs.h:36
static Datum CStringGetDatum(const char *X)
Definition: postgres.h:350
bool criticalSharedRelcachesBuilt
Definition: relcache.c:146
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define BTEqualStrategyNumber
Definition: stratnum.h:31
char * dbname
Definition: streamutil.c:52
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40

References AccessShareLock, BTEqualStrategyNumber, criticalSharedRelcachesBuilt, CStringGetDatum(), dbname, heap_copytuple(), HeapTupleIsValid, sort-test::key, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), and table_open().

Referenced by InitPostgres().

◆ GetDatabaseTupleByOid()

static HeapTuple GetDatabaseTupleByOid ( Oid  dboid)
static

Definition at line 144 of file postinit.c.

145 {
146  HeapTuple tuple;
147  Relation relation;
148  SysScanDesc scan;
149  ScanKeyData key[1];
150 
151  /*
152  * form a scan key
153  */
154  ScanKeyInit(&key[0],
155  Anum_pg_database_oid,
156  BTEqualStrategyNumber, F_OIDEQ,
157  ObjectIdGetDatum(dboid));
158 
159  /*
160  * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
161  * built the critical shared relcache entries (i.e., we're starting up
162  * without a shared relcache cache file).
163  */
164  relation = table_open(DatabaseRelationId, AccessShareLock);
165  scan = systable_beginscan(relation, DatabaseOidIndexId,
167  NULL,
168  1, key);
169 
170  tuple = systable_getnext(scan);
171 
172  /* Must copy tuple before releasing buffer */
173  if (HeapTupleIsValid(tuple))
174  tuple = heap_copytuple(tuple);
175 
176  /* all done */
177  systable_endscan(scan);
178  table_close(relation, AccessShareLock);
179 
180  return tuple;
181 }

References AccessShareLock, BTEqualStrategyNumber, criticalSharedRelcachesBuilt, heap_copytuple(), HeapTupleIsValid, sort-test::key, ObjectIdGetDatum(), ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), and table_open().

Referenced by InitPostgres().

◆ IdleInTransactionSessionTimeoutHandler()

static void IdleInTransactionSessionTimeoutHandler ( void  )
static

Definition at line 1344 of file postinit.c.

1345 {
1347  InterruptPending = true;
1348  SetLatch(MyLatch);
1349 }
volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
Definition: globals.c:36

References IdleInTransactionSessionTimeoutPending, InterruptPending, MyLatch, and SetLatch().

Referenced by InitPostgres().

◆ IdleSessionTimeoutHandler()

static void IdleSessionTimeoutHandler ( void  )
static

Definition at line 1352 of file postinit.c.

1353 {
1355  InterruptPending = true;
1356  SetLatch(MyLatch);
1357 }
volatile sig_atomic_t IdleSessionTimeoutPending
Definition: globals.c:38

References IdleSessionTimeoutPending, InterruptPending, MyLatch, and SetLatch().

Referenced by InitPostgres().

◆ IdleStatsUpdateTimeoutHandler()

static void IdleStatsUpdateTimeoutHandler ( void  )
static

Definition at line 1360 of file postinit.c.

1361 {
1363  InterruptPending = true;
1364  SetLatch(MyLatch);
1365 }
volatile sig_atomic_t IdleStatsUpdateTimeoutPending
Definition: globals.c:41

References IdleStatsUpdateTimeoutPending, InterruptPending, MyLatch, and SetLatch().

Referenced by InitPostgres().

◆ InitializeMaxBackends()

void InitializeMaxBackends ( void  )

Definition at line 542 of file postinit.c.

543 {
544  Assert(MaxBackends == 0);
545 
546  /* the extra unit accounts for the autovacuum launcher */
549 
551  ereport(ERROR,
552  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
553  errmsg("too many server processes configured"),
554  errdetail("\"max_connections\" (%d) plus \"autovacuum_max_workers\" (%d) plus \"max_worker_processes\" (%d) plus \"max_wal_senders\" (%d) must be less than %d.",
557  MAX_BACKENDS)));
558 }
int autovacuum_max_workers
Definition: autovacuum.c:118
int MaxConnections
Definition: globals.c:142
int MaxBackends
Definition: globals.c:145
int max_worker_processes
Definition: globals.c:143
#define MAX_BACKENDS
Definition: postmaster.h:92
int max_wal_senders
Definition: walsender.c:121

References Assert, autovacuum_max_workers, ereport, errcode(), errdetail(), errmsg(), ERROR, MAX_BACKENDS, max_wal_senders, max_worker_processes, MaxBackends, and MaxConnections.

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

◆ InitPostgres()

void InitPostgres ( const char *  in_dbname,
Oid  dboid,
const char *  username,
Oid  useroid,
bits32  flags,
char *  out_dbname 
)

Definition at line 663 of file postinit.c.

667 {
668  bool bootstrap = IsBootstrapProcessingMode();
669  bool am_superuser;
670  char *fullpath;
671  char dbname[NAMEDATALEN];
672  int nfree = 0;
673 
674  elog(DEBUG3, "InitPostgres");
675 
676  /*
677  * Add my PGPROC struct to the ProcArray.
678  *
679  * Once I have done this, I am visible to other backends!
680  */
682 
683  /*
684  * Initialize my entry in the shared-invalidation manager's array of
685  * per-backend data.
686  */
687  SharedInvalBackendInit(false);
688 
690 
691  /*
692  * Also set up timeout handlers needed for backend operation. We need
693  * these in every case except bootstrap.
694  */
695  if (!bootstrap)
696  {
707  }
708 
709  /*
710  * If this is either a bootstrap process or a standalone backend, start up
711  * the XLOG machinery, and register to have it closed down at exit. In
712  * other cases, the startup process is responsible for starting up the
713  * XLOG machinery, and the checkpointer for closing it down.
714  */
715  if (!IsUnderPostmaster)
716  {
717  /*
718  * We don't yet have an aux-process resource owner, but StartupXLOG
719  * and ShutdownXLOG will need one. Hence, create said resource owner
720  * (and register a callback to clean it up after ShutdownXLOG runs).
721  */
723 
724  StartupXLOG();
725  /* Release (and warn about) any buffer pins leaked in StartupXLOG */
727  /* Reset CurrentResourceOwner to nothing for the moment */
728  CurrentResourceOwner = NULL;
729 
730  /*
731  * Use before_shmem_exit() so that ShutdownXLOG() can rely on DSM
732  * segments etc to work (which in turn is required for pgstats).
733  */
736  }
737 
738  /*
739  * Initialize the relation cache and the system catalog caches. Note that
740  * no catalog access happens here; we only set up the hashtable structure.
741  * We must do this before starting a transaction because transaction abort
742  * would try to touch these hashtables.
743  */
746  InitPlanCache();
747 
748  /* Initialize portal manager */
750 
751  /* Initialize status reporting */
752  pgstat_beinit();
753 
754  /*
755  * Load relcache entries for the shared system catalogs. This must create
756  * at least entries for pg_database and catalogs used for authentication.
757  */
759 
760  /*
761  * Set up process-exit callback to do pre-shutdown cleanup. This is the
762  * one of the first before_shmem_exit callbacks we register; thus, this
763  * will be one the last things we do before low-level modules like the
764  * buffer manager begin to close down. We need to have this in place
765  * before we begin our first transaction --- if we fail during the
766  * initialization transaction, as is entirely possible, we need the
767  * AbortTransaction call to clean up.
768  */
770 
771  /* The autovacuum launcher is done here */
773  {
774  /* report this backend in the PgBackendStatus array */
775  pgstat_bestart();
776 
777  return;
778  }
779 
780  /*
781  * Start a new transaction here before first access to db, and get a
782  * snapshot. We don't have a use for the snapshot itself, but we're
783  * interested in the secondary effect that it sets RecentGlobalXmin. (This
784  * is critical for anything that reads heap pages, because HOT may decide
785  * to prune them even if the process doesn't attempt to modify any
786  * tuples.)
787  *
788  * FIXME: This comment is inaccurate / the code buggy. A snapshot that is
789  * not pushed/active does not reliably prevent HOT pruning (->xmin could
790  * e.g. be cleared when cache invalidations are processed).
791  */
792  if (!bootstrap)
793  {
794  /* statement_timestamp must be set for timeouts to work correctly */
797 
798  /*
799  * transaction_isolation will have been set to the default by the
800  * above. If the default is "serializable", and we are in hot
801  * standby, we will fail if we don't change it to something lower.
802  * Fortunately, "read committed" is plenty good enough.
803  */
805 
806  (void) GetTransactionSnapshot();
807  }
808 
809  /*
810  * Perform client authentication if necessary, then figure out our
811  * postgres user ID, and see if we are a superuser.
812  *
813  * In standalone mode, autovacuum worker processes and slot sync worker
814  * process, we use a fixed ID, otherwise we figure it out from the
815  * authenticated user name.
816  */
818  {
820  am_superuser = true;
821  }
822  else if (!IsUnderPostmaster)
823  {
825  am_superuser = true;
826  if (!ThereIsAtLeastOneRole())
828  (errcode(ERRCODE_UNDEFINED_OBJECT),
829  errmsg("no roles are defined in this database system"),
830  errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
831  username != NULL ? username : "postgres")));
832  }
833  else if (AmBackgroundWorkerProcess())
834  {
835  if (username == NULL && !OidIsValid(useroid))
836  {
838  am_superuser = true;
839  }
840  else
841  {
843  (flags & INIT_PG_OVERRIDE_ROLE_LOGIN) != 0);
844  am_superuser = superuser();
845  }
846  }
847  else
848  {
849  /* normal multiuser case */
850  Assert(MyProcPort != NULL);
852  InitializeSessionUserId(username, useroid, false);
853  /* ensure that auth_method is actually valid, aka authn_id is not NULL */
857  am_superuser = superuser();
858  }
859 
860  /*
861  * Binary upgrades only allowed super-user connections
862  */
863  if (IsBinaryUpgrade && !am_superuser)
864  {
865  ereport(FATAL,
866  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
867  errmsg("must be superuser to connect in binary upgrade mode")));
868  }
869 
870  /*
871  * The last few connection slots are reserved for superusers and roles
872  * with privileges of pg_use_reserved_connections. Replication
873  * connections are drawn from slots reserved with max_wal_senders and are
874  * not limited by max_connections, superuser_reserved_connections, or
875  * reserved_connections.
876  *
877  * Note: At this point, the new backend has already claimed a proc struct,
878  * so we must check whether the number of free slots is strictly less than
879  * the reserved connection limits.
880  */
881  if (!am_superuser && !am_walsender &&
884  {
885  if (nfree < SuperuserReservedConnections)
886  ereport(FATAL,
887  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
888  errmsg("remaining connection slots are reserved for roles with the %s attribute",
889  "SUPERUSER")));
890 
891  if (!has_privs_of_role(GetUserId(), ROLE_PG_USE_RESERVED_CONNECTIONS))
892  ereport(FATAL,
893  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
894  errmsg("remaining connection slots are reserved for roles with privileges of the \"%s\" role",
895  "pg_use_reserved_connections")));
896  }
897 
898  /* Check replication permissions needed for walsender processes. */
899  if (am_walsender)
900  {
901  Assert(!bootstrap);
902 
904  ereport(FATAL,
905  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
906  errmsg("permission denied to start WAL sender"),
907  errdetail("Only roles with the %s attribute may start a WAL sender process.",
908  "REPLICATION")));
909  }
910 
911  /*
912  * If this is a plain walsender only supporting physical replication, we
913  * don't want to connect to any particular database. Just finish the
914  * backend startup by processing any options from the startup packet, and
915  * we're done.
916  */
918  {
919  /* process any options passed in the startup packet */
920  if (MyProcPort != NULL)
921  process_startup_options(MyProcPort, am_superuser);
922 
923  /* Apply PostAuthDelay as soon as we've read all options */
924  if (PostAuthDelay > 0)
925  pg_usleep(PostAuthDelay * 1000000L);
926 
927  /* initialize client encoding */
929 
930  /* report this backend in the PgBackendStatus array */
931  pgstat_bestart();
932 
933  /* close the transaction we started above */
935 
936  return;
937  }
938 
939  /*
940  * Set up the global variables holding database id and default tablespace.
941  * But note we won't actually try to touch the database just yet.
942  *
943  * We take a shortcut in the bootstrap case, otherwise we have to look up
944  * the db's entry in pg_database.
945  */
946  if (bootstrap)
947  {
948  dboid = Template1DbOid;
949  MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
950  }
951  else if (in_dbname != NULL)
952  {
953  HeapTuple tuple;
954  Form_pg_database dbform;
955 
956  tuple = GetDatabaseTuple(in_dbname);
957  if (!HeapTupleIsValid(tuple))
958  ereport(FATAL,
959  (errcode(ERRCODE_UNDEFINED_DATABASE),
960  errmsg("database \"%s\" does not exist", in_dbname)));
961  dbform = (Form_pg_database) GETSTRUCT(tuple);
962  dboid = dbform->oid;
963  }
964  else if (!OidIsValid(dboid))
965  {
966  /*
967  * If this is a background worker not bound to any particular
968  * database, we're done now. Everything that follows only makes sense
969  * if we are bound to a specific database. We do need to close the
970  * transaction we started before returning.
971  */
972  if (!bootstrap)
973  {
974  pgstat_bestart();
976  }
977  return;
978  }
979 
980  /*
981  * Now, take a writer's lock on the database we are trying to connect to.
982  * If there is a concurrently running DROP DATABASE on that database, this
983  * will block us until it finishes (and has committed its update of
984  * pg_database).
985  *
986  * Note that the lock is not held long, only until the end of this startup
987  * transaction. This is OK since we will advertise our use of the
988  * database in the ProcArray before dropping the lock (in fact, that's the
989  * next thing to do). Anyone trying a DROP DATABASE after this point will
990  * see us in the array once they have the lock. Ordering is important for
991  * this because we don't want to advertise ourselves as being in this
992  * database until we have the lock; otherwise we create what amounts to a
993  * deadlock with CountOtherDBBackends().
994  *
995  * Note: use of RowExclusiveLock here is reasonable because we envision
996  * our session as being a concurrent writer of the database. If we had a
997  * way of declaring a session as being guaranteed-read-only, we could use
998  * AccessShareLock for such sessions and thereby not conflict against
999  * CREATE DATABASE.
1000  */
1001  if (!bootstrap)
1002  LockSharedObject(DatabaseRelationId, dboid, 0, RowExclusiveLock);
1003 
1004  /*
1005  * Recheck pg_database to make sure the target database hasn't gone away.
1006  * If there was a concurrent DROP DATABASE, this ensures we will die
1007  * cleanly without creating a mess.
1008  */
1009  if (!bootstrap)
1010  {
1011  HeapTuple tuple;
1012  Form_pg_database datform;
1013 
1014  tuple = GetDatabaseTupleByOid(dboid);
1015  if (HeapTupleIsValid(tuple))
1016  datform = (Form_pg_database) GETSTRUCT(tuple);
1017 
1018  if (!HeapTupleIsValid(tuple) ||
1019  (in_dbname && namestrcmp(&datform->datname, in_dbname)))
1020  {
1021  if (in_dbname)
1022  ereport(FATAL,
1023  (errcode(ERRCODE_UNDEFINED_DATABASE),
1024  errmsg("database \"%s\" does not exist", in_dbname),
1025  errdetail("It seems to have just been dropped or renamed.")));
1026  else
1027  ereport(FATAL,
1028  (errcode(ERRCODE_UNDEFINED_DATABASE),
1029  errmsg("database %u does not exist", dboid)));
1030  }
1031 
1032  strlcpy(dbname, NameStr(datform->datname), sizeof(dbname));
1033 
1034  if (database_is_invalid_form(datform))
1035  {
1036  ereport(FATAL,
1037  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1038  errmsg("cannot connect to invalid database \"%s\"", dbname),
1039  errhint("Use DROP DATABASE to drop invalid databases."));
1040  }
1041 
1042  MyDatabaseTableSpace = datform->dattablespace;
1043  MyDatabaseHasLoginEventTriggers = datform->dathasloginevt;
1044  /* pass the database name back to the caller */
1045  if (out_dbname)
1046  strcpy(out_dbname, dbname);
1047  }
1048 
1049  /*
1050  * Now that we rechecked, we are certain to be connected to a database and
1051  * thus can set MyDatabaseId.
1052  *
1053  * It is important that MyDatabaseId only be set once we are sure that the
1054  * target database can no longer be concurrently dropped or renamed. For
1055  * example, without this guarantee, pgstat_update_dbstats() could create
1056  * entries for databases that were just dropped in the pgstat shutdown
1057  * callback, which could confuse other code paths like the autovacuum
1058  * scheduler.
1059  */
1060  MyDatabaseId = dboid;
1061 
1062  /*
1063  * Now we can mark our PGPROC entry with the database ID.
1064  *
1065  * We assume this is an atomic store so no lock is needed; though actually
1066  * things would work fine even if it weren't atomic. Anyone searching the
1067  * ProcArray for this database's ID should hold the database lock, so they
1068  * would not be executing concurrently with this store. A process looking
1069  * for another database's ID could in theory see a chance match if it read
1070  * a partially-updated databaseId value; but as long as all such searches
1071  * wait and retry, as in CountOtherDBBackends(), they will certainly see
1072  * the correct value on their next try.
1073  */
1075 
1076  /*
1077  * We established a catalog snapshot while reading pg_authid and/or
1078  * pg_database; but until we have set up MyDatabaseId, we won't react to
1079  * incoming sinval messages for unshared catalogs, so we won't realize it
1080  * if the snapshot has been invalidated. Assume it's no good anymore.
1081  */
1083 
1084  /*
1085  * Now we should be able to access the database directory safely. Verify
1086  * it's there and looks reasonable.
1087  */
1089 
1090  if (!bootstrap)
1091  {
1092  if (access(fullpath, F_OK) == -1)
1093  {
1094  if (errno == ENOENT)
1095  ereport(FATAL,
1096  (errcode(ERRCODE_UNDEFINED_DATABASE),
1097  errmsg("database \"%s\" does not exist",
1098  dbname),
1099  errdetail("The database subdirectory \"%s\" is missing.",
1100  fullpath)));
1101  else
1102  ereport(FATAL,
1104  errmsg("could not access directory \"%s\": %m",
1105  fullpath)));
1106  }
1107 
1108  ValidatePgVersion(fullpath);
1109  }
1110 
1111  SetDatabasePath(fullpath);
1112  pfree(fullpath);
1113 
1114  /*
1115  * It's now possible to do real access to the system catalogs.
1116  *
1117  * Load relcache entries for the system catalogs. This must create at
1118  * least the minimum set of "nailed-in" cache entries.
1119  */
1121 
1122  /* set up ACL framework (so CheckMyDatabase can check permissions) */
1123  initialize_acl();
1124 
1125  /*
1126  * Re-read the pg_database row for our database, check permissions and set
1127  * up database-specific GUC settings. We can't do this until all the
1128  * database-access infrastructure is up. (Also, it wants to know if the
1129  * user is a superuser, so the above stuff has to happen first.)
1130  */
1131  if (!bootstrap)
1132  CheckMyDatabase(dbname, am_superuser,
1133  (flags & INIT_PG_OVERRIDE_ALLOW_CONNS) != 0);
1134 
1135  /*
1136  * Now process any command-line switches and any additional GUC variable
1137  * settings passed in the startup packet. We couldn't do this before
1138  * because we didn't know if client is a superuser.
1139  */
1140  if (MyProcPort != NULL)
1141  process_startup_options(MyProcPort, am_superuser);
1142 
1143  /* Process pg_db_role_setting options */
1145 
1146  /* Apply PostAuthDelay as soon as we've read all options */
1147  if (PostAuthDelay > 0)
1148  pg_usleep(PostAuthDelay * 1000000L);
1149 
1150  /*
1151  * Initialize various default states that can't be set up until we've
1152  * selected the active user and gotten the right GUC settings.
1153  */
1154 
1155  /* set default namespace search path */
1157 
1158  /* initialize client encoding */
1160 
1161  /* Initialize this backend's session state. */
1163 
1164  /*
1165  * If this is an interactive session, load any libraries that should be
1166  * preloaded at backend start. Since those are determined by GUCs, this
1167  * can't happen until GUC settings are complete, but we want it to happen
1168  * during the initial transaction in case anything that requires database
1169  * access needs to be done.
1170  */
1171  if ((flags & INIT_PG_LOAD_SESSION_LIBS) != 0)
1173 
1174  /* report this backend in the PgBackendStatus array */
1175  if (!bootstrap)
1176  pgstat_bestart();
1177 
1178  /* close the transaction we started above */
1179  if (!bootstrap)
1181 }
void initialize_acl(void)
Definition: acl.c:5024
bool has_privs_of_role(Oid member, Oid role)
Definition: acl.c:5268
void pgstat_beinit(void)
void pgstat_bestart(void)
#define OidIsValid(objectId)
Definition: c.h:775
bool database_is_invalid_form(Form_pg_database datform)
Definition: dbcommands.c:3208
int errcode_for_file_access(void)
Definition: elog.c:876
#define DEBUG3
Definition: elog.h:28
bool MyDatabaseHasLoginEventTriggers
Definition: globals.c:97
bool IsBinaryUpgrade
Definition: globals.c:120
int32 MyCancelKey
Definition: globals.c:52
Oid MyDatabaseTableSpace
Definition: globals.c:95
bool MyCancelKeyValid
Definition: globals.c:51
struct Port * MyProcPort
Definition: globals.c:50
const char * hba_authname(UserAuth auth_method)
Definition: hba.c:3065
static char * username
Definition: initdb.c:153
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:337
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1073
#define RowExclusiveLock
Definition: lockdefs.h:38
void InitializeClientEncoding(void)
Definition: mbutils.c:281
void pfree(void *pointer)
Definition: mcxt.c:1521
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:451
#define INIT_PG_LOAD_SESSION_LIBS
Definition: miscadmin.h:473
#define AmBackgroundWorkerProcess()
Definition: miscadmin.h:373
#define AmLogicalSlotSyncWorkerProcess()
Definition: miscadmin.h:375
#define AmAutoVacuumLauncherProcess()
Definition: miscadmin.h:371
#define INIT_PG_OVERRIDE_ROLE_LOGIN
Definition: miscadmin.h:475
#define INIT_PG_OVERRIDE_ALLOW_CONNS
Definition: miscadmin.h:474
void InitializeSessionUserId(const char *rolename, Oid roleid, bool bypass_login_check)
Definition: miscinit.c:733
void InitializeSystemUser(const char *authn_id, const char *auth_method)
Definition: miscinit.c:867
void InitializeSessionUserIdStandalone(void)
Definition: miscinit.c:837
void process_session_preload_libraries(void)
Definition: miscinit.c:1857
Oid GetSessionUserId(void)
Definition: miscinit.c:548
void SetDatabasePath(const char *path)
Definition: miscinit.c:328
ClientConnectionInfo MyClientConnectionInfo
Definition: miscinit.c:1010
bool has_rolreplication(Oid roleid)
Definition: miscinit.c:711
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1710
int namestrcmp(Name name, const char *str)
Definition: name.c:247
void InitializeSearchPath(void)
Definition: namespace.c:4721
#define NAMEDATALEN
void pgstat_before_server_shutdown(int code, Datum arg)
Definition: pgstat.c:532
void InitPlanCache(void)
Definition: plancache.c:155
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
void EnablePortalManager(void)
Definition: portalmem.c:104
int PostAuthDelay
Definition: postgres.c:102
static void ShutdownPostgres(int code, Datum arg)
Definition: postinit.c:1287
static void IdleInTransactionSessionTimeoutHandler(void)
Definition: postinit.c:1344
static void LockTimeoutHandler(void)
Definition: postinit.c:1326
static void IdleStatsUpdateTimeoutHandler(void)
Definition: postinit.c:1360
static void process_settings(Oid databaseid, Oid roleid)
Definition: postinit.c:1253
static void IdleSessionTimeoutHandler(void)
Definition: postinit.c:1352
static void process_startup_options(Port *port, bool am_superuser)
Definition: postinit.c:1188
static void StatementTimeoutHandler(void)
Definition: postinit.c:1304
static void CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections)
Definition: postinit.c:313
static bool ThereIsAtLeastOneRole(void)
Definition: postinit.c:1379
static void PerformAuthentication(Port *port)
Definition: postinit.c:190
static void ClientCheckTimeoutHandler(void)
Definition: postinit.c:1368
static HeapTuple GetDatabaseTuple(const char *dbname)
Definition: postinit.c:101
static HeapTuple GetDatabaseTupleByOid(Oid dboid)
Definition: postinit.c:144
static void TransactionTimeoutHandler(void)
Definition: postinit.c:1336
int ReservedConnections
Definition: postmaster.c:213
int SuperuserReservedConnections
Definition: postmaster.c:212
short access
Definition: preproc-type.c:36
void ProcSignalInit(bool cancel_key_valid, int32 cancel_key)
Definition: procsignal.c:166
void RelationCacheInitializePhase3(void)
Definition: relcache.c:4097
void RelationCacheInitialize(void)
Definition: relcache.c:3992
void RelationCacheInitializePhase2(void)
Definition: relcache.c:4038
char * GetDatabasePath(Oid dbOid, Oid spcOid)
Definition: relpath.c:110
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:1002
ResourceOwner CurrentResourceOwner
Definition: resowner.c:165
void CreateAuxProcessResourceOwner(void)
Definition: resowner.c:982
void InitializeSession(void)
Definition: session.c:54
void pg_usleep(long microsec)
Definition: signal.c:53
void SharedInvalBackendInit(bool sendOnly)
Definition: sinvaladt.c:272
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:216
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:422
bool HaveNFreeProcs(int n, int *nfree)
Definition: proc.c:688
void CheckDeadLockAlert(void)
Definition: proc.c:1846
void InitProcessPhase2(void)
Definition: proc.c:489
const char * authn_id
Definition: libpq-be.h:103
UserAuth auth_method
Definition: libpq-be.h:109
Oid databaseId
Definition: proc.h:202
bool superuser(void)
Definition: superuser.c:46
void InitCatalogCache(void)
Definition: syscache.c:107
TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
Definition: timeout.c:505
@ IDLE_SESSION_TIMEOUT
Definition: timeout.h:35
@ IDLE_IN_TRANSACTION_SESSION_TIMEOUT
Definition: timeout.h:33
@ LOCK_TIMEOUT
Definition: timeout.h:28
@ STATEMENT_TIMEOUT
Definition: timeout.h:29
@ DEADLOCK_TIMEOUT
Definition: timeout.h:27
@ TRANSACTION_TIMEOUT
Definition: timeout.h:34
@ IDLE_STATS_UPDATE_TIMEOUT
Definition: timeout.h:36
@ CLIENT_CONNECTION_CHECK_TIMEOUT
Definition: timeout.h:37
bool am_walsender
Definition: walsender.c:115
bool am_db_walsender
Definition: walsender.c:118
void StartTransactionCommand(void)
Definition: xact.c:3039
int XactIsoLevel
Definition: xact.c:78
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:913
void CommitTransactionCommand(void)
Definition: xact.c:3137
#define XACT_READ_COMMITTED
Definition: xact.h:37
void StartupXLOG(void)
Definition: xlog.c:5422
void ShutdownXLOG(int code, Datum arg)
Definition: xlog.c:6601

References am_db_walsender, am_walsender, AmAutoVacuumLauncherProcess, AmAutoVacuumWorkerProcess, AmBackgroundWorkerProcess, AmLogicalSlotSyncWorkerProcess, Assert, ClientConnectionInfo::auth_method, ClientConnectionInfo::authn_id, before_shmem_exit(), CheckDeadLockAlert(), CheckMyDatabase(), CLIENT_CONNECTION_CHECK_TIMEOUT, ClientCheckTimeoutHandler(), CommitTransactionCommand(), CreateAuxProcessResourceOwner(), CurrentResourceOwner, database_is_invalid_form(), PGPROC::databaseId, dbname, DEADLOCK_TIMEOUT, DEBUG3, elog, EnablePortalManager(), ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg(), FATAL, GetDatabasePath(), GetDatabaseTuple(), GetDatabaseTupleByOid(), GetSessionUserId(), GETSTRUCT, GetTransactionSnapshot(), GetUserId(), has_privs_of_role(), has_rolreplication(), HaveNFreeProcs(), hba_authname(), HeapTupleIsValid, IDLE_IN_TRANSACTION_SESSION_TIMEOUT, IDLE_SESSION_TIMEOUT, IDLE_STATS_UPDATE_TIMEOUT, IdleInTransactionSessionTimeoutHandler(), IdleSessionTimeoutHandler(), IdleStatsUpdateTimeoutHandler(), INIT_PG_LOAD_SESSION_LIBS, INIT_PG_OVERRIDE_ALLOW_CONNS, INIT_PG_OVERRIDE_ROLE_LOGIN, InitCatalogCache(), initialize_acl(), InitializeClientEncoding(), InitializeSearchPath(), InitializeSession(), InitializeSessionUserId(), InitializeSessionUserIdStandalone(), InitializeSystemUser(), InitPlanCache(), InitProcessPhase2(), InvalidateCatalogSnapshot(), IsBinaryUpgrade, IsBootstrapProcessingMode, IsUnderPostmaster, LOCK_TIMEOUT, LockSharedObject(), LockTimeoutHandler(), MyCancelKey, MyCancelKeyValid, MyClientConnectionInfo, MyDatabaseHasLoginEventTriggers, MyDatabaseId, MyDatabaseTableSpace, MyProc, MyProcPort, NAMEDATALEN, NameStr, namestrcmp(), OidIsValid, PerformAuthentication(), pfree(), pg_usleep(), pgstat_before_server_shutdown(), pgstat_beinit(), pgstat_bestart(), PostAuthDelay, process_session_preload_libraries(), process_settings(), process_startup_options(), ProcSignalInit(), RegisterTimeout(), RelationCacheInitialize(), RelationCacheInitializePhase2(), RelationCacheInitializePhase3(), ReleaseAuxProcessResources(), ReservedConnections, RowExclusiveLock, SetCurrentStatementStartTimestamp(), SetDatabasePath(), SharedInvalBackendInit(), ShutdownPostgres(), ShutdownXLOG(), StartTransactionCommand(), StartupXLOG(), STATEMENT_TIMEOUT, StatementTimeoutHandler(), strlcpy(), superuser(), SuperuserReservedConnections, ThereIsAtLeastOneRole(), TRANSACTION_TIMEOUT, TransactionTimeoutHandler(), username, ValidatePgVersion(), WARNING, XACT_READ_COMMITTED, and XactIsoLevel.

Referenced by AutoVacWorkerMain(), BackgroundWorkerInitializeConnection(), BackgroundWorkerInitializeConnectionByOid(), BootstrapModeMain(), PostgresMain(), and ReplSlotSyncWorkerMain().

◆ LockTimeoutHandler()

static void LockTimeoutHandler ( void  )
static

Definition at line 1326 of file postinit.c.

1327 {
1328 #ifdef HAVE_SETSID
1329  /* try to signal whole process group */
1330  kill(-MyProcPid, SIGINT);
1331 #endif
1332  kill(MyProcPid, SIGINT);
1333 }
int MyProcPid
Definition: globals.c:46
#define kill(pid, sig)
Definition: win32_port.h:503

References kill, and MyProcPid.

Referenced by InitPostgres().

◆ PerformAuthentication()

static void PerformAuthentication ( Port port)
static

Definition at line 190 of file postinit.c.

191 {
192  /* This should be set already, but let's make sure */
193  ClientAuthInProgress = true; /* limit visibility of log messages */
194 
195  /*
196  * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
197  * etcetera from the postmaster, and have to load them ourselves.
198  *
199  * FIXME: [fork/exec] Ugh. Is there a way around this overhead?
200  */
201 #ifdef EXEC_BACKEND
202 
203  /*
204  * load_hba() and load_ident() want to work within the PostmasterContext,
205  * so create that if it doesn't exist (which it won't). We'll delete it
206  * again later, in PostgresMain.
207  */
208  if (PostmasterContext == NULL)
210  "Postmaster",
212 
213  if (!load_hba())
214  {
215  /*
216  * It makes no sense to continue if we fail to load the HBA file,
217  * since there is no way to connect to the database in this case.
218  */
219  ereport(FATAL,
220  /* translator: %s is a configuration file */
221  (errmsg("could not load %s", HbaFileName)));
222  }
223 
224  if (!load_ident())
225  {
226  /*
227  * It is ok to continue if we fail to load the IDENT file, although it
228  * means that you cannot log in using any of the authentication
229  * methods that need a user name mapping. load_ident() already logged
230  * the details of error to the log.
231  */
232  }
233 #endif
234 
235  /*
236  * Set up a timeout in case a buggy or malicious client fails to respond
237  * during authentication. Since we're inside a transaction and might do
238  * database access, we have to use the statement_timeout infrastructure.
239  */
241 
242  /*
243  * Now perform authentication exchange.
244  */
245  set_ps_display("authentication");
246  ClientAuthentication(port); /* might not return, if failure */
247 
248  /*
249  * Done with authentication. Disable the timeout, and log if needed.
250  */
252 
253  if (Log_connections)
254  {
255  StringInfoData logmsg;
256 
257  initStringInfo(&logmsg);
258  if (am_walsender)
259  appendStringInfo(&logmsg, _("replication connection authorized: user=%s"),
260  port->user_name);
261  else
262  appendStringInfo(&logmsg, _("connection authorized: user=%s"),
263  port->user_name);
264  if (!am_walsender)
265  appendStringInfo(&logmsg, _(" database=%s"), port->database_name);
266 
267  if (port->application_name != NULL)
268  appendStringInfo(&logmsg, _(" application_name=%s"),
269  port->application_name);
270 
271 #ifdef USE_SSL
272  if (port->ssl_in_use)
273  appendStringInfo(&logmsg, _(" SSL enabled (protocol=%s, cipher=%s, bits=%d)"),
277 #endif
278 #ifdef ENABLE_GSS
279  if (port->gss)
280  {
281  const char *princ = be_gssapi_get_princ(port);
282 
283  if (princ)
284  appendStringInfo(&logmsg,
285  _(" GSS (authenticated=%s, encrypted=%s, delegated_credentials=%s, principal=%s)"),
286  be_gssapi_get_auth(port) ? _("yes") : _("no"),
287  be_gssapi_get_enc(port) ? _("yes") : _("no"),
288  be_gssapi_get_delegation(port) ? _("yes") : _("no"),
289  princ);
290  else
291  appendStringInfo(&logmsg,
292  _(" GSS (authenticated=%s, encrypted=%s, delegated_credentials=%s)"),
293  be_gssapi_get_auth(port) ? _("yes") : _("no"),
294  be_gssapi_get_enc(port) ? _("yes") : _("no"),
295  be_gssapi_get_delegation(port) ? _("yes") : _("no"));
296  }
297 #endif
298 
299  ereport(LOG, errmsg_internal("%s", logmsg.data));
300  pfree(logmsg.data);
301  }
302 
303  set_ps_display("startup");
304 
305  ClientAuthInProgress = false; /* client_min_messages is active now */
306 }
void ClientAuthentication(Port *port)
Definition: auth.c:382
bool be_gssapi_get_auth(Port *port)
bool be_gssapi_get_enc(Port *port)
const char * be_gssapi_get_princ(Port *port)
bool be_gssapi_get_delegation(Port *port)
const char * be_tls_get_version(Port *port)
int be_tls_get_cipher_bits(Port *port)
const char * be_tls_get_cipher(Port *port)
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
#define _(x)
Definition: elog.c:90
#define LOG
Definition: elog.h:31
char * HbaFileName
Definition: guc_tables.c:539
bool load_ident(void)
Definition: hba.c:2963
bool load_hba(void)
Definition: hba.c:2587
MemoryContext TopMemoryContext
Definition: mcxt.c:149
MemoryContext PostmasterContext
Definition: mcxt.c:151
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
static int port
Definition: pg_regress.c:116
bool Log_connections
Definition: postmaster.c:227
bool ClientAuthInProgress
Definition: postmaster.c:346
int AuthenticationTimeout
Definition: postmaster.c:224
static void set_ps_display(const char *activity)
Definition: ps_status.h:40
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:97
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:560
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:685

References _, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, am_walsender, appendStringInfo(), AuthenticationTimeout, be_gssapi_get_auth(), be_gssapi_get_delegation(), be_gssapi_get_enc(), be_gssapi_get_princ(), be_tls_get_cipher(), be_tls_get_cipher_bits(), be_tls_get_version(), ClientAuthentication(), ClientAuthInProgress, StringInfoData::data, disable_timeout(), enable_timeout_after(), ereport, errmsg(), errmsg_internal(), FATAL, HbaFileName, initStringInfo(), load_hba(), load_ident(), LOG, Log_connections, pfree(), port, PostmasterContext, set_ps_display(), STATEMENT_TIMEOUT, and TopMemoryContext.

Referenced by InitPostgres().

◆ pg_split_opts()

void pg_split_opts ( char **  argv,
int *  argcp,
const char *  optstr 
)

Definition at line 484 of file postinit.c.

485 {
486  StringInfoData s;
487 
488  initStringInfo(&s);
489 
490  while (*optstr)
491  {
492  bool last_was_escape = false;
493 
494  resetStringInfo(&s);
495 
496  /* skip over leading space */
497  while (isspace((unsigned char) *optstr))
498  optstr++;
499 
500  if (*optstr == '\0')
501  break;
502 
503  /*
504  * Parse a single option, stopping at the first space, unless it's
505  * escaped.
506  */
507  while (*optstr)
508  {
509  if (isspace((unsigned char) *optstr) && !last_was_escape)
510  break;
511 
512  if (!last_was_escape && *optstr == '\\')
513  last_was_escape = true;
514  else
515  {
516  last_was_escape = false;
517  appendStringInfoChar(&s, *optstr);
518  }
519 
520  optstr++;
521  }
522 
523  /* now store the option in the next argv[] position */
524  argv[(*argcp)++] = pstrdup(s.data);
525  }
526 
527  pfree(s.data);
528 }
char * pstrdup(const char *in)
Definition: mcxt.c:1696
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:78
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:194

References appendStringInfoChar(), StringInfoData::data, initStringInfo(), pfree(), pstrdup(), and resetStringInfo().

Referenced by process_startup_options().

◆ process_settings()

static void process_settings ( Oid  databaseid,
Oid  roleid 
)
static

Definition at line 1253 of file postinit.c.

1254 {
1255  Relation relsetting;
1256  Snapshot snapshot;
1257 
1258  if (!IsUnderPostmaster)
1259  return;
1260 
1261  relsetting = table_open(DbRoleSettingRelationId, AccessShareLock);
1262 
1263  /* read all the settings under the same snapshot for efficiency */
1264  snapshot = RegisterSnapshot(GetCatalogSnapshot(DbRoleSettingRelationId));
1265 
1266  /* Later settings are ignored if set earlier. */
1267  ApplySetting(snapshot, databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
1268  ApplySetting(snapshot, InvalidOid, roleid, relsetting, PGC_S_USER);
1269  ApplySetting(snapshot, databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
1270  ApplySetting(snapshot, InvalidOid, InvalidOid, relsetting, PGC_S_GLOBAL);
1271 
1272  UnregisterSnapshot(snapshot);
1273  table_close(relsetting, AccessShareLock);
1274 }
@ PGC_S_GLOBAL
Definition: guc.h:114
@ PGC_S_DATABASE
Definition: guc.h:115
@ PGC_S_DATABASE_USER
Definition: guc.h:117
@ PGC_S_USER
Definition: guc.h:116
void ApplySetting(Snapshot snapshot, Oid databaseid, Oid roleid, Relation relsetting, GucSource source)
#define InvalidOid
Definition: postgres_ext.h:36
Snapshot GetCatalogSnapshot(Oid relid)
Definition: snapmgr.c:352
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:836
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:794

References AccessShareLock, ApplySetting(), GetCatalogSnapshot(), InvalidOid, IsUnderPostmaster, PGC_S_DATABASE, PGC_S_DATABASE_USER, PGC_S_GLOBAL, PGC_S_USER, RegisterSnapshot(), table_close(), table_open(), and UnregisterSnapshot().

Referenced by InitPostgres().

◆ process_startup_options()

static void process_startup_options ( Port port,
bool  am_superuser 
)
static

Definition at line 1188 of file postinit.c.

1189 {
1190  GucContext gucctx;
1191  ListCell *gucopts;
1192 
1193  gucctx = am_superuser ? PGC_SU_BACKEND : PGC_BACKEND;
1194 
1195  /*
1196  * First process any command-line switches that were included in the
1197  * startup packet, if we are in a regular backend.
1198  */
1199  if (port->cmdline_options != NULL)
1200  {
1201  /*
1202  * The maximum possible number of commandline arguments that could
1203  * come from port->cmdline_options is (strlen + 1) / 2; see
1204  * pg_split_opts().
1205  */
1206  char **av;
1207  int maxac;
1208  int ac;
1209 
1210  maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
1211 
1212  av = (char **) palloc(maxac * sizeof(char *));
1213  ac = 0;
1214 
1215  av[ac++] = "postgres";
1216 
1217  pg_split_opts(av, &ac, port->cmdline_options);
1218 
1219  av[ac] = NULL;
1220 
1221  Assert(ac < maxac);
1222 
1223  (void) process_postgres_switches(ac, av, gucctx, NULL);
1224  }
1225 
1226  /*
1227  * Process any additional GUC variable settings passed in startup packet.
1228  * These are handled exactly like command-line variables.
1229  */
1230  gucopts = list_head(port->guc_options);
1231  while (gucopts)
1232  {
1233  char *name;
1234  char *value;
1235 
1236  name = lfirst(gucopts);
1237  gucopts = lnext(port->guc_options, gucopts);
1238 
1239  value = lfirst(gucopts);
1240  gucopts = lnext(port->guc_options, gucopts);
1241 
1243  }
1244 }
@ PGC_S_CLIENT
Definition: guc.h:118
GucContext
Definition: guc.h:68
@ PGC_SU_BACKEND
Definition: guc.h:72
static struct @157 value
void * palloc(Size size)
Definition: mcxt.c:1317
#define lfirst(lc)
Definition: pg_list.h:172
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3859
void pg_split_opts(char **argv, int *argcp, const char *optstr)
Definition: postinit.c:484
struct @10::@11 av[32]

References Assert, av, lfirst, list_head(), lnext(), name, palloc(), pg_split_opts(), PGC_BACKEND, PGC_S_CLIENT, PGC_SU_BACKEND, port, process_postgres_switches(), SetConfigOption(), and value.

Referenced by InitPostgres().

◆ ShutdownPostgres()

static void ShutdownPostgres ( int  code,
Datum  arg 
)
static

Definition at line 1287 of file postinit.c.

1288 {
1289  /* Make sure we've killed any active transaction */
1291 
1292  /*
1293  * User locks are not released by transaction end, so be sure to release
1294  * them explicitly.
1295  */
1297 }
void LockReleaseAll(LOCKMETHODID lockmethodid, bool allLocks)
Definition: lock.c:2168
#define USER_LOCKMETHOD
Definition: lock.h:126
void AbortOutOfAnyTransaction(void)
Definition: xact.c:4855

References AbortOutOfAnyTransaction(), LockReleaseAll(), and USER_LOCKMETHOD.

Referenced by InitPostgres().

◆ StatementTimeoutHandler()

static void StatementTimeoutHandler ( void  )
static

Definition at line 1304 of file postinit.c.

1305 {
1306  int sig = SIGINT;
1307 
1308  /*
1309  * During authentication the timeout is used to deal with
1310  * authentication_timeout - we want to quit in response to such timeouts.
1311  */
1313  sig = SIGTERM;
1314 
1315 #ifdef HAVE_SETSID
1316  /* try to signal whole process group */
1317  kill(-MyProcPid, sig);
1318 #endif
1319  kill(MyProcPid, sig);
1320 }
static int sig
Definition: pg_ctl.c:80

References ClientAuthInProgress, kill, MyProcPid, and sig.

Referenced by InitPostgres().

◆ ThereIsAtLeastOneRole()

static bool ThereIsAtLeastOneRole ( void  )
static

Definition at line 1379 of file postinit.c.

1380 {
1381  Relation pg_authid_rel;
1382  TableScanDesc scan;
1383  bool result;
1384 
1385  pg_authid_rel = table_open(AuthIdRelationId, AccessShareLock);
1386 
1387  scan = table_beginscan_catalog(pg_authid_rel, 0, NULL);
1388  result = (heap_getnext(scan, ForwardScanDirection) != NULL);
1389 
1390  table_endscan(scan);
1391  table_close(pg_authid_rel, AccessShareLock);
1392 
1393  return result;
1394 }
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1234
@ ForwardScanDirection
Definition: sdir.h:28
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:1019

References AccessShareLock, ForwardScanDirection, heap_getnext(), table_beginscan_catalog(), table_close(), table_endscan(), and table_open().

Referenced by InitPostgres().

◆ TransactionTimeoutHandler()

static void TransactionTimeoutHandler ( void  )
static

Definition at line 1336 of file postinit.c.

1337 {
1339  InterruptPending = true;
1340  SetLatch(MyLatch);
1341 }
volatile sig_atomic_t TransactionTimeoutPending
Definition: globals.c:37

References InterruptPending, MyLatch, SetLatch(), and TransactionTimeoutPending.

Referenced by InitPostgres().