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/sysattr.h"
#include "access/tableam.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "access/xloginsert.h"
#include "catalog/catalog.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/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 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)
 
bool check_max_connections (int *newval, void **extra, GucSource source)
 
bool check_autovacuum_max_workers (int *newval, void **extra, GucSource source)
 
bool check_max_worker_processes (int *newval, void **extra, GucSource source)
 
bool check_max_wal_senders (int *newval, void **extra, GucSource source)
 
void BaseInit (void)
 
void InitPostgres (const char *in_dbname, Oid dboid, const char *username, Oid useroid, bool load_session_libraries, bool override_allow_connections, char *out_dbname)
 

Function Documentation

◆ BaseInit()

void BaseInit ( void  )

Definition at line 623 of file postinit.c.

624 {
625  Assert(MyProc != NULL);
626 
627  /*
628  * Initialize our input/output/debugging file descriptors.
629  */
630  DebugFileOpen();
631 
632  /*
633  * Initialize file access. Done early so other subsystems can access
634  * files.
635  */
636  InitFileAccess();
637 
638  /*
639  * Initialize statistics reporting. This needs to happen early to ensure
640  * that pgstat's shutdown callback runs after the shutdown callbacks of
641  * all subsystems that can produce stats (like e.g. transaction commits
642  * can).
643  */
645 
646  /* Do local initialization of storage and buffer managers */
647  InitSync();
648  smgrinit();
650 
651  /*
652  * Initialize temporary file access after pgstat, so that the temporary
653  * file shutdown hook can report temporary file statistics.
654  */
656 
657  /*
658  * Initialize local buffers for WAL record construction, in case we ever
659  * try to insert XLOG.
660  */
661  InitXLogInsert();
662 
663  /*
664  * Initialize replication slots after pgstat. The exit hook might need to
665  * drop ephemeral slots, which in turn triggers stats reporting.
666  */
668 }
void InitBufferPoolAccess(void)
Definition: bufmgr.c:2611
void DebugFileOpen(void)
Definition: elog.c:1918
void InitFileAccess(void)
Definition: fd.c:809
void InitTemporaryFileAccess(void)
Definition: fd.c:839
Assert(fmt[strlen(fmt) - 1] !='\n')
void pgstat_initialize(void)
Definition: pgstat.c:523
void ReplicationSlotInitialize(void)
Definition: slot.c:170
void smgrinit(void)
Definition: smgr.c:111
PGPROC * MyProc
Definition: proc.c:68
void InitSync(void)
Definition: sync.c:131
void InitXLogInsert(void)
Definition: xloginsert.c:1298

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

Referenced by AutoVacLauncherMain(), AutoVacWorkerMain(), AuxiliaryProcessMain(), BootstrapModeMain(), PostgresMain(), and StartBackgroundWorker().

◆ check_autovacuum_max_workers()

bool check_autovacuum_max_workers ( int *  newval,
void **  extra,
GucSource  source 
)

Definition at line 582 of file postinit.c.

583 {
584  if (MaxConnections + *newval + 1 +
586  return false;
587  return true;
588 }
int MaxConnections
Definition: globals.c:137
int max_worker_processes
Definition: globals.c:138
#define newval
#define MAX_BACKENDS
Definition: postmaster.h:77
int max_wal_senders
Definition: walsender.c:122

References MAX_BACKENDS, max_wal_senders, max_worker_processes, MaxConnections, and newval.

◆ check_max_connections()

bool check_max_connections ( int *  newval,
void **  extra,
GucSource  source 
)

Definition at line 570 of file postinit.c.

571 {
572  if (*newval + autovacuum_max_workers + 1 +
574  return false;
575  return true;
576 }
int autovacuum_max_workers
Definition: autovacuum.c:117

References autovacuum_max_workers, MAX_BACKENDS, max_wal_senders, max_worker_processes, and newval.

◆ check_max_wal_senders()

bool check_max_wal_senders ( int *  newval,
void **  extra,
GucSource  source 
)

Definition at line 606 of file postinit.c.

607 {
610  return false;
611  return true;
612 }

References autovacuum_max_workers, MAX_BACKENDS, max_worker_processes, MaxConnections, and newval.

◆ check_max_worker_processes()

bool check_max_worker_processes ( int *  newval,
void **  extra,
GucSource  source 
)

Definition at line 594 of file postinit.c.

595 {
598  return false;
599  return true;
600 }

References autovacuum_max_workers, MAX_BACKENDS, max_wal_senders, MaxConnections, and newval.

◆ CheckMyDatabase()

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

Definition at line 311 of file postinit.c.

312 {
313  HeapTuple tup;
314  Form_pg_database dbform;
315  Datum datum;
316  bool isnull;
317  char *collate;
318  char *ctype;
319  char *iculocale;
320 
321  /* Fetch our pg_database row normally, via syscache */
323  if (!HeapTupleIsValid(tup))
324  elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
325  dbform = (Form_pg_database) GETSTRUCT(tup);
326 
327  /* This recheck is strictly paranoia */
328  if (strcmp(name, NameStr(dbform->datname)) != 0)
329  ereport(FATAL,
330  (errcode(ERRCODE_UNDEFINED_DATABASE),
331  errmsg("database \"%s\" has disappeared from pg_database",
332  name),
333  errdetail("Database OID %u now seems to belong to \"%s\".",
334  MyDatabaseId, NameStr(dbform->datname))));
335 
336  /*
337  * Check permissions to connect to the database.
338  *
339  * These checks are not enforced when in standalone mode, so that there is
340  * a way to recover from disabling all access to all databases, for
341  * example "UPDATE pg_database SET datallowconn = false;".
342  *
343  * We do not enforce them for autovacuum worker processes either.
344  */
346  {
347  /*
348  * Check that the database is currently allowing connections.
349  */
350  if (!dbform->datallowconn && !override_allow_connections)
351  ereport(FATAL,
352  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
353  errmsg("database \"%s\" is not currently accepting connections",
354  name)));
355 
356  /*
357  * Check privilege to connect to the database. (The am_superuser test
358  * is redundant, but since we have the flag, might as well check it
359  * and save a few cycles.)
360  */
361  if (!am_superuser &&
362  object_aclcheck(DatabaseRelationId, MyDatabaseId, GetUserId(),
364  ereport(FATAL,
365  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
366  errmsg("permission denied for database \"%s\"", name),
367  errdetail("User does not have CONNECT privilege.")));
368 
369  /*
370  * Check connection limit for this database.
371  *
372  * There is a race condition here --- we create our PGPROC before
373  * checking for other PGPROCs. If two backends did this at about the
374  * same time, they might both think they were over the limit, while
375  * ideally one should succeed and one fail. Getting that to work
376  * exactly seems more trouble than it is worth, however; instead we
377  * just document that the connection limit is approximate.
378  */
379  if (dbform->datconnlimit >= 0 &&
380  !am_superuser &&
381  CountDBConnections(MyDatabaseId) > dbform->datconnlimit)
382  ereport(FATAL,
383  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
384  errmsg("too many connections for database \"%s\"",
385  name)));
386  }
387 
388  /*
389  * OK, we're golden. Next to-do item is to save the encoding info out of
390  * the pg_database tuple.
391  */
392  SetDatabaseEncoding(dbform->encoding);
393  /* Record it as a GUC internal option, too */
394  SetConfigOption("server_encoding", GetDatabaseEncodingName(),
396  /* If we have no other source of client_encoding, use server encoding */
397  SetConfigOption("client_encoding", GetDatabaseEncodingName(),
399 
400  /* assign locale variables */
401  datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_datcollate, &isnull);
402  Assert(!isnull);
403  collate = TextDatumGetCString(datum);
404  datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_datctype, &isnull);
405  Assert(!isnull);
406  ctype = TextDatumGetCString(datum);
407 
408  if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
409  ereport(FATAL,
410  (errmsg("database locale is incompatible with operating system"),
411  errdetail("The database was initialized with LC_COLLATE \"%s\", "
412  " which is not recognized by setlocale().", collate),
413  errhint("Recreate the database with another locale or install the missing locale.")));
414 
415  if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
416  ereport(FATAL,
417  (errmsg("database locale is incompatible with operating system"),
418  errdetail("The database was initialized with LC_CTYPE \"%s\", "
419  " which is not recognized by setlocale().", ctype),
420  errhint("Recreate the database with another locale or install the missing locale.")));
421 
422  if (dbform->datlocprovider == COLLPROVIDER_ICU)
423  {
424  datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_daticulocale, &isnull);
425  Assert(!isnull);
426  iculocale = TextDatumGetCString(datum);
427  make_icu_collator(iculocale, &default_locale);
428  }
429  else
430  iculocale = NULL;
431 
432  default_locale.provider = dbform->datlocprovider;
433 
434  /*
435  * Default locale is currently always deterministic. Nondeterministic
436  * locales currently don't support pattern matching, which would break a
437  * lot of things if applied globally.
438  */
440 
441  /*
442  * Check collation version. See similar code in
443  * pg_newlocale_from_collation(). Note that here we warn instead of error
444  * in any case, so that we don't prevent connecting.
445  */
446  datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_datcollversion,
447  &isnull);
448  if (!isnull)
449  {
450  char *actual_versionstr;
451  char *collversionstr;
452 
453  collversionstr = TextDatumGetCString(datum);
454 
455  actual_versionstr = get_collation_actual_version(dbform->datlocprovider, dbform->datlocprovider == COLLPROVIDER_ICU ? iculocale : collate);
456  if (!actual_versionstr)
457  /* should not happen */
458  elog(WARNING,
459  "database \"%s\" has no actual collation version, but a version was recorded",
460  name);
461  else if (strcmp(actual_versionstr, collversionstr) != 0)
463  (errmsg("database \"%s\" has a collation version mismatch",
464  name),
465  errdetail("The database was created using collation version %s, "
466  "but the operating system provides version %s.",
467  collversionstr, actual_versionstr),
468  errhint("Rebuild all objects in this database that use the default collation and run "
469  "ALTER DATABASE %s REFRESH COLLATION VERSION, "
470  "or build PostgreSQL with the right library version.",
472  }
473 
474  /* Make the locale settings visible as GUC variables, too */
475  SetConfigOption("lc_collate", collate, PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
477 
479 
480  ReleaseSysCache(tup);
481 }
@ ACLCHECK_OK
Definition: acl.h:182
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:4570
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3314
#define TextDatumGetCString(d)
Definition: builtins.h:86
#define NameStr(name)
Definition: c.h:682
int errdetail(const char *fmt,...)
Definition: elog.c:1039
int errhint(const char *fmt,...)
Definition: elog.c:1153
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define FATAL
Definition: elog.h:37
#define WARNING
Definition: elog.h:32
#define ERROR
Definition: elog.h:35
#define ereport(elevel,...)
Definition: elog.h:145
const char * name
Definition: encode.c:561
bool IsUnderPostmaster
Definition: globals.c:113
Oid MyDatabaseId
Definition: globals.c:89
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4158
@ 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:649
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1216
void SetDatabaseEncoding(int encoding)
Definition: mbutils.c:1104
Oid GetUserId(void)
Definition: miscinit.c:497
#define ACL_CONNECT
Definition: parsenodes.h:94
FormData_pg_database * Form_pg_database
Definition: pg_database.h:87
void make_icu_collator(const char *iculocstr, struct pg_locale_struct *resultp)
Definition: pg_locale.c:1404
struct pg_locale_struct default_locale
Definition: pg_locale.c:1401
void check_strxfrm_bug(void)
Definition: pg_locale.c:1150
char * get_collation_actual_version(char collprovider, const char *collcollate)
Definition: pg_locale.c:1647
char * pg_perm_setlocale(int category, const char *locale)
Definition: pg_locale.c:144
uintptr_t Datum
Definition: postgres.h:412
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:600
int CountDBConnections(Oid databaseid)
Definition: procarray.c:3584
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11529
bool deterministic
Definition: pg_locale.h:76
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1221
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1173
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1434
@ DATABASEOID
Definition: syscache.h:55

References ACL_CONNECT, ACLCHECK_OK, Assert(), check_strxfrm_bug(), CountDBConnections(), DATABASEOID, default_locale, pg_locale_struct::deterministic, elog(), ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, FATAL, get_collation_actual_version(), GetDatabaseEncodingName(), GETSTRUCT, GetUserId(), HeapTupleIsValid, IsAutoVacuumWorkerProcess(), IsUnderPostmaster, make_icu_collator(), MyDatabaseId, name, NameStr, object_aclcheck(), ObjectIdGetDatum(), pg_perm_setlocale(), PGC_BACKEND, PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT, pg_locale_struct::provider, quote_identifier(), ReleaseSysCache(), SearchSysCache1(), SetConfigOption(), SetDatabaseEncoding(), SysCacheGetAttr(), TextDatumGetCString, and WARNING.

Referenced by InitPostgres().

◆ ClientCheckTimeoutHandler()

static void ClientCheckTimeoutHandler ( void  )
static

Definition at line 1380 of file postinit.c.

1381 {
1383  InterruptPending = true;
1384  SetLatch(MyLatch);
1385 }
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
struct Latch * MyLatch
Definition: globals.c:58
volatile sig_atomic_t CheckClientConnectionPending
Definition: globals.c:33
void SetLatch(Latch *latch)
Definition: latch.c:591

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:599
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:506
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:387
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:680
#define AccessShareLock
Definition: lockdefs.h:36
static Datum CStringGetDatum(const char *X)
Definition: postgres.h:698
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:51
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 1356 of file postinit.c.

1357 {
1359  InterruptPending = true;
1360  SetLatch(MyLatch);
1361 }
volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
Definition: globals.c:35

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

Referenced by InitPostgres().

◆ IdleSessionTimeoutHandler()

static void IdleSessionTimeoutHandler ( void  )
static

Definition at line 1364 of file postinit.c.

1365 {
1367  InterruptPending = true;
1368  SetLatch(MyLatch);
1369 }
volatile sig_atomic_t IdleSessionTimeoutPending
Definition: globals.c:36

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

Referenced by InitPostgres().

◆ IdleStatsUpdateTimeoutHandler()

static void IdleStatsUpdateTimeoutHandler ( void  )
static

Definition at line 1372 of file postinit.c.

1373 {
1375  InterruptPending = true;
1376  SetLatch(MyLatch);
1377 }
volatile sig_atomic_t IdleStatsUpdateTimeoutPending
Definition: globals.c:39

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

Referenced by InitPostgres().

◆ InitializeMaxBackends()

void InitializeMaxBackends ( void  )

Definition at line 553 of file postinit.c.

554 {
555  Assert(MaxBackends == 0);
556 
557  /* the extra unit accounts for the autovacuum launcher */
560 
561  /* internal error because the values were all checked previously */
563  elog(ERROR, "too many backends configured");
564 }
int MaxBackends
Definition: globals.c:140

References Assert(), autovacuum_max_workers, elog(), 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,
bool  load_session_libraries,
bool  override_allow_connections,
char *  out_dbname 
)

Definition at line 712 of file postinit.c.

717 {
718  bool bootstrap = IsBootstrapProcessingMode();
719  bool am_superuser;
720  char *fullpath;
721  char dbname[NAMEDATALEN];
722 
723  elog(DEBUG3, "InitPostgres");
724 
725  /*
726  * Add my PGPROC struct to the ProcArray.
727  *
728  * Once I have done this, I am visible to other backends!
729  */
731 
732  /*
733  * Initialize my entry in the shared-invalidation manager's array of
734  * per-backend data.
735  *
736  * Sets up MyBackendId, a unique backend identifier.
737  */
739 
740  SharedInvalBackendInit(false);
741 
742  if (MyBackendId > MaxBackends || MyBackendId <= 0)
743  elog(FATAL, "bad backend ID: %d", MyBackendId);
744 
745  /* Now that we have a BackendId, we can participate in ProcSignal */
747 
748  /*
749  * Also set up timeout handlers needed for backend operation. We need
750  * these in every case except bootstrap.
751  */
752  if (!bootstrap)
753  {
763  }
764 
765  /*
766  * If this is either a bootstrap process or a standalone backend, start up
767  * the XLOG machinery, and register to have it closed down at exit. In
768  * other cases, the startup process is responsible for starting up the
769  * XLOG machinery, and the checkpointer for closing it down.
770  */
771  if (!IsUnderPostmaster)
772  {
773  /*
774  * We don't yet have an aux-process resource owner, but StartupXLOG
775  * and ShutdownXLOG will need one. Hence, create said resource owner
776  * (and register a callback to clean it up after ShutdownXLOG runs).
777  */
779 
780  StartupXLOG();
781  /* Release (and warn about) any buffer pins leaked in StartupXLOG */
783  /* Reset CurrentResourceOwner to nothing for the moment */
784  CurrentResourceOwner = NULL;
785 
786  /*
787  * Use before_shmem_exit() so that ShutdownXLOG() can rely on DSM
788  * segments etc to work (which in turn is required for pgstats).
789  */
792  }
793 
794  /*
795  * Initialize the relation cache and the system catalog caches. Note that
796  * no catalog access happens here; we only set up the hashtable structure.
797  * We must do this before starting a transaction because transaction abort
798  * would try to touch these hashtables.
799  */
802  InitPlanCache();
803 
804  /* Initialize portal manager */
806 
807  /* Initialize status reporting */
808  pgstat_beinit();
809 
810  /*
811  * Load relcache entries for the shared system catalogs. This must create
812  * at least entries for pg_database and catalogs used for authentication.
813  */
815 
816  /*
817  * Set up process-exit callback to do pre-shutdown cleanup. This is the
818  * one of the first before_shmem_exit callbacks we register; thus, this
819  * will be one the last things we do before low-level modules like the
820  * buffer manager begin to close down. We need to have this in place
821  * before we begin our first transaction --- if we fail during the
822  * initialization transaction, as is entirely possible, we need the
823  * AbortTransaction call to clean up.
824  */
826 
827  /* The autovacuum launcher is done here */
829  {
830  /* report this backend in the PgBackendStatus array */
831  pgstat_bestart();
832 
833  return;
834  }
835 
836  /*
837  * Start a new transaction here before first access to db, and get a
838  * snapshot. We don't have a use for the snapshot itself, but we're
839  * interested in the secondary effect that it sets RecentGlobalXmin. (This
840  * is critical for anything that reads heap pages, because HOT may decide
841  * to prune them even if the process doesn't attempt to modify any
842  * tuples.)
843  *
844  * FIXME: This comment is inaccurate / the code buggy. A snapshot that is
845  * not pushed/active does not reliably prevent HOT pruning (->xmin could
846  * e.g. be cleared when cache invalidations are processed).
847  */
848  if (!bootstrap)
849  {
850  /* statement_timestamp must be set for timeouts to work correctly */
853 
854  /*
855  * transaction_isolation will have been set to the default by the
856  * above. If the default is "serializable", and we are in hot
857  * standby, we will fail if we don't change it to something lower.
858  * Fortunately, "read committed" is plenty good enough.
859  */
861 
862  (void) GetTransactionSnapshot();
863  }
864 
865  /*
866  * Perform client authentication if necessary, then figure out our
867  * postgres user ID, and see if we are a superuser.
868  *
869  * In standalone mode and in autovacuum worker processes, we use a fixed
870  * ID, otherwise we figure it out from the authenticated user name.
871  */
872  if (bootstrap || IsAutoVacuumWorkerProcess())
873  {
875  am_superuser = true;
876  }
877  else if (!IsUnderPostmaster)
878  {
880  am_superuser = true;
881  if (!ThereIsAtLeastOneRole())
883  (errcode(ERRCODE_UNDEFINED_OBJECT),
884  errmsg("no roles are defined in this database system"),
885  errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
886  username != NULL ? username : "postgres")));
887  }
888  else if (IsBackgroundWorker)
889  {
890  if (username == NULL && !OidIsValid(useroid))
891  {
893  am_superuser = true;
894  }
895  else
896  {
898  am_superuser = superuser();
899  }
900  }
901  else
902  {
903  /* normal multiuser case */
904  Assert(MyProcPort != NULL);
907  /* ensure that auth_method is actually valid, aka authn_id is not NULL */
911  am_superuser = superuser();
912  }
913 
914  /*
915  * Binary upgrades only allowed super-user connections
916  */
917  if (IsBinaryUpgrade && !am_superuser)
918  {
919  ereport(FATAL,
920  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
921  errmsg("must be superuser to connect in binary upgrade mode")));
922  }
923 
924  /*
925  * The last few connection slots are reserved for superusers. Replication
926  * connections are drawn from slots reserved with max_wal_senders and not
927  * limited by max_connections or superuser_reserved_connections.
928  */
929  if (!am_superuser && !am_walsender &&
930  ReservedBackends > 0 &&
932  ereport(FATAL,
933  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
934  errmsg("remaining connection slots are reserved for non-replication superuser connections")));
935 
936  /* Check replication permissions needed for walsender processes. */
937  if (am_walsender)
938  {
939  Assert(!bootstrap);
940 
941  if (!superuser() && !has_rolreplication(GetUserId()))
942  ereport(FATAL,
943  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
944  errmsg("must be superuser or replication role to start walsender")));
945  }
946 
947  /*
948  * If this is a plain walsender only supporting physical replication, we
949  * don't want to connect to any particular database. Just finish the
950  * backend startup by processing any options from the startup packet, and
951  * we're done.
952  */
954  {
955  /* process any options passed in the startup packet */
956  if (MyProcPort != NULL)
957  process_startup_options(MyProcPort, am_superuser);
958 
959  /* Apply PostAuthDelay as soon as we've read all options */
960  if (PostAuthDelay > 0)
961  pg_usleep(PostAuthDelay * 1000000L);
962 
963  /* initialize client encoding */
965 
966  /* report this backend in the PgBackendStatus array */
967  pgstat_bestart();
968 
969  /* close the transaction we started above */
971 
972  return;
973  }
974 
975  /*
976  * Set up the global variables holding database id and default tablespace.
977  * But note we won't actually try to touch the database just yet.
978  *
979  * We take a shortcut in the bootstrap case, otherwise we have to look up
980  * the db's entry in pg_database.
981  */
982  if (bootstrap)
983  {
984  MyDatabaseId = Template1DbOid;
985  MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
986  }
987  else if (in_dbname != NULL)
988  {
989  HeapTuple tuple;
990  Form_pg_database dbform;
991 
992  tuple = GetDatabaseTuple(in_dbname);
993  if (!HeapTupleIsValid(tuple))
994  ereport(FATAL,
995  (errcode(ERRCODE_UNDEFINED_DATABASE),
996  errmsg("database \"%s\" does not exist", in_dbname)));
997  dbform = (Form_pg_database) GETSTRUCT(tuple);
998  MyDatabaseId = dbform->oid;
999  MyDatabaseTableSpace = dbform->dattablespace;
1000  /* take database name from the caller, just for paranoia */
1001  strlcpy(dbname, in_dbname, sizeof(dbname));
1002  }
1003  else if (OidIsValid(dboid))
1004  {
1005  /* caller specified database by OID */
1006  HeapTuple tuple;
1007  Form_pg_database dbform;
1008 
1009  tuple = GetDatabaseTupleByOid(dboid);
1010  if (!HeapTupleIsValid(tuple))
1011  ereport(FATAL,
1012  (errcode(ERRCODE_UNDEFINED_DATABASE),
1013  errmsg("database %u does not exist", dboid)));
1014  dbform = (Form_pg_database) GETSTRUCT(tuple);
1015  MyDatabaseId = dbform->oid;
1016  MyDatabaseTableSpace = dbform->dattablespace;
1017  Assert(MyDatabaseId == dboid);
1018  strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
1019  /* pass the database name back to the caller */
1020  if (out_dbname)
1021  strcpy(out_dbname, dbname);
1022  }
1023  else
1024  {
1025  /*
1026  * If this is a background worker not bound to any particular
1027  * database, we're done now. Everything that follows only makes sense
1028  * if we are bound to a specific database. We do need to close the
1029  * transaction we started before returning.
1030  */
1031  if (!bootstrap)
1032  {
1033  pgstat_bestart();
1035  }
1036  return;
1037  }
1038 
1039  /*
1040  * Now, take a writer's lock on the database we are trying to connect to.
1041  * If there is a concurrently running DROP DATABASE on that database, this
1042  * will block us until it finishes (and has committed its update of
1043  * pg_database).
1044  *
1045  * Note that the lock is not held long, only until the end of this startup
1046  * transaction. This is OK since we will advertise our use of the
1047  * database in the ProcArray before dropping the lock (in fact, that's the
1048  * next thing to do). Anyone trying a DROP DATABASE after this point will
1049  * see us in the array once they have the lock. Ordering is important for
1050  * this because we don't want to advertise ourselves as being in this
1051  * database until we have the lock; otherwise we create what amounts to a
1052  * deadlock with CountOtherDBBackends().
1053  *
1054  * Note: use of RowExclusiveLock here is reasonable because we envision
1055  * our session as being a concurrent writer of the database. If we had a
1056  * way of declaring a session as being guaranteed-read-only, we could use
1057  * AccessShareLock for such sessions and thereby not conflict against
1058  * CREATE DATABASE.
1059  */
1060  if (!bootstrap)
1061  LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
1063 
1064  /*
1065  * Now we can mark our PGPROC entry with the database ID.
1066  *
1067  * We assume this is an atomic store so no lock is needed; though actually
1068  * things would work fine even if it weren't atomic. Anyone searching the
1069  * ProcArray for this database's ID should hold the database lock, so they
1070  * would not be executing concurrently with this store. A process looking
1071  * for another database's ID could in theory see a chance match if it read
1072  * a partially-updated databaseId value; but as long as all such searches
1073  * wait and retry, as in CountOtherDBBackends(), they will certainly see
1074  * the correct value on their next try.
1075  */
1077 
1078  /*
1079  * We established a catalog snapshot while reading pg_authid and/or
1080  * pg_database; but until we have set up MyDatabaseId, we won't react to
1081  * incoming sinval messages for unshared catalogs, so we won't realize it
1082  * if the snapshot has been invalidated. Assume it's no good anymore.
1083  */
1085 
1086  /*
1087  * Recheck pg_database to make sure the target database hasn't gone away.
1088  * If there was a concurrent DROP DATABASE, this ensures we will die
1089  * cleanly without creating a mess.
1090  */
1091  if (!bootstrap)
1092  {
1093  HeapTuple tuple;
1094 
1095  tuple = GetDatabaseTuple(dbname);
1096  if (!HeapTupleIsValid(tuple) ||
1097  MyDatabaseId != ((Form_pg_database) GETSTRUCT(tuple))->oid ||
1098  MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
1099  ereport(FATAL,
1100  (errcode(ERRCODE_UNDEFINED_DATABASE),
1101  errmsg("database \"%s\" does not exist", dbname),
1102  errdetail("It seems to have just been dropped or renamed.")));
1103  }
1104 
1105  /*
1106  * Now we should be able to access the database directory safely. Verify
1107  * it's there and looks reasonable.
1108  */
1110 
1111  if (!bootstrap)
1112  {
1113  if (access(fullpath, F_OK) == -1)
1114  {
1115  if (errno == ENOENT)
1116  ereport(FATAL,
1117  (errcode(ERRCODE_UNDEFINED_DATABASE),
1118  errmsg("database \"%s\" does not exist",
1119  dbname),
1120  errdetail("The database subdirectory \"%s\" is missing.",
1121  fullpath)));
1122  else
1123  ereport(FATAL,
1125  errmsg("could not access directory \"%s\": %m",
1126  fullpath)));
1127  }
1128 
1129  ValidatePgVersion(fullpath);
1130  }
1131 
1132  SetDatabasePath(fullpath);
1133  pfree(fullpath);
1134 
1135  /*
1136  * It's now possible to do real access to the system catalogs.
1137  *
1138  * Load relcache entries for the system catalogs. This must create at
1139  * least the minimum set of "nailed-in" cache entries.
1140  */
1142 
1143  /* set up ACL framework (so CheckMyDatabase can check permissions) */
1144  initialize_acl();
1145 
1146  /*
1147  * Re-read the pg_database row for our database, check permissions and set
1148  * up database-specific GUC settings. We can't do this until all the
1149  * database-access infrastructure is up. (Also, it wants to know if the
1150  * user is a superuser, so the above stuff has to happen first.)
1151  */
1152  if (!bootstrap)
1153  CheckMyDatabase(dbname, am_superuser, override_allow_connections);
1154 
1155  /*
1156  * Now process any command-line switches and any additional GUC variable
1157  * settings passed in the startup packet. We couldn't do this before
1158  * because we didn't know if client is a superuser.
1159  */
1160  if (MyProcPort != NULL)
1161  process_startup_options(MyProcPort, am_superuser);
1162 
1163  /* Process pg_db_role_setting options */
1165 
1166  /* Apply PostAuthDelay as soon as we've read all options */
1167  if (PostAuthDelay > 0)
1168  pg_usleep(PostAuthDelay * 1000000L);
1169 
1170  /*
1171  * Initialize various default states that can't be set up until we've
1172  * selected the active user and gotten the right GUC settings.
1173  */
1174 
1175  /* set default namespace search path */
1177 
1178  /* initialize client encoding */
1180 
1181  /* Initialize this backend's session state. */
1183 
1184  /*
1185  * If this is an interactive session, load any libraries that should be
1186  * preloaded at backend start. Since those are determined by GUCs, this
1187  * can't happen until GUC settings are complete, but we want it to happen
1188  * during the initial transaction in case anything that requires database
1189  * access needs to be done.
1190  */
1191  if (load_session_libraries)
1193 
1194  /* report this backend in the PgBackendStatus array */
1195  if (!bootstrap)
1196  pgstat_bestart();
1197 
1198  /* close the transaction we started above */
1199  if (!bootstrap)
1201 }
void initialize_acl(void)
Definition: acl.c:4743
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:3308
void pgstat_beinit(void)
void pgstat_bestart(void)
#define InvalidBackendId
Definition: backendid.h:23
#define OidIsValid(objectId)
Definition: c.h:711
int errcode_for_file_access(void)
Definition: elog.c:718
#define DEBUG3
Definition: elog.h:24
bool IsBinaryUpgrade
Definition: globals.c:114
bool IsBackgroundWorker
Definition: globals.c:115
BackendId MyBackendId
Definition: globals.c:85
Oid MyDatabaseTableSpace
Definition: globals.c:91
struct Port * MyProcPort
Definition: globals.c:47
const char * hba_authname(UserAuth auth_method)
Definition: hba.c:3118
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:333
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1046
#define RowExclusiveLock
Definition: lockdefs.h:38
void InitializeClientEncoding(void)
Definition: mbutils.c:281
void pfree(void *pointer)
Definition: mcxt.c:1306
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:402
void InitializeSystemUser(const char *authn_id, const char *auth_method)
Definition: miscinit.c:838
void InitializeSessionUserIdStandalone(void)
Definition: miscinit.c:815
void process_session_preload_libraries(void)
Definition: miscinit.c:1844
Oid GetSessionUserId(void)
Definition: miscinit.c:531
void SetDatabasePath(const char *path)
Definition: miscinit.c:310
void InitializeSessionUserId(const char *rolename, Oid roleid)
Definition: miscinit.c:712
ClientConnectionInfo MyClientConnectionInfo
Definition: miscinit.c:997
bool has_rolreplication(Oid roleid)
Definition: miscinit.c:694
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1697
void InitializeSearchPath(void)
Definition: namespace.c:4369
#define NAMEDATALEN
const char * username
Definition: pgbench.c:305
void pgstat_before_server_shutdown(int code, Datum arg)
Definition: pgstat.c:448
void InitPlanCache(void)
Definition: plancache.c:127
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
void EnablePortalManager(void)
Definition: portalmem.c:105
int PostAuthDelay
Definition: postgres.c:96
static void ShutdownPostgres(int code, Datum arg)
Definition: postinit.c:1307
static void IdleInTransactionSessionTimeoutHandler(void)
Definition: postinit.c:1356
static void LockTimeoutHandler(void)
Definition: postinit.c:1346
static void IdleStatsUpdateTimeoutHandler(void)
Definition: postinit.c:1372
static void process_settings(Oid databaseid, Oid roleid)
Definition: postinit.c:1273
static void IdleSessionTimeoutHandler(void)
Definition: postinit.c:1364
static void process_startup_options(Port *port, bool am_superuser)
Definition: postinit.c:1208
static void StatementTimeoutHandler(void)
Definition: postinit.c:1324
static void CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections)
Definition: postinit.c:311
static bool ThereIsAtLeastOneRole(void)
Definition: postinit.c:1391
static void PerformAuthentication(Port *port)
Definition: postinit.c:190
static void ClientCheckTimeoutHandler(void)
Definition: postinit.c:1380
static HeapTuple GetDatabaseTuple(const char *dbname)
Definition: postinit.c:101
static HeapTuple GetDatabaseTupleByOid(Oid dboid)
Definition: postinit.c:144
int ReservedBackends
Definition: postmaster.c:216
short access
Definition: preproc-type.c:36
void ProcSignalInit(int pss_idx)
Definition: procsignal.c:161
void RelationCacheInitializePhase3(void)
Definition: relcache.c:4031
void RelationCacheInitialize(void)
Definition: relcache.c:3926
void RelationCacheInitializePhase2(void)
Definition: relcache.c:3972
char * GetDatabasePath(Oid dbOid, Oid spcOid)
Definition: relpath.c:110
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:912
ResourceOwner CurrentResourceOwner
Definition: resowner.c:146
void CreateAuxProcessResourceOwner(void)
Definition: resowner.c:892
void InitializeSession(void)
Definition: session.c:54
void pg_usleep(long microsec)
Definition: signal.c:53
void SharedInvalBackendInit(bool sendOnly)
Definition: sinvaladt.c:266
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:251
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:457
void CheckDeadLockAlert(void)
Definition: proc.c:1852
void InitProcessPhase2(void)
Definition: proc.c:480
bool HaveNFreeProcs(int n)
Definition: proc.c:659
const char * authn_id
Definition: libpq-be.h:113
UserAuth auth_method
Definition: libpq-be.h:119
Oid databaseId
Definition: proc.h:198
bool superuser(void)
Definition: superuser.c:46
void InitCatalogCache(void)
Definition: syscache.c:1067
TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
Definition: timeout.c:509
@ IDLE_SESSION_TIMEOUT
Definition: timeout.h:34
@ 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
@ IDLE_STATS_UPDATE_TIMEOUT
Definition: timeout.h:35
@ CLIENT_CONNECTION_CHECK_TIMEOUT
Definition: timeout.h:36
bool am_walsender
Definition: walsender.c:116
bool am_db_walsender
Definition: walsender.c:119
void StartTransactionCommand(void)
Definition: xact.c:2925
int XactIsoLevel
Definition: xact.c:78
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:898
void CommitTransactionCommand(void)
Definition: xact.c:3022
#define XACT_READ_COMMITTED
Definition: xact.h:37
void StartupXLOG(void)
Definition: xlog.c:5024
void ShutdownXLOG(int code, Datum arg)
Definition: xlog.c:6163

References am_db_walsender, am_walsender, Assert(), ClientConnectionInfo::auth_method, ClientConnectionInfo::authn_id, before_shmem_exit(), CheckDeadLockAlert(), CheckMyDatabase(), CLIENT_CONNECTION_CHECK_TIMEOUT, ClientCheckTimeoutHandler(), CommitTransactionCommand(), CreateAuxProcessResourceOwner(), CurrentResourceOwner, 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_rolreplication(), HaveNFreeProcs(), hba_authname(), HeapTupleIsValid, IDLE_IN_TRANSACTION_SESSION_TIMEOUT, IDLE_SESSION_TIMEOUT, IDLE_STATS_UPDATE_TIMEOUT, IdleInTransactionSessionTimeoutHandler(), IdleSessionTimeoutHandler(), IdleStatsUpdateTimeoutHandler(), InitCatalogCache(), initialize_acl(), InitializeClientEncoding(), InitializeSearchPath(), InitializeSession(), InitializeSessionUserId(), InitializeSessionUserIdStandalone(), InitializeSystemUser(), InitPlanCache(), InitProcessPhase2(), InvalidateCatalogSnapshot(), InvalidBackendId, IsAutoVacuumLauncherProcess(), IsAutoVacuumWorkerProcess(), IsBackgroundWorker, IsBinaryUpgrade, IsBootstrapProcessingMode, IsUnderPostmaster, LOCK_TIMEOUT, LockSharedObject(), LockTimeoutHandler(), MaxBackends, MyBackendId, MyClientConnectionInfo, MyDatabaseId, MyDatabaseTableSpace, MyProc, MyProcPort, NAMEDATALEN, NameStr, 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(), ReservedBackends, RowExclusiveLock, SetCurrentStatementStartTimestamp(), SetDatabasePath(), SharedInvalBackendInit(), ShutdownPostgres(), ShutdownXLOG(), StartTransactionCommand(), StartupXLOG(), STATEMENT_TIMEOUT, StatementTimeoutHandler(), strlcpy(), superuser(), ThereIsAtLeastOneRole(), username, ValidatePgVersion(), WARNING, XACT_READ_COMMITTED, and XactIsoLevel.

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

◆ LockTimeoutHandler()

static void LockTimeoutHandler ( void  )
static

Definition at line 1346 of file postinit.c.

1347 {
1348 #ifdef HAVE_SETSID
1349  /* try to signal whole process group */
1350  kill(-MyProcPid, SIGINT);
1351 #endif
1352  kill(MyProcPid, SIGINT);
1353 }
int MyProcPid
Definition: globals.c:44
#define kill(pid, sig)
Definition: win32_port.h:482

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, principal=%s)"),
286  be_gssapi_get_auth(port) ? _("yes") : _("no"),
287  be_gssapi_get_enc(port) ? _("yes") : _("no"),
288  princ);
289  else
290  appendStringInfo(&logmsg,
291  _(" GSS (authenticated=%s, encrypted=%s)"),
292  be_gssapi_get_auth(port) ? _("yes") : _("no"),
293  be_gssapi_get_enc(port) ? _("yes") : _("no"));
294  }
295 #endif
296 
297  ereport(LOG, errmsg_internal("%s", logmsg.data));
298  pfree(logmsg.data);
299  }
300 
301  set_ps_display("startup");
302 
303  ClientAuthInProgress = false; /* client_min_messages is active now */
304 }
void ClientAuthentication(Port *port)
Definition: auth.c:379
bool be_gssapi_get_auth(Port *port)
bool be_gssapi_get_enc(Port *port)
const char * be_gssapi_get_princ(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:993
#define _(x)
Definition: elog.c:90
#define LOG
Definition: elog.h:27
char * HbaFileName
Definition: guc_tables.c:504
bool load_ident(void)
Definition: hba.c:3001
bool load_hba(void)
Definition: hba.c:2637
MemoryContext TopMemoryContext
Definition: mcxt.c:130
MemoryContext PostmasterContext
Definition: mcxt.c:132
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
static int port
Definition: pg_regress.c:90
bool Log_connections
Definition: postmaster.c:229
bool ClientAuthInProgress
Definition: postmaster.c:347
int AuthenticationTimeout
Definition: postmaster.c:226
void set_ps_display(const char *activity)
Definition: ps_status.c:342
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:564
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:689

References _, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, am_walsender, appendStringInfo(), AuthenticationTimeout, be_gssapi_get_auth(), 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 495 of file postinit.c.

496 {
497  StringInfoData s;
498 
499  initStringInfo(&s);
500 
501  while (*optstr)
502  {
503  bool last_was_escape = false;
504 
505  resetStringInfo(&s);
506 
507  /* skip over leading space */
508  while (isspace((unsigned char) *optstr))
509  optstr++;
510 
511  if (*optstr == '\0')
512  break;
513 
514  /*
515  * Parse a single option, stopping at the first space, unless it's
516  * escaped.
517  */
518  while (*optstr)
519  {
520  if (isspace((unsigned char) *optstr) && !last_was_escape)
521  break;
522 
523  if (!last_was_escape && *optstr == '\\')
524  last_was_escape = true;
525  else
526  {
527  last_was_escape = false;
528  appendStringInfoChar(&s, *optstr);
529  }
530 
531  optstr++;
532  }
533 
534  /* now store the option in the next argv[] position */
535  argv[(*argcp)++] = pstrdup(s.data);
536  }
537 
538  pfree(s.data);
539 }
char * pstrdup(const char *in)
Definition: mcxt.c:1483
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188

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 1273 of file postinit.c.

1274 {
1275  Relation relsetting;
1276  Snapshot snapshot;
1277 
1278  if (!IsUnderPostmaster)
1279  return;
1280 
1281  relsetting = table_open(DbRoleSettingRelationId, AccessShareLock);
1282 
1283  /* read all the settings under the same snapshot for efficiency */
1284  snapshot = RegisterSnapshot(GetCatalogSnapshot(DbRoleSettingRelationId));
1285 
1286  /* Later settings are ignored if set earlier. */
1287  ApplySetting(snapshot, databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
1288  ApplySetting(snapshot, InvalidOid, roleid, relsetting, PGC_S_USER);
1289  ApplySetting(snapshot, databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
1290  ApplySetting(snapshot, InvalidOid, InvalidOid, relsetting, PGC_S_GLOBAL);
1291 
1292  UnregisterSnapshot(snapshot);
1293  table_close(relsetting, AccessShareLock);
1294 }
@ 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:387
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:871
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:829

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 1208 of file postinit.c.

1209 {
1210  GucContext gucctx;
1211  ListCell *gucopts;
1212 
1213  gucctx = am_superuser ? PGC_SU_BACKEND : PGC_BACKEND;
1214 
1215  /*
1216  * First process any command-line switches that were included in the
1217  * startup packet, if we are in a regular backend.
1218  */
1219  if (port->cmdline_options != NULL)
1220  {
1221  /*
1222  * The maximum possible number of commandline arguments that could
1223  * come from port->cmdline_options is (strlen + 1) / 2; see
1224  * pg_split_opts().
1225  */
1226  char **av;
1227  int maxac;
1228  int ac;
1229 
1230  maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
1231 
1232  av = (char **) palloc(maxac * sizeof(char *));
1233  ac = 0;
1234 
1235  av[ac++] = "postgres";
1236 
1237  pg_split_opts(av, &ac, port->cmdline_options);
1238 
1239  av[ac] = NULL;
1240 
1241  Assert(ac < maxac);
1242 
1243  (void) process_postgres_switches(ac, av, gucctx, NULL);
1244  }
1245 
1246  /*
1247  * Process any additional GUC variable settings passed in startup packet.
1248  * These are handled exactly like command-line variables.
1249  */
1250  gucopts = list_head(port->guc_options);
1251  while (gucopts)
1252  {
1253  char *name;
1254  char *value;
1255 
1256  name = lfirst(gucopts);
1257  gucopts = lnext(port->guc_options, gucopts);
1258 
1259  value = lfirst(gucopts);
1260  gucopts = lnext(port->guc_options, gucopts);
1261 
1263  }
1264 }
@ PGC_S_CLIENT
Definition: guc.h:118
GucContext
Definition: guc.h:68
@ PGC_SU_BACKEND
Definition: guc.h:72
static struct @143 value
void * palloc(Size size)
Definition: mcxt.c:1199
#define lfirst(lc)
Definition: pg_list.h:170
static ListCell * list_head(const List *l)
Definition: pg_list.h:126
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:341
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3682
void pg_split_opts(char **argv, int *argcp, const char *optstr)
Definition: postinit.c:495
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 1307 of file postinit.c.

1308 {
1309  /* Make sure we've killed any active transaction */
1311 
1312  /*
1313  * User locks are not released by transaction end, so be sure to release
1314  * them explicitly.
1315  */
1317 }
void LockReleaseAll(LOCKMETHODID lockmethodid, bool allLocks)
Definition: lock.c:2180
#define USER_LOCKMETHOD
Definition: lock.h:131
void AbortOutOfAnyTransaction(void)
Definition: xact.c:4692

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

Referenced by InitPostgres().

◆ StatementTimeoutHandler()

static void StatementTimeoutHandler ( void  )
static

Definition at line 1324 of file postinit.c.

1325 {
1326  int sig = SIGINT;
1327 
1328  /*
1329  * During authentication the timeout is used to deal with
1330  * authentication_timeout - we want to quit in response to such timeouts.
1331  */
1333  sig = SIGTERM;
1334 
1335 #ifdef HAVE_SETSID
1336  /* try to signal whole process group */
1337  kill(-MyProcPid, sig);
1338 #endif
1339  kill(MyProcPid, sig);
1340 }
static int sig
Definition: pg_ctl.c:79

References ClientAuthInProgress, kill, MyProcPid, and sig.

Referenced by InitPostgres().

◆ ThereIsAtLeastOneRole()

static bool ThereIsAtLeastOneRole ( void  )
static

Definition at line 1391 of file postinit.c.

1392 {
1393  Relation pg_authid_rel;
1394  TableScanDesc scan;
1395  bool result;
1396 
1397  pg_authid_rel = table_open(AuthIdRelationId, AccessShareLock);
1398 
1399  scan = table_beginscan_catalog(pg_authid_rel, 0, NULL);
1400  result = (heap_getnext(scan, ForwardScanDirection) != NULL);
1401 
1402  table_endscan(scan);
1403  table_close(pg_authid_rel, AccessShareLock);
1404 
1405  return result;
1406 }
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1299
@ ForwardScanDirection
Definition: sdir.h:26
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:993

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

Referenced by InitPostgres().