PostgreSQL Source Code  git master
postinit.c File Reference
#include "postgres.h"
#include <ctype.h>
#include <fcntl.h>
#include <unistd.h>
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/session.h"
#include "access/sysattr.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/procarray.h"
#include "storage/procsignal.h"
#include "storage/proc.h"
#include "storage/sinvaladt.h"
#include "storage/smgr.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 "utils/tqual.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)
 
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)
 

Function Documentation

◆ BaseInit()

void BaseInit ( void  )

Definition at line 518 of file postinit.c.

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

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

519 {
520  /*
521  * Attach to shared memory and semaphores, and initialize our
522  * input/output/debugging file descriptors.
523  */
525  DebugFileOpen();
526 
527  /* Do local initialization of file, storage and buffer managers */
528  InitFileAccess();
529  smgrinit();
531 }
static void InitCommunication(void)
Definition: postinit.c:410
void InitBufferPoolAccess(void)
Definition: bufmgr.c:2437
void DebugFileOpen(void)
Definition: elog.c:1863
void smgrinit(void)
Definition: smgr.c:102
void InitFileAccess(void)
Definition: fd.c:778

◆ CheckMyDatabase()

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

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

288 {
289  HeapTuple tup;
290  Form_pg_database dbform;
291  char *collate;
292  char *ctype;
293 
294  /* Fetch our pg_database row normally, via syscache */
296  if (!HeapTupleIsValid(tup))
297  elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
298  dbform = (Form_pg_database) GETSTRUCT(tup);
299 
300  /* This recheck is strictly paranoia */
301  if (strcmp(name, NameStr(dbform->datname)) != 0)
302  ereport(FATAL,
303  (errcode(ERRCODE_UNDEFINED_DATABASE),
304  errmsg("database \"%s\" has disappeared from pg_database",
305  name),
306  errdetail("Database OID %u now seems to belong to \"%s\".",
307  MyDatabaseId, NameStr(dbform->datname))));
308 
309  /*
310  * Check permissions to connect to the database.
311  *
312  * These checks are not enforced when in standalone mode, so that there is
313  * a way to recover from disabling all access to all databases, for
314  * example "UPDATE pg_database SET datallowconn = false;".
315  *
316  * We do not enforce them for autovacuum worker processes either.
317  */
319  {
320  /*
321  * Check that the database is currently allowing connections.
322  */
323  if (!dbform->datallowconn)
324  ereport(FATAL,
325  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
326  errmsg("database \"%s\" is not currently accepting connections",
327  name)));
328 
329  /*
330  * Check privilege to connect to the database. (The am_superuser test
331  * is redundant, but since we have the flag, might as well check it
332  * and save a few cycles.)
333  */
334  if (!am_superuser &&
337  ereport(FATAL,
338  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
339  errmsg("permission denied for database \"%s\"", name),
340  errdetail("User does not have CONNECT privilege.")));
341 
342  /*
343  * Check connection limit for this database.
344  *
345  * There is a race condition here --- we create our PGPROC before
346  * checking for other PGPROCs. If two backends did this at about the
347  * same time, they might both think they were over the limit, while
348  * ideally one should succeed and one fail. Getting that to work
349  * exactly seems more trouble than it is worth, however; instead we
350  * just document that the connection limit is approximate.
351  */
352  if (dbform->datconnlimit >= 0 &&
353  !am_superuser &&
354  CountDBConnections(MyDatabaseId) > dbform->datconnlimit)
355  ereport(FATAL,
356  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
357  errmsg("too many connections for database \"%s\"",
358  name)));
359  }
360 
361  /*
362  * OK, we're golden. Next to-do item is to save the encoding info out of
363  * the pg_database tuple.
364  */
365  SetDatabaseEncoding(dbform->encoding);
366  /* Record it as a GUC internal option, too */
367  SetConfigOption("server_encoding", GetDatabaseEncodingName(),
369  /* If we have no other source of client_encoding, use server encoding */
370  SetConfigOption("client_encoding", GetDatabaseEncodingName(),
372 
373  /* assign locale variables */
374  collate = NameStr(dbform->datcollate);
375  ctype = NameStr(dbform->datctype);
376 
377  if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
378  ereport(FATAL,
379  (errmsg("database locale is incompatible with operating system"),
380  errdetail("The database was initialized with LC_COLLATE \"%s\", "
381  " which is not recognized by setlocale().", collate),
382  errhint("Recreate the database with another locale or install the missing locale.")));
383 
384  if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
385  ereport(FATAL,
386  (errmsg("database locale is incompatible with operating system"),
387  errdetail("The database was initialized with LC_CTYPE \"%s\", "
388  " which is not recognized by setlocale().", ctype),
389  errhint("Recreate the database with another locale or install the missing locale.")));
390 
391  /* Make the locale settings visible as GUC variables, too */
392  SetConfigOption("lc_collate", collate, PGC_INTERNAL, PGC_S_OVERRIDE);
393  SetConfigOption("lc_ctype", ctype, PGC_INTERNAL, PGC_S_OVERRIDE);
394 
396 
397  ReleaseSysCache(tup);
398 }
int errhint(const char *fmt,...)
Definition: elog.c:987
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
Oid GetUserId(void)
Definition: miscinit.c:284
FormData_pg_database * Form_pg_database
Definition: pg_database.h:57
int errcode(int sqlerrcode)
Definition: elog.c:575
char * pg_perm_setlocale(int category, const char *locale)
Definition: pg_locale.c:151
int CountDBConnections(Oid databaseid)
Definition: procarray.c:2769
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
void check_strxfrm_bug(void)
Definition: pg_locale.c:993
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6700
bool IsUnderPostmaster
Definition: globals.c:101
int errdetail(const char *fmt,...)
Definition: elog.c:873
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3256
#define ereport(elevel, rest)
Definition: elog.h:122
#define ACL_CONNECT
Definition: parsenodes.h:84
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void SetDatabaseEncoding(int encoding)
Definition: mbutils.c:898
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
Oid MyDatabaseId
Definition: globals.c:77
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
AclResult pg_database_aclcheck(Oid db_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4492
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1010
const char * name
Definition: encode.c:521
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:557
#define elog
Definition: elog.h:219

◆ GetDatabaseTuple()

static HeapTuple GetDatabaseTuple ( const char *  dbname)
static

Definition at line 95 of file postinit.c.

References AccessShareLock, Anum_pg_database_datname, BTEqualStrategyNumber, criticalSharedRelcachesBuilt, CStringGetDatum, DatabaseNameIndexId, DatabaseRelationId, heap_close, heap_copytuple(), heap_open(), HeapTupleIsValid, ScanKeyInit(), systable_beginscan(), systable_endscan(), and systable_getnext().

Referenced by InitPostgres().

96 {
97  HeapTuple tuple;
98  Relation relation;
99  SysScanDesc scan;
100  ScanKeyData key[1];
101 
102  /*
103  * form a scan key
104  */
105  ScanKeyInit(&key[0],
107  BTEqualStrategyNumber, F_NAMEEQ,
109 
110  /*
111  * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
112  * built the critical shared relcache entries (i.e., we're starting up
113  * without a shared relcache cache file).
114  */
116  scan = systable_beginscan(relation, DatabaseNameIndexId,
118  NULL,
119  1, key);
120 
121  tuple = systable_getnext(scan);
122 
123  /* Must copy tuple before releasing buffer */
124  if (HeapTupleIsValid(tuple))
125  tuple = heap_copytuple(tuple);
126 
127  /* all done */
128  systable_endscan(scan);
129  heap_close(relation, AccessShareLock);
130 
131  return tuple;
132 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:611
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:499
#define DatabaseRelationId
Definition: pg_database.h:29
#define AccessShareLock
Definition: lockdefs.h:36
bool criticalSharedRelcachesBuilt
Definition: relcache.c:131
#define heap_close(r, l)
Definition: heapam.h:97
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:328
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:416
#define Anum_pg_database_datname
Definition: pg_database.h:64
#define CStringGetDatum(X)
Definition: postgres.h:584
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
char * dbname
Definition: streamutil.c:42
#define DatabaseNameIndexId
Definition: indexing.h:140
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ GetDatabaseTupleByOid()

static HeapTuple GetDatabaseTupleByOid ( Oid  dboid)
static

Definition at line 138 of file postinit.c.

References AccessShareLock, BTEqualStrategyNumber, criticalSharedRelcachesBuilt, DatabaseOidIndexId, DatabaseRelationId, heap_close, heap_copytuple(), heap_open(), HeapTupleIsValid, ObjectIdAttributeNumber, ObjectIdGetDatum, ScanKeyInit(), systable_beginscan(), systable_endscan(), and systable_getnext().

Referenced by InitPostgres().

139 {
140  HeapTuple tuple;
141  Relation relation;
142  SysScanDesc scan;
143  ScanKeyData key[1];
144 
145  /*
146  * form a scan key
147  */
148  ScanKeyInit(&key[0],
150  BTEqualStrategyNumber, F_OIDEQ,
151  ObjectIdGetDatum(dboid));
152 
153  /*
154  * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
155  * built the critical shared relcache entries (i.e., we're starting up
156  * without a shared relcache cache file).
157  */
159  scan = systable_beginscan(relation, DatabaseOidIndexId,
161  NULL,
162  1, key);
163 
164  tuple = systable_getnext(scan);
165 
166  /* Must copy tuple before releasing buffer */
167  if (HeapTupleIsValid(tuple))
168  tuple = heap_copytuple(tuple);
169 
170  /* all done */
171  systable_endscan(scan);
172  heap_close(relation, AccessShareLock);
173 
174  return tuple;
175 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:611
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:499
#define ObjectIdAttributeNumber
Definition: sysattr.h:22
#define DatabaseRelationId
Definition: pg_database.h:29
#define AccessShareLock
Definition: lockdefs.h:36
bool criticalSharedRelcachesBuilt
Definition: relcache.c:131
#define heap_close(r, l)
Definition: heapam.h:97
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:328
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:416
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define DatabaseOidIndexId
Definition: indexing.h:142
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ IdleInTransactionSessionTimeoutHandler()

static void IdleInTransactionSessionTimeoutHandler ( void  )
static

Definition at line 1196 of file postinit.c.

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

Referenced by InitPostgres().

1197 {
1199  InterruptPending = true;
1200  SetLatch(MyLatch);
1201 }
volatile bool IdleInTransactionSessionTimeoutPending
Definition: globals.c:33
volatile bool InterruptPending
Definition: globals.c:29
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
struct Latch * MyLatch
Definition: globals.c:52

◆ InitCommunication()

static void InitCommunication ( void  )
static

Definition at line 410 of file postinit.c.

References CreateSharedMemoryAndSemaphores(), and IsUnderPostmaster.

Referenced by BaseInit().

411 {
412  /*
413  * initialize shared memory and semaphores appropriately.
414  */
415  if (!IsUnderPostmaster) /* postmaster already did this */
416  {
417  /*
418  * We're running a postgres bootstrap process or a standalone backend.
419  * Create private "shmem" and semaphores.
420  */
422  }
423 }
bool IsUnderPostmaster
Definition: globals.c:101
void CreateSharedMemoryAndSemaphores(bool makePrivate, int port)
Definition: ipci.c:96

◆ InitializeMaxBackends()

void InitializeMaxBackends ( void  )

Definition at line 496 of file postinit.c.

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

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

497 {
498  Assert(MaxBackends == 0);
499 
500  /* the extra unit accounts for the autovacuum launcher */
503 
504  /* internal error because the values were all checked previously */
506  elog(ERROR, "too many backends configured");
507 }
#define ERROR
Definition: elog.h:43
#define MAX_BACKENDS
Definition: postmaster.h:75
int MaxBackends
Definition: globals.c:126
int MaxConnections
Definition: globals.c:123
int autovacuum_max_workers
Definition: autovacuum.c:115
#define Assert(condition)
Definition: c.h:680
int max_worker_processes
Definition: globals.c:124
#define elog
Definition: elog.h:219

◆ InitPostgres()

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

Definition at line 559 of file postinit.c.

References am_db_walsender, am_walsender, Assert, before_shmem_exit(), CAC_WAITBACKUP, Port::canAcceptConnections, CheckDeadLockAlert(), CheckMyDatabase(), CommitTransactionCommand(), PGPROC::databaseId, DatabaseRelationId, dbname, DEADLOCK_TIMEOUT, DEBUG3, DEFAULTTABLESPACE_OID, elog, EnablePortalManager(), ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg(), FATAL, GetDatabasePath(), GetDatabaseTuple(), GetDatabaseTupleByOid(), GetSessionUserId(), GETSTRUCT, GetTransactionSnapshot(), GetUserId(), has_rolreplication(), HaveNFreeProcs(), HeapTupleGetOid, 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(), ReservedBackends, RowExclusiveLock, SetCurrentStatementStartTimestamp(), SetDatabasePath(), SharedInvalBackendInit(), ShutdownPostgres(), ShutdownXLOG(), StartTransactionCommand(), StartupXLOG(), STATEMENT_TIMEOUT, StatementTimeoutHandler(), strlcpy(), superuser(), TemplateDbOid, ThereIsAtLeastOneRole(), ValidatePgVersion(), WARNING, XACT_READ_COMMITTED, and XactIsoLevel.

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

561 {
562  bool bootstrap = IsBootstrapProcessingMode();
563  bool am_superuser;
564  char *fullpath;
565  char dbname[NAMEDATALEN];
566 
567  elog(DEBUG3, "InitPostgres");
568 
569  /*
570  * Add my PGPROC struct to the ProcArray.
571  *
572  * Once I have done this, I am visible to other backends!
573  */
575 
576  /*
577  * Initialize my entry in the shared-invalidation manager's array of
578  * per-backend data.
579  *
580  * Sets up MyBackendId, a unique backend identifier.
581  */
583 
584  SharedInvalBackendInit(false);
585 
586  if (MyBackendId > MaxBackends || MyBackendId <= 0)
587  elog(FATAL, "bad backend ID: %d", MyBackendId);
588 
589  /* Now that we have a BackendId, we can participate in ProcSignal */
591 
592  /*
593  * Also set up timeout handlers needed for backend operation. We need
594  * these in every case except bootstrap.
595  */
596  if (!bootstrap)
597  {
603  }
604 
605  /*
606  * bufmgr needs another initialization call too
607  */
609 
610  /*
611  * Initialize local process's access to XLOG.
612  */
613  if (IsUnderPostmaster)
614  {
615  /*
616  * The postmaster already started the XLOG machinery, but we need to
617  * call InitXLOGAccess(), if the system isn't in hot-standby mode.
618  * This is handled by calling RecoveryInProgress and ignoring the
619  * result.
620  */
621  (void) RecoveryInProgress();
622  }
623  else
624  {
625  /*
626  * We are either a bootstrap process or a standalone backend. Either
627  * way, start up the XLOG machinery, and register to have it closed
628  * down at exit.
629  */
630  StartupXLOG();
632  }
633 
634  /*
635  * Initialize the relation cache and the system catalog caches. Note that
636  * no catalog access happens here; we only set up the hashtable structure.
637  * We must do this before starting a transaction because transaction abort
638  * would try to touch these hashtables.
639  */
642  InitPlanCache();
643 
644  /* Initialize portal manager */
646 
647  /* Initialize stats collection --- must happen before first xact */
648  if (!bootstrap)
650 
651  /*
652  * Load relcache entries for the shared system catalogs. This must create
653  * at least entries for pg_database and catalogs used for authentication.
654  */
656 
657  /*
658  * Set up process-exit callback to do pre-shutdown cleanup. This is the
659  * first before_shmem_exit callback we register; thus, this will be the
660  * last thing we do before low-level modules like the buffer manager begin
661  * to close down. We need to have this in place before we begin our first
662  * transaction --- if we fail during the initialization transaction, as is
663  * entirely possible, we need the AbortTransaction call to clean up.
664  */
666 
667  /* The autovacuum launcher is done here */
669  {
670  /* report this backend in the PgBackendStatus array */
671  pgstat_bestart();
672 
673  return;
674  }
675 
676  /*
677  * Start a new transaction here before first access to db, and get a
678  * snapshot. We don't have a use for the snapshot itself, but we're
679  * interested in the secondary effect that it sets RecentGlobalXmin. (This
680  * is critical for anything that reads heap pages, because HOT may decide
681  * to prune them even if the process doesn't attempt to modify any
682  * tuples.)
683  */
684  if (!bootstrap)
685  {
686  /* statement_timestamp must be set for timeouts to work correctly */
689 
690  /*
691  * transaction_isolation will have been set to the default by the
692  * above. If the default is "serializable", and we are in hot
693  * standby, we will fail if we don't change it to something lower.
694  * Fortunately, "read committed" is plenty good enough.
695  */
697 
698  (void) GetTransactionSnapshot();
699  }
700 
701  /*
702  * Perform client authentication if necessary, then figure out our
703  * postgres user ID, and see if we are a superuser.
704  *
705  * In standalone mode and in autovacuum worker processes, we use a fixed
706  * ID, otherwise we figure it out from the authenticated user name.
707  */
708  if (bootstrap || IsAutoVacuumWorkerProcess())
709  {
711  am_superuser = true;
712  }
713  else if (!IsUnderPostmaster)
714  {
716  am_superuser = true;
717  if (!ThereIsAtLeastOneRole())
719  (errcode(ERRCODE_UNDEFINED_OBJECT),
720  errmsg("no roles are defined in this database system"),
721  errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
722  username != NULL ? username : "postgres")));
723  }
724  else if (IsBackgroundWorker)
725  {
726  if (username == NULL && !OidIsValid(useroid))
727  {
729  am_superuser = true;
730  }
731  else
732  {
734  am_superuser = superuser();
735  }
736  }
737  else
738  {
739  /* normal multiuser case */
740  Assert(MyProcPort != NULL);
743  am_superuser = superuser();
744  }
745 
746  /*
747  * If we're trying to shut down, only superusers can connect, and new
748  * replication connections are not allowed.
749  */
750  if ((!am_superuser || am_walsender) &&
751  MyProcPort != NULL &&
753  {
754  if (am_walsender)
755  ereport(FATAL,
756  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
757  errmsg("new replication connections are not allowed during database shutdown")));
758  else
759  ereport(FATAL,
760  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
761  errmsg("must be superuser to connect during database shutdown")));
762  }
763 
764  /*
765  * Binary upgrades only allowed super-user connections
766  */
767  if (IsBinaryUpgrade && !am_superuser)
768  {
769  ereport(FATAL,
770  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
771  errmsg("must be superuser to connect in binary upgrade mode")));
772  }
773 
774  /*
775  * The last few connections slots are reserved for superusers. Although
776  * replication connections currently require superuser privileges, we
777  * don't allow them to consume the reserved slots, which are intended for
778  * interactive use.
779  */
780  if ((!am_superuser || am_walsender) &&
781  ReservedBackends > 0 &&
783  ereport(FATAL,
784  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
785  errmsg("remaining connection slots are reserved for non-replication superuser connections")));
786 
787  /* Check replication permissions needed for walsender processes. */
788  if (am_walsender)
789  {
790  Assert(!bootstrap);
791 
792  if (!superuser() && !has_rolreplication(GetUserId()))
793  ereport(FATAL,
794  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
795  errmsg("must be superuser or replication role to start walsender")));
796  }
797 
798  /*
799  * If this is a plain walsender only supporting physical replication, we
800  * don't want to connect to any particular database. Just finish the
801  * backend startup by processing any options from the startup packet, and
802  * we're done.
803  */
805  {
806  /* process any options passed in the startup packet */
807  if (MyProcPort != NULL)
808  process_startup_options(MyProcPort, am_superuser);
809 
810  /* Apply PostAuthDelay as soon as we've read all options */
811  if (PostAuthDelay > 0)
812  pg_usleep(PostAuthDelay * 1000000L);
813 
814  /* initialize client encoding */
816 
817  /* report this backend in the PgBackendStatus array */
818  pgstat_bestart();
819 
820  /* close the transaction we started above */
822 
823  return;
824  }
825 
826  /*
827  * Set up the global variables holding database id and default tablespace.
828  * But note we won't actually try to touch the database just yet.
829  *
830  * We take a shortcut in the bootstrap case, otherwise we have to look up
831  * the db's entry in pg_database.
832  */
833  if (bootstrap)
834  {
837  }
838  else if (in_dbname != NULL)
839  {
840  HeapTuple tuple;
841  Form_pg_database dbform;
842 
843  tuple = GetDatabaseTuple(in_dbname);
844  if (!HeapTupleIsValid(tuple))
845  ereport(FATAL,
846  (errcode(ERRCODE_UNDEFINED_DATABASE),
847  errmsg("database \"%s\" does not exist", in_dbname)));
848  dbform = (Form_pg_database) GETSTRUCT(tuple);
849  MyDatabaseId = HeapTupleGetOid(tuple);
850  MyDatabaseTableSpace = dbform->dattablespace;
851  /* take database name from the caller, just for paranoia */
852  strlcpy(dbname, in_dbname, sizeof(dbname));
853  }
854  else if (OidIsValid(dboid))
855  {
856  /* caller specified database by OID */
857  HeapTuple tuple;
858  Form_pg_database dbform;
859 
860  tuple = GetDatabaseTupleByOid(dboid);
861  if (!HeapTupleIsValid(tuple))
862  ereport(FATAL,
863  (errcode(ERRCODE_UNDEFINED_DATABASE),
864  errmsg("database %u does not exist", dboid)));
865  dbform = (Form_pg_database) GETSTRUCT(tuple);
866  MyDatabaseId = HeapTupleGetOid(tuple);
867  MyDatabaseTableSpace = dbform->dattablespace;
868  Assert(MyDatabaseId == dboid);
869  strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
870  /* pass the database name back to the caller */
871  if (out_dbname)
872  strcpy(out_dbname, dbname);
873  }
874  else
875  {
876  /*
877  * If this is a background worker not bound to any particular
878  * database, we're done now. Everything that follows only makes sense
879  * if we are bound to a specific database. We do need to close the
880  * transaction we started before returning.
881  */
882  if (!bootstrap)
883  {
884  pgstat_bestart();
886  }
887  return;
888  }
889 
890  /*
891  * Now, take a writer's lock on the database we are trying to connect to.
892  * If there is a concurrently running DROP DATABASE on that database, this
893  * will block us until it finishes (and has committed its update of
894  * pg_database).
895  *
896  * Note that the lock is not held long, only until the end of this startup
897  * transaction. This is OK since we will advertise our use of the
898  * database in the ProcArray before dropping the lock (in fact, that's the
899  * next thing to do). Anyone trying a DROP DATABASE after this point will
900  * see us in the array once they have the lock. Ordering is important for
901  * this because we don't want to advertise ourselves as being in this
902  * database until we have the lock; otherwise we create what amounts to a
903  * deadlock with CountOtherDBBackends().
904  *
905  * Note: use of RowExclusiveLock here is reasonable because we envision
906  * our session as being a concurrent writer of the database. If we had a
907  * way of declaring a session as being guaranteed-read-only, we could use
908  * AccessShareLock for such sessions and thereby not conflict against
909  * CREATE DATABASE.
910  */
911  if (!bootstrap)
914 
915  /*
916  * Now we can mark our PGPROC entry with the database ID.
917  *
918  * We assume this is an atomic store so no lock is needed; though actually
919  * things would work fine even if it weren't atomic. Anyone searching the
920  * ProcArray for this database's ID should hold the database lock, so they
921  * would not be executing concurrently with this store. A process looking
922  * for another database's ID could in theory see a chance match if it read
923  * a partially-updated databaseId value; but as long as all such searches
924  * wait and retry, as in CountOtherDBBackends(), they will certainly see
925  * the correct value on their next try.
926  */
928 
929  /*
930  * We established a catalog snapshot while reading pg_authid and/or
931  * pg_database; but until we have set up MyDatabaseId, we won't react to
932  * incoming sinval messages for unshared catalogs, so we won't realize it
933  * if the snapshot has been invalidated. Assume it's no good anymore.
934  */
936 
937  /*
938  * Recheck pg_database to make sure the target database hasn't gone away.
939  * If there was a concurrent DROP DATABASE, this ensures we will die
940  * cleanly without creating a mess.
941  */
942  if (!bootstrap)
943  {
944  HeapTuple tuple;
945 
946  tuple = GetDatabaseTuple(dbname);
947  if (!HeapTupleIsValid(tuple) ||
948  MyDatabaseId != HeapTupleGetOid(tuple) ||
949  MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
950  ereport(FATAL,
951  (errcode(ERRCODE_UNDEFINED_DATABASE),
952  errmsg("database \"%s\" does not exist", dbname),
953  errdetail("It seems to have just been dropped or renamed.")));
954  }
955 
956  /*
957  * Now we should be able to access the database directory safely. Verify
958  * it's there and looks reasonable.
959  */
961 
962  if (!bootstrap)
963  {
964  if (access(fullpath, F_OK) == -1)
965  {
966  if (errno == ENOENT)
967  ereport(FATAL,
968  (errcode(ERRCODE_UNDEFINED_DATABASE),
969  errmsg("database \"%s\" does not exist",
970  dbname),
971  errdetail("The database subdirectory \"%s\" is missing.",
972  fullpath)));
973  else
974  ereport(FATAL,
976  errmsg("could not access directory \"%s\": %m",
977  fullpath)));
978  }
979 
980  ValidatePgVersion(fullpath);
981  }
982 
983  SetDatabasePath(fullpath);
984 
985  /*
986  * It's now possible to do real access to the system catalogs.
987  *
988  * Load relcache entries for the system catalogs. This must create at
989  * least the minimum set of "nailed-in" cache entries.
990  */
992 
993  /* set up ACL framework (so CheckMyDatabase can check permissions) */
994  initialize_acl();
995 
996  /*
997  * Re-read the pg_database row for our database, check permissions and set
998  * up database-specific GUC settings. We can't do this until all the
999  * database-access infrastructure is up. (Also, it wants to know if the
1000  * user is a superuser, so the above stuff has to happen first.)
1001  */
1002  if (!bootstrap)
1003  CheckMyDatabase(dbname, am_superuser);
1004 
1005  /*
1006  * Now process any command-line switches and any additional GUC variable
1007  * settings passed in the startup packet. We couldn't do this before
1008  * because we didn't know if client is a superuser.
1009  */
1010  if (MyProcPort != NULL)
1011  process_startup_options(MyProcPort, am_superuser);
1012 
1013  /* Process pg_db_role_setting options */
1015 
1016  /* Apply PostAuthDelay as soon as we've read all options */
1017  if (PostAuthDelay > 0)
1018  pg_usleep(PostAuthDelay * 1000000L);
1019 
1020  /*
1021  * Initialize various default states that can't be set up until we've
1022  * selected the active user and gotten the right GUC settings.
1023  */
1024 
1025  /* set default namespace search path */
1027 
1028  /* initialize client encoding */
1030 
1031  /* Initialize this backend's session state. */
1033 
1034  /* report this backend in the PgBackendStatus array */
1035  if (!bootstrap)
1036  pgstat_bestart();
1037 
1038  /* close the transaction we started above */
1039  if (!bootstrap)
1041 }
int errhint(const char *fmt,...)
Definition: elog.c:987
BackendId MyBackendId
Definition: globals.c:73
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
struct Port * MyProcPort
Definition: globals.c:41
CAC_state canAcceptConnections
Definition: libpq-be.h:129
void SharedInvalBackendInit(bool sendOnly)
Definition: sinvaladt.c:258
#define DEBUG3
Definition: elog.h:23
Oid GetUserId(void)
Definition: miscinit.c:284
FormData_pg_database * Form_pg_database
Definition: pg_database.h:57
PGPROC * MyProc
Definition: proc.c:67
static HeapTuple GetDatabaseTuple(const char *dbname)
Definition: postinit.c:95
#define DatabaseRelationId
Definition: pg_database.h:29
void CommitTransactionCommand(void)
Definition: xact.c:2745
void InitializeSession(void)
Definition: session.c:54
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1358
void RelationCacheInitializePhase2(void)
Definition: relcache.c:3582
static void PerformAuthentication(Port *port)
Definition: postinit.c:184
static void LockTimeoutHandler(void)
Definition: postinit.c:1186
int errcode(int sqlerrcode)
Definition: elog.c:575
bool superuser(void)
Definition: superuser.c:47
static void CheckMyDatabase(const char *name, bool am_superuser)
Definition: postinit.c:287
void initialize_acl(void)
Definition: acl.c:4614
bool RecoveryInProgress(void)
Definition: xlog.c:7922
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:304
#define OidIsValid(objectId)
Definition: c.h:586
Oid GetSessionUserId(void)
Definition: miscinit.c:318
bool HaveNFreeProcs(int n)
Definition: proc.c:646
bool IsBinaryUpgrade
Definition: globals.c:102
Oid MyDatabaseTableSpace
Definition: globals.c:79
bool IsBackgroundWorker
Definition: globals.c:103
void RelationCacheInitializePhase3(void)
Definition: relcache.c:3641
#define NAMEDATALEN
bool am_walsender
Definition: walsender.c:114
void pg_usleep(long microsec)
Definition: signal.c:53
int ReservedBackends
Definition: postmaster.c:212
#define FATAL
Definition: elog.h:52
void InitializeSearchPath(void)
Definition: namespace.c:4110
int MaxBackends
Definition: globals.c:126
#define TemplateDbOid
Definition: pg_database.h:80
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:348
bool IsUnderPostmaster
Definition: globals.c:101
#define RowExclusiveLock
Definition: lockdefs.h:38
#define DEFAULTTABLESPACE_OID
Definition: pg_tablespace.h:63
int errdetail(const char *fmt,...)
Definition: elog.c:873
int errcode_for_file_access(void)
Definition: elog.c:598
static void IdleInTransactionSessionTimeoutHandler(void)
Definition: postinit.c:1196
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:320
Oid databaseId
Definition: proc.h:114
void pgstat_initialize(void)
Definition: pgstat.c:2745
static bool ThereIsAtLeastOneRole(void)
Definition: postinit.c:1207
void StartupXLOG(void)
Definition: xlog.c:6257
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3256
#define ereport(elevel, rest)
Definition: elog.h:122
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:510
char * GetDatabasePath(Oid dbNode, Oid spcNode)
Definition: relpath.c:108
void SetDatabasePath(const char *path)
Definition: miscinit.c:83
#define WARNING
Definition: elog.h:40
void ShutdownXLOG(int code, Datum arg)
Definition: xlog.c:8353
static HeapTuple GetDatabaseTupleByOid(Oid dboid)
Definition: postinit.c:138
#define InvalidBackendId
Definition: backendid.h:23
bool am_db_walsender
Definition: walsender.c:117
Oid MyDatabaseId
Definition: globals.c:77
int PostAuthDelay
Definition: postgres.c:99
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:871
void EnablePortalManager(void)
Definition: portalmem.c:103
static void ShutdownPostgres(int code, Datum arg)
Definition: postinit.c:1147
static char * username
Definition: initdb.c:132
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:373
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:3250
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Assert(condition)
Definition: c.h:680
void InitializeSessionUserIdStandalone(void)
Definition: miscinit.c:579
void StartTransactionCommand(void)
Definition: xact.c:2674
#define XACT_READ_COMMITTED
Definition: xact.h:29
void InitializeSessionUserId(const char *rolename, Oid roleid)
Definition: miscinit.c:483
char * dbname
Definition: streamutil.c:42
static void process_startup_options(Port *port, bool am_superuser)
Definition: postinit.c:1048
int XactIsoLevel
Definition: xact.c:74
bool has_rolreplication(Oid roleid)
Definition: miscinit.c:465
void InitializeClientEncoding(void)
Definition: mbutils.c:282
void InitPlanCache(void)
Definition: plancache.c:116
void InitProcessPhase2(void)
Definition: proc.c:456
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:367
void RelationCacheInitialize(void)
Definition: relcache.c:3545
void ProcSignalInit(int pss_idx)
Definition: procsignal.c:105
void InitCatalogCache(void)
Definition: syscache.c:998
static void StatementTimeoutHandler(void)
Definition: postinit.c:1164
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:733
int errmsg(const char *fmt,...)
Definition: elog.c:797
void pgstat_bestart(void)
Definition: pgstat.c:2785
#define NameStr(name)
Definition: c.h:557
static void process_settings(Oid databaseid, Oid roleid)
Definition: postinit.c:1113
void CheckDeadLockAlert(void)
Definition: proc.c:1752
void InitBufferPoolBackend(void)
Definition: bufmgr.c:2461
#define elog
Definition: elog.h:219
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:700

◆ LockTimeoutHandler()

static void LockTimeoutHandler ( void  )
static

Definition at line 1186 of file postinit.c.

References kill, and MyProcPid.

Referenced by InitPostgres().

1187 {
1188 #ifdef HAVE_SETSID
1189  /* try to signal whole process group */
1190  kill(-MyProcPid, SIGINT);
1191 #endif
1192  kill(MyProcPid, SIGINT);
1193 }
int MyProcPid
Definition: globals.c:39
#define kill(pid, sig)
Definition: win32_port.h:437

◆ PerformAuthentication()

static void PerformAuthentication ( Port port)
static

Definition at line 184 of file postinit.c.

References _, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, am_walsender, AuthenticationTimeout, ClientAuthentication(), ClientAuthInProgress, Port::database_name, disable_timeout(), enable_timeout_after(), ereport, errmsg(), FATAL, load_hba(), load_ident(), LOG, Log_connections, PostmasterContext, set_ps_display(), SSL_get_current_compression, Port::ssl_in_use, STATEMENT_TIMEOUT, TopMemoryContext, and Port::user_name.

Referenced by InitPostgres().

185 {
186  /* This should be set already, but let's make sure */
187  ClientAuthInProgress = true; /* limit visibility of log messages */
188 
189  /*
190  * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
191  * etcetera from the postmaster, and have to load them ourselves.
192  *
193  * FIXME: [fork/exec] Ugh. Is there a way around this overhead?
194  */
195 #ifdef EXEC_BACKEND
196 
197  /*
198  * load_hba() and load_ident() want to work within the PostmasterContext,
199  * so create that if it doesn't exist (which it won't). We'll delete it
200  * again later, in PostgresMain.
201  */
202  if (PostmasterContext == NULL)
204  "Postmaster",
206 
207  if (!load_hba())
208  {
209  /*
210  * It makes no sense to continue if we fail to load the HBA file,
211  * since there is no way to connect to the database in this case.
212  */
213  ereport(FATAL,
214  (errmsg("could not load pg_hba.conf")));
215  }
216 
217  if (!load_ident())
218  {
219  /*
220  * It is ok to continue if we fail to load the IDENT file, although it
221  * means that you cannot log in using any of the authentication
222  * methods that need a user name mapping. load_ident() already logged
223  * the details of error to the log.
224  */
225  }
226 #endif
227 
228  /*
229  * Set up a timeout in case a buggy or malicious client fails to respond
230  * during authentication. Since we're inside a transaction and might do
231  * database access, we have to use the statement_timeout infrastructure.
232  */
234 
235  /*
236  * Now perform authentication exchange.
237  */
238  ClientAuthentication(port); /* might not return, if failure */
239 
240  /*
241  * Done with authentication. Disable the timeout, and log if needed.
242  */
244 
245  if (Log_connections)
246  {
247  if (am_walsender)
248  {
249 #ifdef USE_OPENSSL
250  if (port->ssl_in_use)
251  ereport(LOG,
252  (errmsg("replication connection authorized: user=%s SSL enabled (protocol=%s, cipher=%s, compression=%s)",
253  port->user_name, SSL_get_version(port->ssl), SSL_get_cipher(port->ssl),
254  SSL_get_current_compression(port->ssl) ? _("on") : _("off"))));
255  else
256 #endif
257  ereport(LOG,
258  (errmsg("replication connection authorized: user=%s",
259  port->user_name)));
260  }
261  else
262  {
263 #ifdef USE_OPENSSL
264  if (port->ssl_in_use)
265  ereport(LOG,
266  (errmsg("connection authorized: user=%s database=%s SSL enabled (protocol=%s, cipher=%s, compression=%s)",
267  port->user_name, port->database_name, SSL_get_version(port->ssl), SSL_get_cipher(port->ssl),
268  SSL_get_current_compression(port->ssl) ? _("on") : _("off"))));
269  else
270 #endif
271  ereport(LOG,
272  (errmsg("connection authorized: user=%s database=%s",
273  port->user_name, port->database_name)));
274  }
275  }
276 
277  set_ps_display("startup", false);
278 
279  ClientAuthInProgress = false; /* client_min_messages is active now */
280 }
void ClientAuthentication(Port *port)
Definition: auth.c:346
void set_ps_display(const char *activity, bool force)
Definition: ps_status.c:326
bool ssl_in_use
Definition: libpq-be.h:181
#define LOG
Definition: elog.h:26
bool Log_connections
Definition: postmaster.c:240
bool load_ident(void)
Definition: hba.c:2899
int AuthenticationTimeout
Definition: postmaster.c:237
bool ClientAuthInProgress
Definition: postmaster.c:350
bool am_walsender
Definition: walsender.c:114
#define FATAL
Definition: elog.h:52
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:197
bool load_hba(void)
Definition: hba.c:2112
char * user_name
Definition: libpq-be.h:137
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:43
#define AllocSetContextCreate(parent, name, allocparams)
Definition: memutils.h:165
#define SSL_get_current_compression(x)
Definition: port.h:387
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:428
int errmsg(const char *fmt,...)
Definition: elog.c:797
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:525
char * database_name
Definition: libpq-be.h:136
#define _(x)
Definition: elog.c:84
MemoryContext PostmasterContext
Definition: mcxt.c:45

◆ pg_split_opts()

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

Definition at line 437 of file postinit.c.

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

Referenced by BackendRun(), and process_startup_options().

438 {
439  StringInfoData s;
440 
441  initStringInfo(&s);
442 
443  while (*optstr)
444  {
445  bool last_was_escape = false;
446 
447  resetStringInfo(&s);
448 
449  /* skip over leading space */
450  while (isspace((unsigned char) *optstr))
451  optstr++;
452 
453  if (*optstr == '\0')
454  break;
455 
456  /*
457  * Parse a single option, stopping at the first space, unless it's
458  * escaped.
459  */
460  while (*optstr)
461  {
462  if (isspace((unsigned char) *optstr) && !last_was_escape)
463  break;
464 
465  if (!last_was_escape && *optstr == '\\')
466  last_was_escape = true;
467  else
468  {
469  last_was_escape = false;
470  appendStringInfoChar(&s, *optstr);
471  }
472 
473  optstr++;
474  }
475 
476  /* now store the option in the next argv[] position */
477  argv[(*argcp)++] = pstrdup(s.data);
478  }
479 
480  pfree(s.data);
481 }
char * pstrdup(const char *in)
Definition: mcxt.c:1063
void pfree(void *pointer)
Definition: mcxt.c:936
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:62
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46

◆ process_settings()

static void process_settings ( Oid  databaseid,
Oid  roleid 
)
static

Definition at line 1113 of file postinit.c.

References AccessShareLock, ApplySetting(), DbRoleSettingRelationId, GetCatalogSnapshot(), heap_close, heap_open(), InvalidOid, IsUnderPostmaster, PGC_S_DATABASE, PGC_S_DATABASE_USER, PGC_S_GLOBAL, PGC_S_USER, RegisterSnapshot(), and UnregisterSnapshot().

Referenced by InitPostgres().

1114 {
1115  Relation relsetting;
1116  Snapshot snapshot;
1117 
1118  if (!IsUnderPostmaster)
1119  return;
1120 
1122 
1123  /* read all the settings under the same snapshot for efficiency */
1125 
1126  /* Later settings are ignored if set earlier. */
1127  ApplySetting(snapshot, databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
1128  ApplySetting(snapshot, InvalidOid, roleid, relsetting, PGC_S_USER);
1129  ApplySetting(snapshot, databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
1130  ApplySetting(snapshot, InvalidOid, InvalidOid, relsetting, PGC_S_GLOBAL);
1131 
1132  UnregisterSnapshot(snapshot);
1133  heap_close(relsetting, AccessShareLock);
1134 }
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:863
Snapshot GetCatalogSnapshot(Oid relid)
Definition: snapmgr.c:440
#define AccessShareLock
Definition: lockdefs.h:36
#define heap_close(r, l)
Definition: heapam.h:97
bool IsUnderPostmaster
Definition: globals.c:101
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:905
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define InvalidOid
Definition: postgres_ext.h:36
void ApplySetting(Snapshot snapshot, Oid databaseid, Oid roleid, Relation relsetting, GucSource source)
#define DbRoleSettingRelationId

◆ process_startup_options()

static void process_startup_options ( Port port,
bool  am_superuser 
)
static

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

1049 {
1050  GucContext gucctx;
1051  ListCell *gucopts;
1052 
1053  gucctx = am_superuser ? PGC_SU_BACKEND : PGC_BACKEND;
1054 
1055  /*
1056  * First process any command-line switches that were included in the
1057  * startup packet, if we are in a regular backend.
1058  */
1059  if (port->cmdline_options != NULL)
1060  {
1061  /*
1062  * The maximum possible number of commandline arguments that could
1063  * come from port->cmdline_options is (strlen + 1) / 2; see
1064  * pg_split_opts().
1065  */
1066  char **av;
1067  int maxac;
1068  int ac;
1069 
1070  maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
1071 
1072  av = (char **) palloc(maxac * sizeof(char *));
1073  ac = 0;
1074 
1075  av[ac++] = "postgres";
1076 
1077  pg_split_opts(av, &ac, port->cmdline_options);
1078 
1079  av[ac] = NULL;
1080 
1081  Assert(ac < maxac);
1082 
1083  (void) process_postgres_switches(ac, av, gucctx, NULL);
1084  }
1085 
1086  /*
1087  * Process any additional GUC variable settings passed in startup packet.
1088  * These are handled exactly like command-line variables.
1089  */
1090  gucopts = list_head(port->guc_options);
1091  while (gucopts)
1092  {
1093  char *name;
1094  char *value;
1095 
1096  name = lfirst(gucopts);
1097  gucopts = lnext(gucopts);
1098 
1099  value = lfirst(gucopts);
1100  gucopts = lnext(gucopts);
1101 
1102  SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
1103  }
1104 }
GucContext
Definition: guc.h:68
List * guc_options
Definition: libpq-be.h:139
static struct @121 value
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6700
void pg_split_opts(char **argv, int *argcp, const char *optstr)
Definition: postinit.c:437
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
struct @18::@19 av[32]
#define Assert(condition)
Definition: c.h:680
#define lfirst(lc)
Definition: pg_list.h:106
const char * name
Definition: encode.c:521
void * palloc(Size size)
Definition: mcxt.c:835
char * cmdline_options
Definition: libpq-be.h:138
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3356

◆ ShutdownPostgres()

static void ShutdownPostgres ( int  code,
Datum  arg 
)
static

Definition at line 1147 of file postinit.c.

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

Referenced by InitPostgres().

1148 {
1149  /* Make sure we've killed any active transaction */
1151 
1152  /*
1153  * User locks are not released by transaction end, so be sure to release
1154  * them explicitly.
1155  */
1157 }
void AbortOutOfAnyTransaction(void)
Definition: xact.c:4344
#define USER_LOCKMETHOD
Definition: lock.h:129
void LockReleaseAll(LOCKMETHODID lockmethodid, bool allLocks)
Definition: lock.c:2014

◆ StatementTimeoutHandler()

static void StatementTimeoutHandler ( void  )
static

Definition at line 1164 of file postinit.c.

References ClientAuthInProgress, kill, MyProcPid, and sig.

Referenced by InitPostgres().

1165 {
1166  int sig = SIGINT;
1167 
1168  /*
1169  * During authentication the timeout is used to deal with
1170  * authentication_timeout - we want to quit in response to such timeouts.
1171  */
1173  sig = SIGTERM;
1174 
1175 #ifdef HAVE_SETSID
1176  /* try to signal whole process group */
1177  kill(-MyProcPid, sig);
1178 #endif
1179  kill(MyProcPid, sig);
1180 }
int MyProcPid
Definition: globals.c:39
#define kill(pid, sig)
Definition: win32_port.h:437
bool ClientAuthInProgress
Definition: postmaster.c:350
static int sig
Definition: pg_ctl.c:80

◆ ThereIsAtLeastOneRole()

static bool ThereIsAtLeastOneRole ( void  )
static

Definition at line 1207 of file postinit.c.

References AccessShareLock, AuthIdRelationId, ForwardScanDirection, heap_beginscan_catalog(), heap_close, heap_endscan(), heap_getnext(), and heap_open().

Referenced by InitPostgres().

1208 {
1209  Relation pg_authid_rel;
1210  HeapScanDesc scan;
1211  bool result;
1212 
1213  pg_authid_rel = heap_open(AuthIdRelationId, AccessShareLock);
1214 
1215  scan = heap_beginscan_catalog(pg_authid_rel, 0, NULL);
1216  result = (heap_getnext(scan, ForwardScanDirection) != NULL);
1217 
1218  heap_endscan(scan);
1219  heap_close(pg_authid_rel, AccessShareLock);
1220 
1221  return result;
1222 }
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1565
#define AccessShareLock
Definition: lockdefs.h:36
#define heap_close(r, l)
Definition: heapam.h:97
#define AuthIdRelationId
Definition: pg_authid.h:42
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1405
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1808
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290