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

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

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

525 {
526  /*
527  * Attach to shared memory and semaphores, and initialize our
528  * input/output/debugging file descriptors.
529  */
531  DebugFileOpen();
532 
533  /* Do local initialization of file, storage and buffer managers */
534  InitFileAccess();
535  smgrinit();
537 }
static void InitCommunication(void)
Definition: postinit.c:416
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:779

◆ CheckMyDatabase()

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

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

294 {
295  HeapTuple tup;
296  Form_pg_database dbform;
297  char *collate;
298  char *ctype;
299 
300  /* Fetch our pg_database row normally, via syscache */
302  if (!HeapTupleIsValid(tup))
303  elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
304  dbform = (Form_pg_database) GETSTRUCT(tup);
305 
306  /* This recheck is strictly paranoia */
307  if (strcmp(name, NameStr(dbform->datname)) != 0)
308  ereport(FATAL,
309  (errcode(ERRCODE_UNDEFINED_DATABASE),
310  errmsg("database \"%s\" has disappeared from pg_database",
311  name),
312  errdetail("Database OID %u now seems to belong to \"%s\".",
313  MyDatabaseId, NameStr(dbform->datname))));
314 
315  /*
316  * Check permissions to connect to the database.
317  *
318  * These checks are not enforced when in standalone mode, so that there is
319  * a way to recover from disabling all access to all databases, for
320  * example "UPDATE pg_database SET datallowconn = false;".
321  *
322  * We do not enforce them for autovacuum worker processes either.
323  */
325  {
326  /*
327  * Check that the database is currently allowing connections.
328  */
329  if (!dbform->datallowconn)
330  ereport(FATAL,
331  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
332  errmsg("database \"%s\" is not currently accepting connections",
333  name)));
334 
335  /*
336  * Check privilege to connect to the database. (The am_superuser test
337  * is redundant, but since we have the flag, might as well check it
338  * and save a few cycles.)
339  */
340  if (!am_superuser &&
343  ereport(FATAL,
344  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
345  errmsg("permission denied for database \"%s\"", name),
346  errdetail("User does not have CONNECT privilege.")));
347 
348  /*
349  * Check connection limit for this database.
350  *
351  * There is a race condition here --- we create our PGPROC before
352  * checking for other PGPROCs. If two backends did this at about the
353  * same time, they might both think they were over the limit, while
354  * ideally one should succeed and one fail. Getting that to work
355  * exactly seems more trouble than it is worth, however; instead we
356  * just document that the connection limit is approximate.
357  */
358  if (dbform->datconnlimit >= 0 &&
359  !am_superuser &&
360  CountDBConnections(MyDatabaseId) > dbform->datconnlimit)
361  ereport(FATAL,
362  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
363  errmsg("too many connections for database \"%s\"",
364  name)));
365  }
366 
367  /*
368  * OK, we're golden. Next to-do item is to save the encoding info out of
369  * the pg_database tuple.
370  */
371  SetDatabaseEncoding(dbform->encoding);
372  /* Record it as a GUC internal option, too */
373  SetConfigOption("server_encoding", GetDatabaseEncodingName(),
375  /* If we have no other source of client_encoding, use server encoding */
376  SetConfigOption("client_encoding", GetDatabaseEncodingName(),
378 
379  /* assign locale variables */
380  collate = NameStr(dbform->datcollate);
381  ctype = NameStr(dbform->datctype);
382 
383  if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
384  ereport(FATAL,
385  (errmsg("database locale is incompatible with operating system"),
386  errdetail("The database was initialized with LC_COLLATE \"%s\", "
387  " which is not recognized by setlocale().", collate),
388  errhint("Recreate the database with another locale or install the missing locale.")));
389 
390  if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
391  ereport(FATAL,
392  (errmsg("database locale is incompatible with operating system"),
393  errdetail("The database was initialized with LC_CTYPE \"%s\", "
394  " which is not recognized by setlocale().", ctype),
395  errhint("Recreate the database with another locale or install the missing locale.")));
396 
397  /* Make the locale settings visible as GUC variables, too */
398  SetConfigOption("lc_collate", collate, PGC_INTERNAL, PGC_S_OVERRIDE);
399  SetConfigOption("lc_ctype", ctype, PGC_INTERNAL, PGC_S_OVERRIDE);
400 
402 
403  ReleaseSysCache(tup);
404 }
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:490
#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:6720
bool IsUnderPostmaster
Definition: globals.c:101
int errdetail(const char *fmt,...)
Definition: elog.c:873
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3255
#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:4640
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:565
#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:561
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:490
#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 1202 of file postinit.c.

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

Referenced by InitPostgres().

1203 {
1205  InterruptPending = true;
1206  SetLatch(MyLatch);
1207 }
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 416 of file postinit.c.

References CreateSharedMemoryAndSemaphores(), and IsUnderPostmaster.

Referenced by BaseInit().

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

◆ InitializeMaxBackends()

void InitializeMaxBackends ( void  )

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

503 {
504  Assert(MaxBackends == 0);
505 
506  /* the extra unit accounts for the autovacuum launcher */
509 
510  /* internal error because the values were all checked previously */
512  elog(ERROR, "too many backends configured");
513 }
#define ERROR
Definition: elog.h:43
#define MAX_BACKENDS
Definition: postmaster.h:75
int MaxBackends
Definition: globals.c:127
int MaxConnections
Definition: globals.c:124
int autovacuum_max_workers
Definition: autovacuum.c:114
#define Assert(condition)
Definition: c.h:688
int max_worker_processes
Definition: globals.c:125
#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 565 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().

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

References kill, and MyProcPid.

Referenced by InitPostgres().

1193 {
1194 #ifdef HAVE_SETSID
1195  /* try to signal whole process group */
1196  kill(-MyProcPid, SIGINT);
1197 #endif
1198  kill(MyProcPid, SIGINT);
1199 }
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, 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().

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_SSL
250  if (port->ssl_in_use)
251  ereport(LOG,
252  (errmsg("replication connection authorized: user=%s SSL enabled (protocol=%s, cipher=%s, bits=%d, compression=%s)",
253  port->user_name,
254  be_tls_get_version(port),
255  be_tls_get_cipher(port),
257  be_tls_get_compression(port) ? _("on") : _("off"))));
258  else
259 #endif
260  ereport(LOG,
261  (errmsg("replication connection authorized: user=%s",
262  port->user_name)));
263  }
264  else
265  {
266 #ifdef USE_SSL
267  if (port->ssl_in_use)
268  ereport(LOG,
269  (errmsg("connection authorized: user=%s database=%s SSL enabled (protocol=%s, cipher=%s, bits=%d, compression=%s)",
270  port->user_name, port->database_name,
271  be_tls_get_version(port),
272  be_tls_get_cipher(port),
274  be_tls_get_compression(port) ? _("on") : _("off"))));
275  else
276 #endif
277  ereport(LOG,
278  (errmsg("connection authorized: user=%s database=%s",
279  port->user_name, port->database_name)));
280  }
281  }
282 
283  set_ps_display("startup", false);
284 
285  ClientAuthInProgress = false; /* client_min_messages is active now */
286 }
void ClientAuthentication(Port *port)
Definition: auth.c:347
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:2913
int AuthenticationTimeout
Definition: postmaster.c:237
bool ClientAuthInProgress
Definition: postmaster.c:350
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:197
bool load_hba(void)
Definition: hba.c:2126
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
int be_tls_get_cipher_bits(Port *port)
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:428
const char * be_tls_get_version(Port *port)
int errmsg(const char *fmt,...)
Definition: elog.c:797
const char * be_tls_get_cipher(Port *port)
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 443 of file postinit.c.

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

Referenced by BackendRun(), and process_startup_options().

444 {
445  StringInfoData s;
446 
447  initStringInfo(&s);
448 
449  while (*optstr)
450  {
451  bool last_was_escape = false;
452 
453  resetStringInfo(&s);
454 
455  /* skip over leading space */
456  while (isspace((unsigned char) *optstr))
457  optstr++;
458 
459  if (*optstr == '\0')
460  break;
461 
462  /*
463  * Parse a single option, stopping at the first space, unless it's
464  * escaped.
465  */
466  while (*optstr)
467  {
468  if (isspace((unsigned char) *optstr) && !last_was_escape)
469  break;
470 
471  if (!last_was_escape && *optstr == '\\')
472  last_was_escape = true;
473  else
474  {
475  last_was_escape = false;
476  appendStringInfoChar(&s, *optstr);
477  }
478 
479  optstr++;
480  }
481 
482  /* now store the option in the next argv[] position */
483  argv[(*argcp)++] = pstrdup(s.data);
484  }
485 
486  pfree(s.data);
487 }
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 1119 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().

1120 {
1121  Relation relsetting;
1122  Snapshot snapshot;
1123 
1124  if (!IsUnderPostmaster)
1125  return;
1126 
1128 
1129  /* read all the settings under the same snapshot for efficiency */
1131 
1132  /* Later settings are ignored if set earlier. */
1133  ApplySetting(snapshot, databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
1134  ApplySetting(snapshot, InvalidOid, roleid, relsetting, PGC_S_USER);
1135  ApplySetting(snapshot, databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
1136  ApplySetting(snapshot, InvalidOid, InvalidOid, relsetting, PGC_S_GLOBAL);
1137 
1138  UnregisterSnapshot(snapshot);
1139  heap_close(relsetting, AccessShareLock);
1140 }
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 1054 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().

1055 {
1056  GucContext gucctx;
1057  ListCell *gucopts;
1058 
1059  gucctx = am_superuser ? PGC_SU_BACKEND : PGC_BACKEND;
1060 
1061  /*
1062  * First process any command-line switches that were included in the
1063  * startup packet, if we are in a regular backend.
1064  */
1065  if (port->cmdline_options != NULL)
1066  {
1067  /*
1068  * The maximum possible number of commandline arguments that could
1069  * come from port->cmdline_options is (strlen + 1) / 2; see
1070  * pg_split_opts().
1071  */
1072  char **av;
1073  int maxac;
1074  int ac;
1075 
1076  maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
1077 
1078  av = (char **) palloc(maxac * sizeof(char *));
1079  ac = 0;
1080 
1081  av[ac++] = "postgres";
1082 
1083  pg_split_opts(av, &ac, port->cmdline_options);
1084 
1085  av[ac] = NULL;
1086 
1087  Assert(ac < maxac);
1088 
1089  (void) process_postgres_switches(ac, av, gucctx, NULL);
1090  }
1091 
1092  /*
1093  * Process any additional GUC variable settings passed in startup packet.
1094  * These are handled exactly like command-line variables.
1095  */
1096  gucopts = list_head(port->guc_options);
1097  while (gucopts)
1098  {
1099  char *name;
1100  char *value;
1101 
1102  name = lfirst(gucopts);
1103  gucopts = lnext(gucopts);
1104 
1105  value = lfirst(gucopts);
1106  gucopts = lnext(gucopts);
1107 
1108  SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
1109  }
1110 }
GucContext
Definition: guc.h:68
static struct @130 value
List * guc_options
Definition: libpq-be.h:139
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6720
void pg_split_opts(char **argv, int *argcp, const char *optstr)
Definition: postinit.c:443
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:688
#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:3360

◆ ShutdownPostgres()

static void ShutdownPostgres ( int  code,
Datum  arg 
)
static

Definition at line 1153 of file postinit.c.

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

Referenced by InitPostgres().

1154 {
1155  /* Make sure we've killed any active transaction */
1157 
1158  /*
1159  * User locks are not released by transaction end, so be sure to release
1160  * them explicitly.
1161  */
1163 }
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 1170 of file postinit.c.

References ClientAuthInProgress, kill, MyProcPid, and sig.

Referenced by InitPostgres().

1171 {
1172  int sig = SIGINT;
1173 
1174  /*
1175  * During authentication the timeout is used to deal with
1176  * authentication_timeout - we want to quit in response to such timeouts.
1177  */
1179  sig = SIGTERM;
1180 
1181 #ifdef HAVE_SETSID
1182  /* try to signal whole process group */
1183  kill(-MyProcPid, sig);
1184 #endif
1185  kill(MyProcPid, sig);
1186 }
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 1213 of file postinit.c.

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

Referenced by InitPostgres().

1214 {
1215  Relation pg_authid_rel;
1216  HeapScanDesc scan;
1217  bool result;
1218 
1219  pg_authid_rel = heap_open(AuthIdRelationId, AccessShareLock);
1220 
1221  scan = heap_beginscan_catalog(pg_authid_rel, 0, NULL);
1222  result = (heap_getnext(scan, ForwardScanDirection) != NULL);
1223 
1224  heap_endscan(scan);
1225  heap_close(pg_authid_rel, AccessShareLock);
1226 
1227  return result;
1228 }
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1568
#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:1408
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1831
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290