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 "catalog/catalog.h"
#include "catalog/namespace.h"
#include "catalog/pg_authid.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/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/fmgroids.h"
#include "utils/guc.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 InitCommunication (void)
 
static void ShutdownPostgres (int code, Datum arg)
 
static void StatementTimeoutHandler (void)
 
static void LockTimeoutHandler (void)
 
static void IdleInTransactionSessionTimeoutHandler (void)
 
static void IdleSessionTimeoutHandler (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, char *out_dbname, bool override_allow_connections)
 

Function Documentation

◆ BaseInit()

void BaseInit ( void  )

Definition at line 537 of file postinit.c.

References DebugFileOpen(), InitBufferPoolAccess(), InitCommunication(), InitFileAccess(), InitSync(), and smgrinit().

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

538 {
539  /*
540  * Attach to shared memory and semaphores, and initialize our
541  * input/output/debugging file descriptors.
542  */
544  DebugFileOpen();
545 
546  /* Do local initialization of file, storage and buffer managers */
547  InitFileAccess();
548  InitSync();
549  smgrinit();
551 }
static void InitCommunication(void)
Definition: postinit.c:429
void InitBufferPoolAccess(void)
Definition: bufmgr.c:2514
void DebugFileOpen(void)
Definition: elog.c:1927
void smgrinit(void)
Definition: smgr.c:111
void InitSync(void)
Definition: sync.c:128
void InitFileAccess(void)
Definition: fd.c:854

◆ CheckMyDatabase()

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

Definition at line 306 of file postinit.c.

References ACL_CONNECT, ACLCHECK_OK, check_strxfrm_bug(), CountDBConnections(), DATABASEOID, elog, ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, FATAL, GetDatabaseEncodingName(), GETSTRUCT, GetUserId(), HeapTupleIsValid, IsAutoVacuumWorkerProcess(), IsUnderPostmaster, MyDatabaseId, NameStr, ObjectIdGetDatum, pg_database_aclcheck(), pg_perm_setlocale(), PGC_BACKEND, PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT, PGC_S_OVERRIDE, ReleaseSysCache(), SearchSysCache1(), SetConfigOption(), and SetDatabaseEncoding().

Referenced by InitPostgres().

307 {
308  HeapTuple tup;
309  Form_pg_database dbform;
310  char *collate;
311  char *ctype;
312 
313  /* Fetch our pg_database row normally, via syscache */
315  if (!HeapTupleIsValid(tup))
316  elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
317  dbform = (Form_pg_database) GETSTRUCT(tup);
318 
319  /* This recheck is strictly paranoia */
320  if (strcmp(name, NameStr(dbform->datname)) != 0)
321  ereport(FATAL,
322  (errcode(ERRCODE_UNDEFINED_DATABASE),
323  errmsg("database \"%s\" has disappeared from pg_database",
324  name),
325  errdetail("Database OID %u now seems to belong to \"%s\".",
326  MyDatabaseId, NameStr(dbform->datname))));
327 
328  /*
329  * Check permissions to connect to the database.
330  *
331  * These checks are not enforced when in standalone mode, so that there is
332  * a way to recover from disabling all access to all databases, for
333  * example "UPDATE pg_database SET datallowconn = false;".
334  *
335  * We do not enforce them for autovacuum worker processes either.
336  */
338  {
339  /*
340  * Check that the database is currently allowing connections.
341  */
342  if (!dbform->datallowconn && !override_allow_connections)
343  ereport(FATAL,
344  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
345  errmsg("database \"%s\" is not currently accepting connections",
346  name)));
347 
348  /*
349  * Check privilege to connect to the database. (The am_superuser test
350  * is redundant, but since we have the flag, might as well check it
351  * and save a few cycles.)
352  */
353  if (!am_superuser &&
356  ereport(FATAL,
357  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
358  errmsg("permission denied for database \"%s\"", name),
359  errdetail("User does not have CONNECT privilege.")));
360 
361  /*
362  * Check connection limit for this database.
363  *
364  * There is a race condition here --- we create our PGPROC before
365  * checking for other PGPROCs. If two backends did this at about the
366  * same time, they might both think they were over the limit, while
367  * ideally one should succeed and one fail. Getting that to work
368  * exactly seems more trouble than it is worth, however; instead we
369  * just document that the connection limit is approximate.
370  */
371  if (dbform->datconnlimit >= 0 &&
372  !am_superuser &&
373  CountDBConnections(MyDatabaseId) > dbform->datconnlimit)
374  ereport(FATAL,
375  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
376  errmsg("too many connections for database \"%s\"",
377  name)));
378  }
379 
380  /*
381  * OK, we're golden. Next to-do item is to save the encoding info out of
382  * the pg_database tuple.
383  */
384  SetDatabaseEncoding(dbform->encoding);
385  /* Record it as a GUC internal option, too */
386  SetConfigOption("server_encoding", GetDatabaseEncodingName(),
388  /* If we have no other source of client_encoding, use server encoding */
389  SetConfigOption("client_encoding", GetDatabaseEncodingName(),
391 
392  /* assign locale variables */
393  collate = NameStr(dbform->datcollate);
394  ctype = NameStr(dbform->datctype);
395 
396  if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
397  ereport(FATAL,
398  (errmsg("database locale is incompatible with operating system"),
399  errdetail("The database was initialized with LC_COLLATE \"%s\", "
400  " which is not recognized by setlocale().", collate),
401  errhint("Recreate the database with another locale or install the missing locale.")));
402 
403  if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
404  ereport(FATAL,
405  (errmsg("database locale is incompatible with operating system"),
406  errdetail("The database was initialized with LC_CTYPE \"%s\", "
407  " which is not recognized by setlocale().", ctype),
408  errhint("Recreate the database with another locale or install the missing locale.")));
409 
410  /* Make the locale settings visible as GUC variables, too */
411  SetConfigOption("lc_collate", collate, PGC_INTERNAL, PGC_S_OVERRIDE);
412  SetConfigOption("lc_ctype", ctype, PGC_INTERNAL, PGC_S_OVERRIDE);
413 
415 
416  ReleaseSysCache(tup);
417 }
int errhint(const char *fmt,...)
Definition: elog.c:1162
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Oid GetUserId(void)
Definition: miscinit.c:476
FormData_pg_database * Form_pg_database
Definition: pg_database.h:81
int errcode(int sqlerrcode)
Definition: elog.c:704
char * pg_perm_setlocale(int category, const char *locale)
Definition: pg_locale.c:148
int CountDBConnections(Oid databaseid)
Definition: procarray.c:3464
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:45
#define FATAL
Definition: elog.h:54
void check_strxfrm_bug(void)
Definition: pg_locale.c:1192
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:7879
bool IsUnderPostmaster
Definition: globals.c:110
int errdetail(const char *fmt,...)
Definition: elog.c:1048
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3394
#define ACL_CONNECT
Definition: parsenodes.h:86
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void SetDatabaseEncoding(int encoding)
Definition: mbutils.c:1045
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Oid MyDatabaseId
Definition: globals.c:86
#define ereport(elevel,...)
Definition: elog.h:155
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
AclResult pg_database_aclcheck(Oid db_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4575
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1157
const char * name
Definition: encode.c:515
int errmsg(const char *fmt,...)
Definition: elog.c:915
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:669

◆ GetDatabaseTuple()

static HeapTuple GetDatabaseTuple ( const char *  dbname)
static

Definition at line 96 of file postinit.c.

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

Referenced by InitPostgres().

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

◆ GetDatabaseTupleByOid()

static HeapTuple GetDatabaseTupleByOid ( Oid  dboid)
static

Definition at line 139 of file postinit.c.

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

Referenced by InitPostgres().

140 {
141  HeapTuple tuple;
142  Relation relation;
143  SysScanDesc scan;
144  ScanKeyData key[1];
145 
146  /*
147  * form a scan key
148  */
149  ScanKeyInit(&key[0],
150  Anum_pg_database_oid,
151  BTEqualStrategyNumber, F_OIDEQ,
152  ObjectIdGetDatum(dboid));
153 
154  /*
155  * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
156  * built the critical shared relcache entries (i.e., we're starting up
157  * without a shared relcache cache file).
158  */
159  relation = table_open(DatabaseRelationId, AccessShareLock);
160  scan = systable_beginscan(relation, DatabaseOidIndexId,
162  NULL,
163  1, key);
164 
165  tuple = systable_getnext(scan);
166 
167  /* Must copy tuple before releasing buffer */
168  if (HeapTupleIsValid(tuple))
169  tuple = heap_copytuple(tuple);
170 
171  /* all done */
172  systable_endscan(scan);
173  table_close(relation, AccessShareLock);
174 
175  return tuple;
176 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:680
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:593
#define AccessShareLock
Definition: lockdefs.h:36
bool criticalSharedRelcachesBuilt
Definition: relcache.c:144
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:381
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:500
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define DatabaseOidIndexId
Definition: pg_database.h:90
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ IdleInTransactionSessionTimeoutHandler()

static void IdleInTransactionSessionTimeoutHandler ( void  )
static

Definition at line 1231 of file postinit.c.

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

Referenced by InitPostgres().

1232 {
1234  InterruptPending = true;
1235  SetLatch(MyLatch);
1236 }
void SetLatch(Latch *latch)
Definition: latch.c:505
volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
Definition: globals.c:34
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
struct Latch * MyLatch
Definition: globals.c:55

◆ IdleSessionTimeoutHandler()

static void IdleSessionTimeoutHandler ( void  )
static

Definition at line 1239 of file postinit.c.

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

Referenced by InitPostgres().

1240 {
1242  InterruptPending = true;
1243  SetLatch(MyLatch);
1244 }
volatile sig_atomic_t IdleSessionTimeoutPending
Definition: globals.c:35
void SetLatch(Latch *latch)
Definition: latch.c:505
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
struct Latch * MyLatch
Definition: globals.c:55

◆ InitCommunication()

static void InitCommunication ( void  )
static

Definition at line 429 of file postinit.c.

References CreateSharedMemoryAndSemaphores(), and IsUnderPostmaster.

Referenced by BaseInit().

430 {
431  /*
432  * initialize shared memory and semaphores appropriately.
433  */
434  if (!IsUnderPostmaster) /* postmaster already did this */
435  {
436  /*
437  * We're running a postgres bootstrap process or a standalone backend,
438  * so we need to set up shmem.
439  */
441  }
442 }
bool IsUnderPostmaster
Definition: globals.c:110
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:95

◆ InitializeMaxBackends()

void InitializeMaxBackends ( void  )

Definition at line 515 of file postinit.c.

References Assert, autovacuum_max_workers, elog, ERROR, MAX_BACKENDS, max_wal_senders, max_worker_processes, MaxBackends, and MaxConnections.

Referenced by AuxiliaryProcessMain(), PostgresMain(), and PostmasterMain().

516 {
517  Assert(MaxBackends == 0);
518 
519  /* the extra unit accounts for the autovacuum launcher */
522 
523  /* internal error because the values were all checked previously */
525  elog(ERROR, "too many backends configured");
526 }
#define ERROR
Definition: elog.h:45
#define MAX_BACKENDS
Definition: postmaster.h:75
int MaxBackends
Definition: globals.c:137
int max_wal_senders
Definition: walsender.c:121
int MaxConnections
Definition: globals.c:134
int autovacuum_max_workers
Definition: autovacuum.c:115
#define Assert(condition)
Definition: c.h:792
#define elog(elevel,...)
Definition: elog.h:228
int max_worker_processes
Definition: globals.c:135

◆ InitPostgres()

void InitPostgres ( const char *  in_dbname,
Oid  dboid,
const char *  username,
Oid  useroid,
char *  out_dbname,
bool  override_allow_connections 
)

Definition at line 579 of file postinit.c.

References am_db_walsender, am_walsender, Assert, before_shmem_exit(), CAC_SUPERUSER, Port::canAcceptConnections, CheckDeadLockAlert(), CheckMyDatabase(), 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(), HeapTupleIsValid, IDLE_IN_TRANSACTION_SESSION_TIMEOUT, IDLE_SESSION_TIMEOUT, IdleInTransactionSessionTimeoutHandler(), IdleSessionTimeoutHandler(), InitBufferPoolBackend(), InitCatalogCache(), initialize_acl(), InitializeClientEncoding(), InitializeSearchPath(), InitializeSession(), InitializeSessionUserId(), InitializeSessionUserIdStandalone(), InitPlanCache(), InitProcessPhase2(), InvalidateCatalogSnapshot(), InvalidBackendId, IsAutoVacuumLauncherProcess(), IsAutoVacuumWorkerProcess(), IsBackgroundWorker, IsBinaryUpgrade, IsBootstrapProcessingMode, IsUnderPostmaster, LOCK_TIMEOUT, LockSharedObject(), LockTimeoutHandler(), MaxBackends, MyBackendId, MyDatabaseId, MyDatabaseTableSpace, MyProc, MyProcPort, NAMEDATALEN, NameStr, OidIsValid, on_shmem_exit(), PerformAuthentication(), pg_usleep(), pgstat_bestart(), pgstat_initialize(), PostAuthDelay, process_settings(), process_startup_options(), ProcSignalInit(), RecoveryInProgress(), RegisterTimeout(), RelationCacheInitialize(), RelationCacheInitializePhase2(), RelationCacheInitializePhase3(), ReleaseAuxProcessResources(), ReservedBackends, RowExclusiveLock, SetCurrentStatementStartTimestamp(), SetDatabasePath(), SharedInvalBackendInit(), ShutdownPostgres(), ShutdownXLOG(), StartTransactionCommand(), StartupXLOG(), STATEMENT_TIMEOUT, StatementTimeoutHandler(), strlcpy(), superuser(), ThereIsAtLeastOneRole(), ValidatePgVersion(), WARNING, XACT_READ_COMMITTED, and XactIsoLevel.

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

581 {
582  bool bootstrap = IsBootstrapProcessingMode();
583  bool am_superuser;
584  char *fullpath;
585  char dbname[NAMEDATALEN];
586 
587  elog(DEBUG3, "InitPostgres");
588 
589  /*
590  * Add my PGPROC struct to the ProcArray.
591  *
592  * Once I have done this, I am visible to other backends!
593  */
595 
596  /*
597  * Initialize my entry in the shared-invalidation manager's array of
598  * per-backend data.
599  *
600  * Sets up MyBackendId, a unique backend identifier.
601  */
603 
604  SharedInvalBackendInit(false);
605 
606  if (MyBackendId > MaxBackends || MyBackendId <= 0)
607  elog(FATAL, "bad backend ID: %d", MyBackendId);
608 
609  /* Now that we have a BackendId, we can participate in ProcSignal */
611 
612  /*
613  * Also set up timeout handlers needed for backend operation. We need
614  * these in every case except bootstrap.
615  */
616  if (!bootstrap)
617  {
624  }
625 
626  /*
627  * bufmgr needs another initialization call too
628  */
630 
631  /*
632  * Initialize local process's access to XLOG.
633  */
634  if (IsUnderPostmaster)
635  {
636  /*
637  * The postmaster already started the XLOG machinery, but we need to
638  * call InitXLOGAccess(), if the system isn't in hot-standby mode.
639  * This is handled by calling RecoveryInProgress and ignoring the
640  * result.
641  */
642  (void) RecoveryInProgress();
643  }
644  else
645  {
646  /*
647  * We are either a bootstrap process or a standalone backend. Either
648  * way, start up the XLOG machinery, and register to have it closed
649  * down at exit.
650  *
651  * We don't yet have an aux-process resource owner, but StartupXLOG
652  * and ShutdownXLOG will need one. Hence, create said resource owner
653  * (and register a callback to clean it up after ShutdownXLOG runs).
654  */
656 
657  StartupXLOG();
658  /* Release (and warn about) any buffer pins leaked in StartupXLOG */
660  /* Reset CurrentResourceOwner to nothing for the moment */
661  CurrentResourceOwner = NULL;
662 
664  }
665 
666  /*
667  * Initialize the relation cache and the system catalog caches. Note that
668  * no catalog access happens here; we only set up the hashtable structure.
669  * We must do this before starting a transaction because transaction abort
670  * would try to touch these hashtables.
671  */
674  InitPlanCache();
675 
676  /* Initialize portal manager */
678 
679  /* Initialize stats collection --- must happen before first xact */
680  if (!bootstrap)
682 
683  /*
684  * Load relcache entries for the shared system catalogs. This must create
685  * at least entries for pg_database and catalogs used for authentication.
686  */
688 
689  /*
690  * Set up process-exit callback to do pre-shutdown cleanup. This is the
691  * first before_shmem_exit callback we register; thus, this will be the
692  * last thing we do before low-level modules like the buffer manager begin
693  * to close down. We need to have this in place before we begin our first
694  * transaction --- if we fail during the initialization transaction, as is
695  * entirely possible, we need the AbortTransaction call to clean up.
696  */
698 
699  /* The autovacuum launcher is done here */
701  {
702  /* report this backend in the PgBackendStatus array */
703  pgstat_bestart();
704 
705  return;
706  }
707 
708  /*
709  * Start a new transaction here before first access to db, and get a
710  * snapshot. We don't have a use for the snapshot itself, but we're
711  * interested in the secondary effect that it sets RecentGlobalXmin. (This
712  * is critical for anything that reads heap pages, because HOT may decide
713  * to prune them even if the process doesn't attempt to modify any
714  * tuples.)
715  *
716  * FIXME: This comment is inaccurate / the code buggy. A snapshot that is
717  * not pushed/active does not reliably prevent HOT pruning (->xmin could
718  * e.g. be cleared when cache invalidations are processed).
719  */
720  if (!bootstrap)
721  {
722  /* statement_timestamp must be set for timeouts to work correctly */
725 
726  /*
727  * transaction_isolation will have been set to the default by the
728  * above. If the default is "serializable", and we are in hot
729  * standby, we will fail if we don't change it to something lower.
730  * Fortunately, "read committed" is plenty good enough.
731  */
733 
734  (void) GetTransactionSnapshot();
735  }
736 
737  /*
738  * Perform client authentication if necessary, then figure out our
739  * postgres user ID, and see if we are a superuser.
740  *
741  * In standalone mode and in autovacuum worker processes, we use a fixed
742  * ID, otherwise we figure it out from the authenticated user name.
743  */
744  if (bootstrap || IsAutoVacuumWorkerProcess())
745  {
747  am_superuser = true;
748  }
749  else if (!IsUnderPostmaster)
750  {
752  am_superuser = true;
753  if (!ThereIsAtLeastOneRole())
755  (errcode(ERRCODE_UNDEFINED_OBJECT),
756  errmsg("no roles are defined in this database system"),
757  errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
758  username != NULL ? username : "postgres")));
759  }
760  else if (IsBackgroundWorker)
761  {
762  if (username == NULL && !OidIsValid(useroid))
763  {
765  am_superuser = true;
766  }
767  else
768  {
770  am_superuser = superuser();
771  }
772  }
773  else
774  {
775  /* normal multiuser case */
776  Assert(MyProcPort != NULL);
779  am_superuser = superuser();
780  }
781 
782  /*
783  * If we're trying to shut down, only superusers can connect, and new
784  * replication connections are not allowed.
785  */
786  if ((!am_superuser || am_walsender) &&
787  MyProcPort != NULL &&
789  {
790  if (am_walsender)
791  ereport(FATAL,
792  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
793  errmsg("new replication connections are not allowed during database shutdown")));
794  else
795  ereport(FATAL,
796  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
797  errmsg("must be superuser to connect during database shutdown")));
798  }
799 
800  /*
801  * Binary upgrades only allowed super-user connections
802  */
803  if (IsBinaryUpgrade && !am_superuser)
804  {
805  ereport(FATAL,
806  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
807  errmsg("must be superuser to connect in binary upgrade mode")));
808  }
809 
810  /*
811  * The last few connection slots are reserved for superusers. Replication
812  * connections are drawn from slots reserved with max_wal_senders and not
813  * limited by max_connections or superuser_reserved_connections.
814  */
815  if (!am_superuser && !am_walsender &&
816  ReservedBackends > 0 &&
818  ereport(FATAL,
819  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
820  errmsg("remaining connection slots are reserved for non-replication superuser connections")));
821 
822  /* Check replication permissions needed for walsender processes. */
823  if (am_walsender)
824  {
825  Assert(!bootstrap);
826 
827  if (!superuser() && !has_rolreplication(GetUserId()))
828  ereport(FATAL,
829  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
830  errmsg("must be superuser or replication role to start walsender")));
831  }
832 
833  /*
834  * If this is a plain walsender only supporting physical replication, we
835  * don't want to connect to any particular database. Just finish the
836  * backend startup by processing any options from the startup packet, and
837  * we're done.
838  */
840  {
841  /* process any options passed in the startup packet */
842  if (MyProcPort != NULL)
843  process_startup_options(MyProcPort, am_superuser);
844 
845  /* Apply PostAuthDelay as soon as we've read all options */
846  if (PostAuthDelay > 0)
847  pg_usleep(PostAuthDelay * 1000000L);
848 
849  /* initialize client encoding */
851 
852  /* report this backend in the PgBackendStatus array */
853  pgstat_bestart();
854 
855  /* close the transaction we started above */
857 
858  return;
859  }
860 
861  /*
862  * Set up the global variables holding database id and default tablespace.
863  * But note we won't actually try to touch the database just yet.
864  *
865  * We take a shortcut in the bootstrap case, otherwise we have to look up
866  * the db's entry in pg_database.
867  */
868  if (bootstrap)
869  {
870  MyDatabaseId = TemplateDbOid;
871  MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
872  }
873  else if (in_dbname != NULL)
874  {
875  HeapTuple tuple;
876  Form_pg_database dbform;
877 
878  tuple = GetDatabaseTuple(in_dbname);
879  if (!HeapTupleIsValid(tuple))
880  ereport(FATAL,
881  (errcode(ERRCODE_UNDEFINED_DATABASE),
882  errmsg("database \"%s\" does not exist", in_dbname)));
883  dbform = (Form_pg_database) GETSTRUCT(tuple);
884  MyDatabaseId = dbform->oid;
885  MyDatabaseTableSpace = dbform->dattablespace;
886  /* take database name from the caller, just for paranoia */
887  strlcpy(dbname, in_dbname, sizeof(dbname));
888  }
889  else if (OidIsValid(dboid))
890  {
891  /* caller specified database by OID */
892  HeapTuple tuple;
893  Form_pg_database dbform;
894 
895  tuple = GetDatabaseTupleByOid(dboid);
896  if (!HeapTupleIsValid(tuple))
897  ereport(FATAL,
898  (errcode(ERRCODE_UNDEFINED_DATABASE),
899  errmsg("database %u does not exist", dboid)));
900  dbform = (Form_pg_database) GETSTRUCT(tuple);
901  MyDatabaseId = dbform->oid;
902  MyDatabaseTableSpace = dbform->dattablespace;
903  Assert(MyDatabaseId == dboid);
904  strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
905  /* pass the database name back to the caller */
906  if (out_dbname)
907  strcpy(out_dbname, dbname);
908  }
909  else
910  {
911  /*
912  * If this is a background worker not bound to any particular
913  * database, we're done now. Everything that follows only makes sense
914  * if we are bound to a specific database. We do need to close the
915  * transaction we started before returning.
916  */
917  if (!bootstrap)
918  {
919  pgstat_bestart();
921  }
922  return;
923  }
924 
925  /*
926  * Now, take a writer's lock on the database we are trying to connect to.
927  * If there is a concurrently running DROP DATABASE on that database, this
928  * will block us until it finishes (and has committed its update of
929  * pg_database).
930  *
931  * Note that the lock is not held long, only until the end of this startup
932  * transaction. This is OK since we will advertise our use of the
933  * database in the ProcArray before dropping the lock (in fact, that's the
934  * next thing to do). Anyone trying a DROP DATABASE after this point will
935  * see us in the array once they have the lock. Ordering is important for
936  * this because we don't want to advertise ourselves as being in this
937  * database until we have the lock; otherwise we create what amounts to a
938  * deadlock with CountOtherDBBackends().
939  *
940  * Note: use of RowExclusiveLock here is reasonable because we envision
941  * our session as being a concurrent writer of the database. If we had a
942  * way of declaring a session as being guaranteed-read-only, we could use
943  * AccessShareLock for such sessions and thereby not conflict against
944  * CREATE DATABASE.
945  */
946  if (!bootstrap)
947  LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
949 
950  /*
951  * Now we can mark our PGPROC entry with the database ID.
952  *
953  * We assume this is an atomic store so no lock is needed; though actually
954  * things would work fine even if it weren't atomic. Anyone searching the
955  * ProcArray for this database's ID should hold the database lock, so they
956  * would not be executing concurrently with this store. A process looking
957  * for another database's ID could in theory see a chance match if it read
958  * a partially-updated databaseId value; but as long as all such searches
959  * wait and retry, as in CountOtherDBBackends(), they will certainly see
960  * the correct value on their next try.
961  */
963 
964  /*
965  * We established a catalog snapshot while reading pg_authid and/or
966  * pg_database; but until we have set up MyDatabaseId, we won't react to
967  * incoming sinval messages for unshared catalogs, so we won't realize it
968  * if the snapshot has been invalidated. Assume it's no good anymore.
969  */
971 
972  /*
973  * Recheck pg_database to make sure the target database hasn't gone away.
974  * If there was a concurrent DROP DATABASE, this ensures we will die
975  * cleanly without creating a mess.
976  */
977  if (!bootstrap)
978  {
979  HeapTuple tuple;
980 
981  tuple = GetDatabaseTuple(dbname);
982  if (!HeapTupleIsValid(tuple) ||
983  MyDatabaseId != ((Form_pg_database) GETSTRUCT(tuple))->oid ||
984  MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
985  ereport(FATAL,
986  (errcode(ERRCODE_UNDEFINED_DATABASE),
987  errmsg("database \"%s\" does not exist", dbname),
988  errdetail("It seems to have just been dropped or renamed.")));
989  }
990 
991  /*
992  * Now we should be able to access the database directory safely. Verify
993  * it's there and looks reasonable.
994  */
996 
997  if (!bootstrap)
998  {
999  if (access(fullpath, F_OK) == -1)
1000  {
1001  if (errno == ENOENT)
1002  ereport(FATAL,
1003  (errcode(ERRCODE_UNDEFINED_DATABASE),
1004  errmsg("database \"%s\" does not exist",
1005  dbname),
1006  errdetail("The database subdirectory \"%s\" is missing.",
1007  fullpath)));
1008  else
1009  ereport(FATAL,
1011  errmsg("could not access directory \"%s\": %m",
1012  fullpath)));
1013  }
1014 
1015  ValidatePgVersion(fullpath);
1016  }
1017 
1018  SetDatabasePath(fullpath);
1019 
1020  /*
1021  * It's now possible to do real access to the system catalogs.
1022  *
1023  * Load relcache entries for the system catalogs. This must create at
1024  * least the minimum set of "nailed-in" cache entries.
1025  */
1027 
1028  /* set up ACL framework (so CheckMyDatabase can check permissions) */
1029  initialize_acl();
1030 
1031  /*
1032  * Re-read the pg_database row for our database, check permissions and set
1033  * up database-specific GUC settings. We can't do this until all the
1034  * database-access infrastructure is up. (Also, it wants to know if the
1035  * user is a superuser, so the above stuff has to happen first.)
1036  */
1037  if (!bootstrap)
1038  CheckMyDatabase(dbname, am_superuser, override_allow_connections);
1039 
1040  /*
1041  * Now process any command-line switches and any additional GUC variable
1042  * settings passed in the startup packet. We couldn't do this before
1043  * because we didn't know if client is a superuser.
1044  */
1045  if (MyProcPort != NULL)
1046  process_startup_options(MyProcPort, am_superuser);
1047 
1048  /* Process pg_db_role_setting options */
1050 
1051  /* Apply PostAuthDelay as soon as we've read all options */
1052  if (PostAuthDelay > 0)
1053  pg_usleep(PostAuthDelay * 1000000L);
1054 
1055  /*
1056  * Initialize various default states that can't be set up until we've
1057  * selected the active user and gotten the right GUC settings.
1058  */
1059 
1060  /* set default namespace search path */
1062 
1063  /* initialize client encoding */
1065 
1066  /* Initialize this backend's session state. */
1068 
1069  /* report this backend in the PgBackendStatus array */
1070  if (!bootstrap)
1071  pgstat_bestart();
1072 
1073  /* close the transaction we started above */
1074  if (!bootstrap)
1076 }
int errhint(const char *fmt,...)
Definition: elog.c:1162
BackendId MyBackendId
Definition: globals.c:82
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
struct Port * MyProcPort
Definition: globals.c:44
CAC_state canAcceptConnections
Definition: libpq-be.h:133
void SharedInvalBackendInit(bool sendOnly)
Definition: sinvaladt.c:257
#define DEBUG3
Definition: elog.h:23
Oid GetUserId(void)
Definition: miscinit.c:476
FormData_pg_database * Form_pg_database
Definition: pg_database.h:81
PGPROC * MyProc
Definition: proc.c:68
static HeapTuple GetDatabaseTuple(const char *dbname)
Definition: postinit.c:96
ResourceOwner CurrentResourceOwner
Definition: resowner.c:144
void CommitTransactionCommand(void)
Definition: xact.c:2948
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:896
void InitializeSession(void)
Definition: session.c:54
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1528
void RelationCacheInitializePhase2(void)
Definition: relcache.c:3813
static void PerformAuthentication(Port *port)
Definition: postinit.c:185
static void LockTimeoutHandler(void)
Definition: postinit.c:1221
int errcode(int sqlerrcode)
Definition: elog.c:704
bool superuser(void)
Definition: superuser.c:46
void initialize_acl(void)
Definition: acl.c:4672
bool RecoveryInProgress(void)
Definition: xlog.c:8148
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
#define OidIsValid(objectId)
Definition: c.h:698
Oid GetSessionUserId(void)
Definition: miscinit.c:510
bool HaveNFreeProcs(int n)
Definition: proc.c:667
static void CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections)
Definition: postinit.c:306
bool IsBinaryUpgrade
Definition: globals.c:111
Oid MyDatabaseTableSpace
Definition: globals.c:88
bool IsBackgroundWorker
Definition: globals.c:112
void RelationCacheInitializePhase3(void)
Definition: relcache.c:3872
#define NAMEDATALEN
bool am_walsender
Definition: walsender.c:115
void pg_usleep(long microsec)
Definition: signal.c:53
int ReservedBackends
Definition: postmaster.c:216
#define FATAL
Definition: elog.h:54
void InitializeSearchPath(void)
Definition: namespace.c:4323
int MaxBackends
Definition: globals.c:137
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:361
bool IsUnderPostmaster
Definition: globals.c:110
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:1048
int errcode_for_file_access(void)
Definition: elog.c:727
static void IdleInTransactionSessionTimeoutHandler(void)
Definition: postinit.c:1231
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:333
Oid databaseId
Definition: proc.h:154
void pgstat_initialize(void)
Definition: pgstat.c:3096
static bool ThereIsAtLeastOneRole(void)
Definition: postinit.c:1250
void StartupXLOG(void)
Definition: xlog.c:6377
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3394
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:456
char * GetDatabasePath(Oid dbNode, Oid spcNode)
Definition: relpath.c:110
void SetDatabasePath(const char *path)
Definition: miscinit.c:289
#define WARNING
Definition: elog.h:40
void ShutdownXLOG(int code, Datum arg)
Definition: xlog.c:8564
static HeapTuple GetDatabaseTupleByOid(Oid dboid)
Definition: postinit.c:139
#define InvalidBackendId
Definition: backendid.h:23
bool am_db_walsender
Definition: walsender.c:118
Oid MyDatabaseId
Definition: globals.c:86
int PostAuthDelay
Definition: postgres.c:103
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1017
void EnablePortalManager(void)
Definition: portalmem.c:104
static void ShutdownPostgres(int code, Datum arg)
Definition: postinit.c:1182
static char * username
Definition: initdb.c:134
#define ereport(elevel,...)
Definition: elog.h:155
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
Definition: timeout.c:469
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:3388
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:792
void InitializeSessionUserIdStandalone(void)
Definition: miscinit.c:778
void StartTransactionCommand(void)
Definition: xact.c:2847
void CreateAuxProcessResourceOwner(void)
Definition: resowner.c:875
#define XACT_READ_COMMITTED
Definition: xact.h:37
static void IdleSessionTimeoutHandler(void)
Definition: postinit.c:1239
void InitializeSessionUserId(const char *rolename, Oid roleid)
Definition: miscinit.c:675
char * dbname
Definition: streamutil.c:51
static void process_startup_options(Port *port, bool am_superuser)
Definition: postinit.c:1083
int XactIsoLevel
Definition: xact.c:75
bool has_rolreplication(Oid roleid)
Definition: miscinit.c:657
void InitializeClientEncoding(void)
Definition: mbutils.c:281
void InitPlanCache(void)
Definition: plancache.c:127
void InitProcessPhase2(void)
Definition: proc.c:477
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:394
void RelationCacheInitialize(void)
Definition: relcache.c:3777
void ProcSignalInit(int pss_idx)
Definition: procsignal.c:157
void InitCatalogCache(void)
Definition: syscache.c:1021
static void StatementTimeoutHandler(void)
Definition: postinit.c:1199
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:833
int errmsg(const char *fmt,...)
Definition: elog.c:915
void pgstat_bestart(void)
Definition: pgstat.c:3145
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:669
static void process_settings(Oid databaseid, Oid roleid)
Definition: postinit.c:1148
void CheckDeadLockAlert(void)
Definition: proc.c:1841
void InitBufferPoolBackend(void)
Definition: bufmgr.c:2537

◆ LockTimeoutHandler()

static void LockTimeoutHandler ( void  )
static

Definition at line 1221 of file postinit.c.

References kill, and MyProcPid.

Referenced by InitPostgres().

1222 {
1223 #ifdef HAVE_SETSID
1224  /* try to signal whole process group */
1225  kill(-MyProcPid, SIGINT);
1226 #endif
1227  kill(MyProcPid, SIGINT);
1228 }
int MyProcPid
Definition: globals.c:41
#define kill(pid, sig)
Definition: win32_port.h:454

◆ PerformAuthentication()

static void PerformAuthentication ( Port port)
static

Definition at line 185 of file postinit.c.

References _, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, am_walsender, appendStringInfo(), Port::application_name, 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_compression(), be_tls_get_version(), ClientAuthentication(), ClientAuthInProgress, StringInfoData::data, Port::database_name, disable_timeout(), enable_timeout_after(), ereport, errmsg(), errmsg_internal(), FATAL, Port::gss, initStringInfo(), load_hba(), load_ident(), LOG, Log_connections, pfree(), PostmasterContext, set_ps_display(), Port::ssl_in_use, STATEMENT_TIMEOUT, TopMemoryContext, and Port::user_name.

Referenced by InitPostgres().

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

◆ pg_split_opts()

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

Definition at line 456 of file postinit.c.

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

Referenced by process_startup_options().

457 {
458  StringInfoData s;
459 
460  initStringInfo(&s);
461 
462  while (*optstr)
463  {
464  bool last_was_escape = false;
465 
466  resetStringInfo(&s);
467 
468  /* skip over leading space */
469  while (isspace((unsigned char) *optstr))
470  optstr++;
471 
472  if (*optstr == '\0')
473  break;
474 
475  /*
476  * Parse a single option, stopping at the first space, unless it's
477  * escaped.
478  */
479  while (*optstr)
480  {
481  if (isspace((unsigned char) *optstr) && !last_was_escape)
482  break;
483 
484  if (!last_was_escape && *optstr == '\\')
485  last_was_escape = true;
486  else
487  {
488  last_was_escape = false;
489  appendStringInfoChar(&s, *optstr);
490  }
491 
492  optstr++;
493  }
494 
495  /* now store the option in the next argv[] position */
496  argv[(*argcp)++] = pstrdup(s.data);
497  }
498 
499  pfree(s.data);
500 }
char * pstrdup(const char *in)
Definition: mcxt.c:1187
void pfree(void *pointer)
Definition: mcxt.c:1057
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59

◆ process_settings()

static void process_settings ( Oid  databaseid,
Oid  roleid 
)
static

Definition at line 1148 of file postinit.c.

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

1149 {
1150  Relation relsetting;
1151  Snapshot snapshot;
1152 
1153  if (!IsUnderPostmaster)
1154  return;
1155 
1156  relsetting = table_open(DbRoleSettingRelationId, AccessShareLock);
1157 
1158  /* read all the settings under the same snapshot for efficiency */
1159  snapshot = RegisterSnapshot(GetCatalogSnapshot(DbRoleSettingRelationId));
1160 
1161  /* Later settings are ignored if set earlier. */
1162  ApplySetting(snapshot, databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
1163  ApplySetting(snapshot, InvalidOid, roleid, relsetting, PGC_S_USER);
1164  ApplySetting(snapshot, databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
1165  ApplySetting(snapshot, InvalidOid, InvalidOid, relsetting, PGC_S_GLOBAL);
1166 
1167  UnregisterSnapshot(snapshot);
1168  table_close(relsetting, AccessShareLock);
1169 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:810
Snapshot GetCatalogSnapshot(Oid relid)
Definition: snapmgr.c:386
#define AccessShareLock
Definition: lockdefs.h:36
bool IsUnderPostmaster
Definition: globals.c:110
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:852
#define InvalidOid
Definition: postgres_ext.h:36
void ApplySetting(Snapshot snapshot, Oid databaseid, Oid roleid, Relation relsetting, GucSource source)
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ process_startup_options()

static void process_startup_options ( Port port,
bool  am_superuser 
)
static

Definition at line 1083 of file postinit.c.

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

Referenced by InitPostgres().

1084 {
1085  GucContext gucctx;
1086  ListCell *gucopts;
1087 
1088  gucctx = am_superuser ? PGC_SU_BACKEND : PGC_BACKEND;
1089 
1090  /*
1091  * First process any command-line switches that were included in the
1092  * startup packet, if we are in a regular backend.
1093  */
1094  if (port->cmdline_options != NULL)
1095  {
1096  /*
1097  * The maximum possible number of commandline arguments that could
1098  * come from port->cmdline_options is (strlen + 1) / 2; see
1099  * pg_split_opts().
1100  */
1101  char **av;
1102  int maxac;
1103  int ac;
1104 
1105  maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
1106 
1107  av = (char **) palloc(maxac * sizeof(char *));
1108  ac = 0;
1109 
1110  av[ac++] = "postgres";
1111 
1112  pg_split_opts(av, &ac, port->cmdline_options);
1113 
1114  av[ac] = NULL;
1115 
1116  Assert(ac < maxac);
1117 
1118  (void) process_postgres_switches(ac, av, gucctx, NULL);
1119  }
1120 
1121  /*
1122  * Process any additional GUC variable settings passed in startup packet.
1123  * These are handled exactly like command-line variables.
1124  */
1125  gucopts = list_head(port->guc_options);
1126  while (gucopts)
1127  {
1128  char *name;
1129  char *value;
1130 
1131  name = lfirst(gucopts);
1132  gucopts = lnext(port->guc_options, gucopts);
1133 
1134  value = lfirst(gucopts);
1135  gucopts = lnext(port->guc_options, gucopts);
1136 
1137  SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
1138  }
1139 }
GucContext
Definition: guc.h:68
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:310
static struct @144 value
List * guc_options
Definition: libpq-be.h:143
struct @15::@16 av[32]
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:7879
void pg_split_opts(char **argv, int *argcp, const char *optstr)
Definition: postinit.c:456
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
#define Assert(condition)
Definition: c.h:792
#define lfirst(lc)
Definition: pg_list.h:169
const char * name
Definition: encode.c:515
void * palloc(Size size)
Definition: mcxt.c:950
char * cmdline_options
Definition: libpq-be.h:142
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3583

◆ ShutdownPostgres()

static void ShutdownPostgres ( int  code,
Datum  arg 
)
static

Definition at line 1182 of file postinit.c.

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

Referenced by InitPostgres().

1183 {
1184  /* Make sure we've killed any active transaction */
1186 
1187  /*
1188  * User locks are not released by transaction end, so be sure to release
1189  * them explicitly.
1190  */
1192 }
void AbortOutOfAnyTransaction(void)
Definition: xact.c:4581
#define USER_LOCKMETHOD
Definition: lock.h:128
void LockReleaseAll(LOCKMETHODID lockmethodid, bool allLocks)
Definition: lock.c:2179

◆ StatementTimeoutHandler()

static void StatementTimeoutHandler ( void  )
static

Definition at line 1199 of file postinit.c.

References ClientAuthInProgress, kill, MyProcPid, and sig.

Referenced by InitPostgres().

1200 {
1201  int sig = SIGINT;
1202 
1203  /*
1204  * During authentication the timeout is used to deal with
1205  * authentication_timeout - we want to quit in response to such timeouts.
1206  */
1208  sig = SIGTERM;
1209 
1210 #ifdef HAVE_SETSID
1211  /* try to signal whole process group */
1212  kill(-MyProcPid, sig);
1213 #endif
1214  kill(MyProcPid, sig);
1215 }
int MyProcPid
Definition: globals.c:41
#define kill(pid, sig)
Definition: win32_port.h:454
bool ClientAuthInProgress
Definition: postmaster.c:362
static int sig
Definition: pg_ctl.c:84

◆ ThereIsAtLeastOneRole()

static bool ThereIsAtLeastOneRole ( void  )
static

Definition at line 1250 of file postinit.c.

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

Referenced by InitPostgres().

1251 {
1252  Relation pg_authid_rel;
1253  TableScanDesc scan;
1254  bool result;
1255 
1256  pg_authid_rel = table_open(AuthIdRelationId, AccessShareLock);
1257 
1258  scan = table_beginscan_catalog(pg_authid_rel, 0, NULL);
1259  result = (heap_getnext(scan, ForwardScanDirection) != NULL);
1260 
1261  table_endscan(scan);
1262  table_close(pg_authid_rel, AccessShareLock);
1263 
1264  return result;
1265 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
#define AccessShareLock
Definition: lockdefs.h:36
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1304
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:962
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39