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/indexing.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 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 548 of file postinit.c.

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

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

549 {
550  /*
551  * Attach to shared memory and semaphores, and initialize our
552  * input/output/debugging file descriptors.
553  */
555  DebugFileOpen();
556 
557  /* Do local initialization of file, storage and buffer managers */
558  InitFileAccess();
559  InitSync();
560  smgrinit();
562 }
static void InitCommunication(void)
Definition: postinit.c:440
void InitBufferPoolAccess(void)
Definition: bufmgr.c:2502
void DebugFileOpen(void)
Definition: elog.c:1839
void smgrinit(void)
Definition: smgr.c:111
void InitSync(void)
Definition: sync.c:128
void InitFileAccess(void)
Definition: fd.c:826

◆ CheckMyDatabase()

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

Definition at line 317 of file postinit.c.

References ACL_CONNECT, ACLCHECK_OK, check_strxfrm_bug(), CountDBConnections(), DATABASEOID, elog, ereport, errcode(), ERRCODE_INSUFFICIENT_PRIVILEGE, 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().

318 {
319  HeapTuple tup;
320  Form_pg_database dbform;
321  char *collate;
322  char *ctype;
323 
324  /* Fetch our pg_database row normally, via syscache */
326  if (!HeapTupleIsValid(tup))
327  elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
328  dbform = (Form_pg_database) GETSTRUCT(tup);
329 
330  /* This recheck is strictly paranoia */
331  if (strcmp(name, NameStr(dbform->datname)) != 0)
332  ereport(FATAL,
333  (errcode(ERRCODE_UNDEFINED_DATABASE),
334  errmsg("database \"%s\" has disappeared from pg_database",
335  name),
336  errdetail("Database OID %u now seems to belong to \"%s\".",
337  MyDatabaseId, NameStr(dbform->datname))));
338 
339  /*
340  * Check permissions to connect to the database.
341  *
342  * These checks are not enforced when in standalone mode, so that there is
343  * a way to recover from disabling all access to all databases, for
344  * example "UPDATE pg_database SET datallowconn = false;".
345  *
346  * We do not enforce them for autovacuum worker processes either.
347  */
349  {
350  /*
351  * Check that the database is currently allowing connections.
352  */
353  if (!dbform->datallowconn && !override_allow_connections)
354  ereport(FATAL,
355  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
356  errmsg("database \"%s\" is not currently accepting connections",
357  name)));
358 
359  /*
360  * Check privilege to connect to the database. (The am_superuser test
361  * is redundant, but since we have the flag, might as well check it
362  * and save a few cycles.)
363  */
364  if (!am_superuser &&
367  ereport(FATAL,
369  errmsg("permission denied for database \"%s\"", name),
370  errdetail("User does not have CONNECT privilege.")));
371 
372  /*
373  * Check connection limit for this database.
374  *
375  * There is a race condition here --- we create our PGPROC before
376  * checking for other PGPROCs. If two backends did this at about the
377  * same time, they might both think they were over the limit, while
378  * ideally one should succeed and one fail. Getting that to work
379  * exactly seems more trouble than it is worth, however; instead we
380  * just document that the connection limit is approximate.
381  */
382  if (dbform->datconnlimit >= 0 &&
383  !am_superuser &&
384  CountDBConnections(MyDatabaseId) > dbform->datconnlimit)
385  ereport(FATAL,
386  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
387  errmsg("too many connections for database \"%s\"",
388  name)));
389  }
390 
391  /*
392  * OK, we're golden. Next to-do item is to save the encoding info out of
393  * the pg_database tuple.
394  */
395  SetDatabaseEncoding(dbform->encoding);
396  /* Record it as a GUC internal option, too */
397  SetConfigOption("server_encoding", GetDatabaseEncodingName(),
399  /* If we have no other source of client_encoding, use server encoding */
400  SetConfigOption("client_encoding", GetDatabaseEncodingName(),
402 
403  /* assign locale variables */
404  collate = NameStr(dbform->datcollate);
405  ctype = NameStr(dbform->datctype);
406 
407  if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
408  ereport(FATAL,
409  (errmsg("database locale is incompatible with operating system"),
410  errdetail("The database was initialized with LC_COLLATE \"%s\", "
411  " which is not recognized by setlocale().", collate),
412  errhint("Recreate the database with another locale or install the missing locale.")));
413 
414  if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
415  ereport(FATAL,
416  (errmsg("database locale is incompatible with operating system"),
417  errdetail("The database was initialized with LC_CTYPE \"%s\", "
418  " which is not recognized by setlocale().", ctype),
419  errhint("Recreate the database with another locale or install the missing locale.")));
420 
421  /* Make the locale settings visible as GUC variables, too */
422  SetConfigOption("lc_collate", collate, PGC_INTERNAL, PGC_S_OVERRIDE);
423  SetConfigOption("lc_ctype", ctype, PGC_INTERNAL, PGC_S_OVERRIDE);
424 
426 
427  ReleaseSysCache(tup);
428 }
int errhint(const char *fmt,...)
Definition: elog.c:1068
#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:610
char * pg_perm_setlocale(int category, const char *locale)
Definition: pg_locale.c:157
#define ERRCODE_INSUFFICIENT_PRIVILEGE
int CountDBConnections(Oid databaseid)
Definition: procarray.c:3453
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
void check_strxfrm_bug(void)
Definition: pg_locale.c:1212
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:7742
bool IsUnderPostmaster
Definition: globals.c:109
int errdetail(const char *fmt,...)
Definition: elog.c:954
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3325
#define ACL_CONNECT
Definition: parsenodes.h:86
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void SetDatabaseEncoding(int encoding)
Definition: mbutils.c:1045
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Oid MyDatabaseId
Definition: globals.c:85
#define ereport(elevel,...)
Definition: elog.h:144
#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:561
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define elog(elevel,...)
Definition: elog.h:214
#define NameStr(name)
Definition: c.h:623

◆ 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:569
#define AccessShareLock
Definition: lockdefs.h:36
bool criticalSharedRelcachesBuilt
Definition: relcache.c:143
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:357
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:476
#define CStringGetDatum(X)
Definition: postgres.h:578
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
char * dbname
Definition: streamutil.c:51
#define DatabaseNameIndexId
Definition: indexing.h:155
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:569
#define AccessShareLock
Definition: lockdefs.h:36
bool criticalSharedRelcachesBuilt
Definition: relcache.c:143
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:357
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:476
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define DatabaseOidIndexId
Definition: indexing.h:157
#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 1241 of file postinit.c.

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

Referenced by InitPostgres().

1242 {
1244  InterruptPending = true;
1245  SetLatch(MyLatch);
1246 }
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:54

◆ InitCommunication()

static void InitCommunication ( void  )
static

Definition at line 440 of file postinit.c.

References CreateSharedMemoryAndSemaphores(), and IsUnderPostmaster.

Referenced by BaseInit().

441 {
442  /*
443  * initialize shared memory and semaphores appropriately.
444  */
445  if (!IsUnderPostmaster) /* postmaster already did this */
446  {
447  /*
448  * We're running a postgres bootstrap process or a standalone backend,
449  * so we need to set up shmem.
450  */
452  }
453 }
bool IsUnderPostmaster
Definition: globals.c:109
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:95

◆ InitializeMaxBackends()

void InitializeMaxBackends ( void  )

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

527 {
528  Assert(MaxBackends == 0);
529 
530  /* the extra unit accounts for the autovacuum launcher */
533 
534  /* internal error because the values were all checked previously */
536  elog(ERROR, "too many backends configured");
537 }
#define ERROR
Definition: elog.h:43
#define MAX_BACKENDS
Definition: postmaster.h:75
int MaxBackends
Definition: globals.c:136
int max_wal_senders
Definition: walsender.c:121
int MaxConnections
Definition: globals.c:133
int autovacuum_max_workers
Definition: autovacuum.c:115
#define Assert(condition)
Definition: c.h:746
#define elog(elevel,...)
Definition: elog.h:214
int max_worker_processes
Definition: globals.c:134

◆ InitPostgres()

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

Definition at line 590 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(), ERRCODE_INSUFFICIENT_PRIVILEGE, errdetail(), errhint(), errmsg(), FATAL, GetDatabasePath(), GetDatabaseTuple(), GetDatabaseTupleByOid(), GetSessionUserId(), GETSTRUCT, GetTransactionSnapshot(), GetUserId(), has_rolreplication(), HaveNFreeProcs(), HeapTupleIsValid, IDLE_IN_TRANSACTION_SESSION_TIMEOUT, IdleInTransactionSessionTimeoutHandler(), 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().

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

◆ LockTimeoutHandler()

static void LockTimeoutHandler ( void  )
static

Definition at line 1231 of file postinit.c.

References kill, and MyProcPid.

Referenced by InitPostgres().

1232 {
1233 #ifdef HAVE_SETSID
1234  /* try to signal whole process group */
1235  kill(-MyProcPid, SIGINT);
1236 #endif
1237  kill(MyProcPid, SIGINT);
1238 }
int MyProcPid
Definition: globals.c:40
#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, Port::application_name, AuthenticationTimeout, be_tls_get_cipher(), be_tls_get_cipher_bits(), be_tls_get_compression(), be_tls_get_version(), ClientAuthentication(), ClientAuthInProgress, Port::database_name, disable_timeout(), enable_timeout_after(), ereport, errmsg(), FATAL, load_hba(), load_ident(), LOG, Log_connections, 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  if (am_walsender)
250  {
251 #ifdef USE_SSL
252  if (port->ssl_in_use)
253  ereport(LOG,
254  (port->application_name != NULL
255  ? errmsg("replication connection authorized: user=%s application_name=%s SSL enabled (protocol=%s, cipher=%s, bits=%d, compression=%s)",
256  port->user_name,
257  port->application_name,
258  be_tls_get_version(port),
259  be_tls_get_cipher(port),
261  be_tls_get_compression(port) ? _("on") : _("off"))
262  : errmsg("replication connection authorized: user=%s SSL enabled (protocol=%s, cipher=%s, bits=%d, compression=%s)",
263  port->user_name,
264  be_tls_get_version(port),
265  be_tls_get_cipher(port),
267  be_tls_get_compression(port) ? _("on") : _("off"))));
268  else
269 #endif
270  ereport(LOG,
271  (port->application_name != NULL
272  ? errmsg("replication connection authorized: user=%s application_name=%s",
273  port->user_name,
274  port->application_name)
275  : errmsg("replication connection authorized: user=%s",
276  port->user_name)));
277  }
278  else
279  {
280 #ifdef USE_SSL
281  if (port->ssl_in_use)
282  ereport(LOG,
283  (port->application_name != NULL
284  ? errmsg("connection authorized: user=%s database=%s application_name=%s SSL enabled (protocol=%s, cipher=%s, bits=%d, compression=%s)",
285  port->user_name, port->database_name, port->application_name,
286  be_tls_get_version(port),
287  be_tls_get_cipher(port),
289  be_tls_get_compression(port) ? _("on") : _("off"))
290  : errmsg("connection authorized: user=%s database=%s SSL enabled (protocol=%s, cipher=%s, bits=%d, compression=%s)",
291  port->user_name, port->database_name,
292  be_tls_get_version(port),
293  be_tls_get_cipher(port),
295  be_tls_get_compression(port) ? _("on") : _("off"))));
296  else
297 #endif
298  ereport(LOG,
299  (port->application_name != NULL
300  ? errmsg("connection authorized: user=%s database=%s application_name=%s",
301  port->user_name, port->database_name, port->application_name)
302  : errmsg("connection authorized: user=%s database=%s",
303  port->user_name, port->database_name)));
304  }
305  }
306 
307  set_ps_display("startup");
308 
309  ClientAuthInProgress = false; /* client_min_messages is active now */
310 }
#define AllocSetContextCreate
Definition: memutils.h:170
void ClientAuthentication(Port *port)
Definition: auth.c:345
bool ssl_in_use
Definition: libpq-be.h:190
#define LOG
Definition: elog.h:26
bool Log_connections
Definition: postmaster.c:245
bool load_ident(void)
Definition: hba.c:2997
int AuthenticationTimeout
Definition: postmaster.c:242
void set_ps_display(const char *activity)
Definition: ps_status.c:349
bool ClientAuthInProgress
Definition: postmaster.c:368
bool am_walsender
Definition: walsender.c:115
bool be_tls_get_compression(Port *port)
#define FATAL
Definition: elog.h:52
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
bool load_hba(void)
Definition: hba.c:2203
char * user_name
Definition: libpq-be.h:141
MemoryContext TopMemoryContext
Definition: mcxt.c:44
int be_tls_get_cipher_bits(Port *port)
#define ereport(elevel,...)
Definition: elog.h:144
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:435
char * application_name
Definition: libpq-be.h:150
const char * be_tls_get_version(Port *port)
int errmsg(const char *fmt,...)
Definition: elog.c:821
const char * be_tls_get_cipher(Port *port)
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:532
char * database_name
Definition: libpq-be.h:140
#define _(x)
Definition: elog.c:88
MemoryContext PostmasterContext
Definition: mcxt.c:46

◆ pg_split_opts()

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

Definition at line 467 of file postinit.c.

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

Referenced by BackendRun(), and process_startup_options().

468 {
469  StringInfoData s;
470 
471  initStringInfo(&s);
472 
473  while (*optstr)
474  {
475  bool last_was_escape = false;
476 
477  resetStringInfo(&s);
478 
479  /* skip over leading space */
480  while (isspace((unsigned char) *optstr))
481  optstr++;
482 
483  if (*optstr == '\0')
484  break;
485 
486  /*
487  * Parse a single option, stopping at the first space, unless it's
488  * escaped.
489  */
490  while (*optstr)
491  {
492  if (isspace((unsigned char) *optstr) && !last_was_escape)
493  break;
494 
495  if (!last_was_escape && *optstr == '\\')
496  last_was_escape = true;
497  else
498  {
499  last_was_escape = false;
500  appendStringInfoChar(&s, *optstr);
501  }
502 
503  optstr++;
504  }
505 
506  /* now store the option in the next argv[] position */
507  argv[(*argcp)++] = pstrdup(s.data);
508  }
509 
510  pfree(s.data);
511 }
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 1158 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().

1159 {
1160  Relation relsetting;
1161  Snapshot snapshot;
1162 
1163  if (!IsUnderPostmaster)
1164  return;
1165 
1166  relsetting = table_open(DbRoleSettingRelationId, AccessShareLock);
1167 
1168  /* read all the settings under the same snapshot for efficiency */
1169  snapshot = RegisterSnapshot(GetCatalogSnapshot(DbRoleSettingRelationId));
1170 
1171  /* Later settings are ignored if set earlier. */
1172  ApplySetting(snapshot, databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
1173  ApplySetting(snapshot, InvalidOid, roleid, relsetting, PGC_S_USER);
1174  ApplySetting(snapshot, databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
1175  ApplySetting(snapshot, InvalidOid, InvalidOid, relsetting, PGC_S_GLOBAL);
1176 
1177  UnregisterSnapshot(snapshot);
1178  table_close(relsetting, AccessShareLock);
1179 }
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:109
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 1093 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().

1094 {
1095  GucContext gucctx;
1096  ListCell *gucopts;
1097 
1098  gucctx = am_superuser ? PGC_SU_BACKEND : PGC_BACKEND;
1099 
1100  /*
1101  * First process any command-line switches that were included in the
1102  * startup packet, if we are in a regular backend.
1103  */
1104  if (port->cmdline_options != NULL)
1105  {
1106  /*
1107  * The maximum possible number of commandline arguments that could
1108  * come from port->cmdline_options is (strlen + 1) / 2; see
1109  * pg_split_opts().
1110  */
1111  char **av;
1112  int maxac;
1113  int ac;
1114 
1115  maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
1116 
1117  av = (char **) palloc(maxac * sizeof(char *));
1118  ac = 0;
1119 
1120  av[ac++] = "postgres";
1121 
1122  pg_split_opts(av, &ac, port->cmdline_options);
1123 
1124  av[ac] = NULL;
1125 
1126  Assert(ac < maxac);
1127 
1128  (void) process_postgres_switches(ac, av, gucctx, NULL);
1129  }
1130 
1131  /*
1132  * Process any additional GUC variable settings passed in startup packet.
1133  * These are handled exactly like command-line variables.
1134  */
1135  gucopts = list_head(port->guc_options);
1136  while (gucopts)
1137  {
1138  char *name;
1139  char *value;
1140 
1141  name = lfirst(gucopts);
1142  gucopts = lnext(port->guc_options, gucopts);
1143 
1144  value = lfirst(gucopts);
1145  gucopts = lnext(port->guc_options, gucopts);
1146 
1147  SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
1148  }
1149 }
GucContext
Definition: guc.h:68
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:310
List * guc_options
Definition: libpq-be.h:143
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:7742
void pg_split_opts(char **argv, int *argcp, const char *optstr)
Definition: postinit.c:467
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
struct @17::@18 av[32]
static struct @143 value
#define Assert(condition)
Definition: c.h:746
#define lfirst(lc)
Definition: pg_list.h:169
const char * name
Definition: encode.c:561
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:3518

◆ ShutdownPostgres()

static void ShutdownPostgres ( int  code,
Datum  arg 
)
static

Definition at line 1192 of file postinit.c.

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

Referenced by InitPostgres().

1193 {
1194  /* Make sure we've killed any active transaction */
1196 
1197  /*
1198  * User locks are not released by transaction end, so be sure to release
1199  * them explicitly.
1200  */
1202 }
void AbortOutOfAnyTransaction(void)
Definition: xact.c:4580
#define USER_LOCKMETHOD
Definition: lock.h:128
void LockReleaseAll(LOCKMETHODID lockmethodid, bool allLocks)
Definition: lock.c:2180

◆ StatementTimeoutHandler()

static void StatementTimeoutHandler ( void  )
static

Definition at line 1209 of file postinit.c.

References ClientAuthInProgress, kill, MyProcPid, and sig.

Referenced by InitPostgres().

1210 {
1211  int sig = SIGINT;
1212 
1213  /*
1214  * During authentication the timeout is used to deal with
1215  * authentication_timeout - we want to quit in response to such timeouts.
1216  */
1218  sig = SIGTERM;
1219 
1220 #ifdef HAVE_SETSID
1221  /* try to signal whole process group */
1222  kill(-MyProcPid, sig);
1223 #endif
1224  kill(MyProcPid, sig);
1225 }
int MyProcPid
Definition: globals.c:40
#define kill(pid, sig)
Definition: win32_port.h:454
bool ClientAuthInProgress
Definition: postmaster.c:368
static int sig
Definition: pg_ctl.c:84

◆ ThereIsAtLeastOneRole()

static bool ThereIsAtLeastOneRole ( void  )
static

Definition at line 1252 of file postinit.c.

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

Referenced by InitPostgres().

1253 {
1254  Relation pg_authid_rel;
1255  TableScanDesc scan;
1256  bool result;
1257 
1258  pg_authid_rel = table_open(AuthIdRelationId, AccessShareLock);
1259 
1260  scan = table_beginscan_catalog(pg_authid_rel, 0, NULL);
1261  result = (heap_getnext(scan, ForwardScanDirection) != NULL);
1262 
1263  table_endscan(scan);
1264  table_close(pg_authid_rel, AccessShareLock);
1265 
1266  return result;
1267 }
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:1286
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:863
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39