PostgreSQL Source Code  git master
postinit.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * postinit.c
4  * postgres initialization utilities
5  *
6  * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/utils/init/postinit.c
12  *
13  *
14  *-------------------------------------------------------------------------
15  */
16 #include "postgres.h"
17 
18 #include <ctype.h>
19 #include <fcntl.h>
20 #include <unistd.h>
21 
22 #include "access/genam.h"
23 #include "access/heapam.h"
24 #include "access/htup_details.h"
25 #include "access/session.h"
26 #include "access/sysattr.h"
27 #include "access/tableam.h"
28 #include "access/xact.h"
29 #include "access/xlog.h"
30 #include "access/xloginsert.h"
31 #include "catalog/catalog.h"
32 #include "catalog/namespace.h"
33 #include "catalog/pg_authid.h"
34 #include "catalog/pg_collation.h"
35 #include "catalog/pg_database.h"
37 #include "catalog/pg_tablespace.h"
38 #include "libpq/auth.h"
39 #include "libpq/libpq-be.h"
40 #include "mb/pg_wchar.h"
41 #include "miscadmin.h"
42 #include "pgstat.h"
43 #include "postmaster/autovacuum.h"
44 #include "postmaster/postmaster.h"
45 #include "replication/slot.h"
46 #include "replication/slotsync.h"
47 #include "replication/walsender.h"
48 #include "storage/bufmgr.h"
49 #include "storage/fd.h"
50 #include "storage/ipc.h"
51 #include "storage/lmgr.h"
52 #include "storage/proc.h"
53 #include "storage/procarray.h"
54 #include "storage/procsignal.h"
55 #include "storage/sinvaladt.h"
56 #include "storage/smgr.h"
57 #include "storage/sync.h"
58 #include "tcop/tcopprot.h"
59 #include "utils/acl.h"
60 #include "utils/builtins.h"
61 #include "utils/fmgroids.h"
62 #include "utils/guc_hooks.h"
63 #include "utils/memutils.h"
64 #include "utils/pg_locale.h"
65 #include "utils/portal.h"
66 #include "utils/ps_status.h"
67 #include "utils/snapmgr.h"
68 #include "utils/syscache.h"
69 #include "utils/timeout.h"
70 
71 static HeapTuple GetDatabaseTuple(const char *dbname);
72 static HeapTuple GetDatabaseTupleByOid(Oid dboid);
73 static void PerformAuthentication(Port *port);
74 static void CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections);
75 static void ShutdownPostgres(int code, Datum arg);
76 static void StatementTimeoutHandler(void);
77 static void LockTimeoutHandler(void);
79 static void TransactionTimeoutHandler(void);
80 static void IdleSessionTimeoutHandler(void);
81 static void IdleStatsUpdateTimeoutHandler(void);
82 static void ClientCheckTimeoutHandler(void);
83 static bool ThereIsAtLeastOneRole(void);
84 static void process_startup_options(Port *port, bool am_superuser);
85 static void process_settings(Oid databaseid, Oid roleid);
86 
87 
88 /*** InitPostgres support ***/
89 
90 
91 /*
92  * GetDatabaseTuple -- fetch the pg_database row for a database
93  *
94  * This is used during backend startup when we don't yet have any access to
95  * system catalogs in general. In the worst case, we can seqscan pg_database
96  * using nothing but the hard-wired descriptor that relcache.c creates for
97  * pg_database. In more typical cases, relcache.c was able to load
98  * descriptors for both pg_database and its indexes from the shared relcache
99  * cache file, and so we can do an indexscan. criticalSharedRelcachesBuilt
100  * tells whether we got the cached descriptors.
101  */
102 static HeapTuple
104 {
105  HeapTuple tuple;
106  Relation relation;
107  SysScanDesc scan;
108  ScanKeyData key[1];
109 
110  /*
111  * form a scan key
112  */
113  ScanKeyInit(&key[0],
114  Anum_pg_database_datname,
115  BTEqualStrategyNumber, F_NAMEEQ,
117 
118  /*
119  * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
120  * built the critical shared relcache entries (i.e., we're starting up
121  * without a shared relcache cache file).
122  */
123  relation = table_open(DatabaseRelationId, AccessShareLock);
124  scan = systable_beginscan(relation, DatabaseNameIndexId,
126  NULL,
127  1, key);
128 
129  tuple = systable_getnext(scan);
130 
131  /* Must copy tuple before releasing buffer */
132  if (HeapTupleIsValid(tuple))
133  tuple = heap_copytuple(tuple);
134 
135  /* all done */
136  systable_endscan(scan);
137  table_close(relation, AccessShareLock);
138 
139  return tuple;
140 }
141 
142 /*
143  * GetDatabaseTupleByOid -- as above, but search by database OID
144  */
145 static HeapTuple
147 {
148  HeapTuple tuple;
149  Relation relation;
150  SysScanDesc scan;
151  ScanKeyData key[1];
152 
153  /*
154  * form a scan key
155  */
156  ScanKeyInit(&key[0],
157  Anum_pg_database_oid,
158  BTEqualStrategyNumber, F_OIDEQ,
159  ObjectIdGetDatum(dboid));
160 
161  /*
162  * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
163  * built the critical shared relcache entries (i.e., we're starting up
164  * without a shared relcache cache file).
165  */
166  relation = table_open(DatabaseRelationId, AccessShareLock);
167  scan = systable_beginscan(relation, DatabaseOidIndexId,
169  NULL,
170  1, key);
171 
172  tuple = systable_getnext(scan);
173 
174  /* Must copy tuple before releasing buffer */
175  if (HeapTupleIsValid(tuple))
176  tuple = heap_copytuple(tuple);
177 
178  /* all done */
179  systable_endscan(scan);
180  table_close(relation, AccessShareLock);
181 
182  return tuple;
183 }
184 
185 
186 /*
187  * PerformAuthentication -- authenticate a remote client
188  *
189  * returns: nothing. Will not return at all if there's any failure.
190  */
191 static void
193 {
194  /* This should be set already, but let's make sure */
195  ClientAuthInProgress = true; /* limit visibility of log messages */
196 
197  /*
198  * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
199  * etcetera from the postmaster, and have to load them ourselves.
200  *
201  * FIXME: [fork/exec] Ugh. Is there a way around this overhead?
202  */
203 #ifdef EXEC_BACKEND
204 
205  /*
206  * load_hba() and load_ident() want to work within the PostmasterContext,
207  * so create that if it doesn't exist (which it won't). We'll delete it
208  * again later, in PostgresMain.
209  */
210  if (PostmasterContext == NULL)
212  "Postmaster",
214 
215  if (!load_hba())
216  {
217  /*
218  * It makes no sense to continue if we fail to load the HBA file,
219  * since there is no way to connect to the database in this case.
220  */
221  ereport(FATAL,
222  /* translator: %s is a configuration file */
223  (errmsg("could not load %s", HbaFileName)));
224  }
225 
226  if (!load_ident())
227  {
228  /*
229  * It is ok to continue if we fail to load the IDENT file, although it
230  * means that you cannot log in using any of the authentication
231  * methods that need a user name mapping. load_ident() already logged
232  * the details of error to the log.
233  */
234  }
235 #endif
236 
237  /*
238  * Set up a timeout in case a buggy or malicious client fails to respond
239  * during authentication. Since we're inside a transaction and might do
240  * database access, we have to use the statement_timeout infrastructure.
241  */
243 
244  /*
245  * Now perform authentication exchange.
246  */
247  set_ps_display("authentication");
248  ClientAuthentication(port); /* might not return, if failure */
249 
250  /*
251  * Done with authentication. Disable the timeout, and log if needed.
252  */
254 
255  if (Log_connections)
256  {
257  StringInfoData logmsg;
258 
259  initStringInfo(&logmsg);
260  if (am_walsender)
261  appendStringInfo(&logmsg, _("replication connection authorized: user=%s"),
262  port->user_name);
263  else
264  appendStringInfo(&logmsg, _("connection authorized: user=%s"),
265  port->user_name);
266  if (!am_walsender)
267  appendStringInfo(&logmsg, _(" database=%s"), port->database_name);
268 
269  if (port->application_name != NULL)
270  appendStringInfo(&logmsg, _(" application_name=%s"),
271  port->application_name);
272 
273 #ifdef USE_SSL
274  if (port->ssl_in_use)
275  appendStringInfo(&logmsg, _(" SSL enabled (protocol=%s, cipher=%s, bits=%d)"),
279 #endif
280 #ifdef ENABLE_GSS
281  if (port->gss)
282  {
283  const char *princ = be_gssapi_get_princ(port);
284 
285  if (princ)
286  appendStringInfo(&logmsg,
287  _(" GSS (authenticated=%s, encrypted=%s, delegated_credentials=%s, principal=%s)"),
288  be_gssapi_get_auth(port) ? _("yes") : _("no"),
289  be_gssapi_get_enc(port) ? _("yes") : _("no"),
290  be_gssapi_get_delegation(port) ? _("yes") : _("no"),
291  princ);
292  else
293  appendStringInfo(&logmsg,
294  _(" GSS (authenticated=%s, encrypted=%s, delegated_credentials=%s)"),
295  be_gssapi_get_auth(port) ? _("yes") : _("no"),
296  be_gssapi_get_enc(port) ? _("yes") : _("no"),
297  be_gssapi_get_delegation(port) ? _("yes") : _("no"));
298  }
299 #endif
300 
301  ereport(LOG, errmsg_internal("%s", logmsg.data));
302  pfree(logmsg.data);
303  }
304 
305  set_ps_display("startup");
306 
307  ClientAuthInProgress = false; /* client_min_messages is active now */
308 }
309 
310 
311 /*
312  * CheckMyDatabase -- fetch information from the pg_database entry for our DB
313  */
314 static void
315 CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections)
316 {
317  HeapTuple tup;
318  Form_pg_database dbform;
319  Datum datum;
320  bool isnull;
321  char *collate;
322  char *ctype;
323  char *iculocale;
324 
325  /* Fetch our pg_database row normally, via syscache */
326  tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
327  if (!HeapTupleIsValid(tup))
328  elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
329  dbform = (Form_pg_database) GETSTRUCT(tup);
330 
331  /* This recheck is strictly paranoia */
332  if (strcmp(name, NameStr(dbform->datname)) != 0)
333  ereport(FATAL,
334  (errcode(ERRCODE_UNDEFINED_DATABASE),
335  errmsg("database \"%s\" has disappeared from pg_database",
336  name),
337  errdetail("Database OID %u now seems to belong to \"%s\".",
338  MyDatabaseId, NameStr(dbform->datname))));
339 
340  /*
341  * Check permissions to connect to the database.
342  *
343  * These checks are not enforced when in standalone mode, so that there is
344  * a way to recover from disabling all access to all databases, for
345  * example "UPDATE pg_database SET datallowconn = false;".
346  *
347  * We do not enforce them for autovacuum worker processes either.
348  */
350  {
351  /*
352  * Check that the database is currently allowing connections.
353  */
354  if (!dbform->datallowconn && !override_allow_connections)
355  ereport(FATAL,
356  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
357  errmsg("database \"%s\" is not currently accepting connections",
358  name)));
359 
360  /*
361  * Check privilege to connect to the database. (The am_superuser test
362  * is redundant, but since we have the flag, might as well check it
363  * and save a few cycles.)
364  */
365  if (!am_superuser &&
366  object_aclcheck(DatabaseRelationId, MyDatabaseId, GetUserId(),
368  ereport(FATAL,
369  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
370  errmsg("permission denied for database \"%s\"", name),
371  errdetail("User does not have CONNECT privilege.")));
372 
373  /*
374  * Check connection limit for this database.
375  *
376  * There is a race condition here --- we create our PGPROC before
377  * checking for other PGPROCs. If two backends did this at about the
378  * same time, they might both think they were over the limit, while
379  * ideally one should succeed and one fail. Getting that to work
380  * exactly seems more trouble than it is worth, however; instead we
381  * just document that the connection limit is approximate.
382  */
383  if (dbform->datconnlimit >= 0 &&
384  !am_superuser &&
385  CountDBConnections(MyDatabaseId) > dbform->datconnlimit)
386  ereport(FATAL,
387  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
388  errmsg("too many connections for database \"%s\"",
389  name)));
390  }
391 
392  /*
393  * OK, we're golden. Next to-do item is to save the encoding info out of
394  * the pg_database tuple.
395  */
396  SetDatabaseEncoding(dbform->encoding);
397  /* Record it as a GUC internal option, too */
398  SetConfigOption("server_encoding", GetDatabaseEncodingName(),
400  /* If we have no other source of client_encoding, use server encoding */
401  SetConfigOption("client_encoding", GetDatabaseEncodingName(),
403 
404  /* assign locale variables */
405  datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datcollate);
406  collate = TextDatumGetCString(datum);
407  datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datctype);
408  ctype = TextDatumGetCString(datum);
409 
410  if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
411  ereport(FATAL,
412  (errmsg("database locale is incompatible with operating system"),
413  errdetail("The database was initialized with LC_COLLATE \"%s\", "
414  " which is not recognized by setlocale().", collate),
415  errhint("Recreate the database with another locale or install the missing locale.")));
416 
417  if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
418  ereport(FATAL,
419  (errmsg("database locale is incompatible with operating system"),
420  errdetail("The database was initialized with LC_CTYPE \"%s\", "
421  " which is not recognized by setlocale().", ctype),
422  errhint("Recreate the database with another locale or install the missing locale.")));
423 
424  if (strcmp(ctype, "C") == 0 ||
425  strcmp(ctype, "POSIX") == 0)
426  database_ctype_is_c = true;
427 
428  if (dbform->datlocprovider == COLLPROVIDER_ICU)
429  {
430  char *icurules;
431 
432  datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_daticulocale);
433  iculocale = TextDatumGetCString(datum);
434 
435  datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_daticurules, &isnull);
436  if (!isnull)
437  icurules = TextDatumGetCString(datum);
438  else
439  icurules = NULL;
440 
441  make_icu_collator(iculocale, icurules, &default_locale);
442  }
443  else
444  iculocale = NULL;
445 
446  default_locale.provider = dbform->datlocprovider;
447 
448  /*
449  * Default locale is currently always deterministic. Nondeterministic
450  * locales currently don't support pattern matching, which would break a
451  * lot of things if applied globally.
452  */
454 
455  /*
456  * Check collation version. See similar code in
457  * pg_newlocale_from_collation(). Note that here we warn instead of error
458  * in any case, so that we don't prevent connecting.
459  */
460  datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_datcollversion,
461  &isnull);
462  if (!isnull)
463  {
464  char *actual_versionstr;
465  char *collversionstr;
466 
467  collversionstr = TextDatumGetCString(datum);
468 
469  actual_versionstr = get_collation_actual_version(dbform->datlocprovider, dbform->datlocprovider == COLLPROVIDER_ICU ? iculocale : collate);
470  if (!actual_versionstr)
471  /* should not happen */
472  elog(WARNING,
473  "database \"%s\" has no actual collation version, but a version was recorded",
474  name);
475  else if (strcmp(actual_versionstr, collversionstr) != 0)
477  (errmsg("database \"%s\" has a collation version mismatch",
478  name),
479  errdetail("The database was created using collation version %s, "
480  "but the operating system provides version %s.",
481  collversionstr, actual_versionstr),
482  errhint("Rebuild all objects in this database that use the default collation and run "
483  "ALTER DATABASE %s REFRESH COLLATION VERSION, "
484  "or build PostgreSQL with the right library version.",
486  }
487 
488  ReleaseSysCache(tup);
489 }
490 
491 
492 /*
493  * pg_split_opts -- split a string of options and append it to an argv array
494  *
495  * The caller is responsible for ensuring the argv array is large enough. The
496  * maximum possible number of arguments added by this routine is
497  * (strlen(optstr) + 1) / 2.
498  *
499  * Because some option values can contain spaces we allow escaping using
500  * backslashes, with \\ representing a literal backslash.
501  */
502 void
503 pg_split_opts(char **argv, int *argcp, const char *optstr)
504 {
505  StringInfoData s;
506 
507  initStringInfo(&s);
508 
509  while (*optstr)
510  {
511  bool last_was_escape = false;
512 
513  resetStringInfo(&s);
514 
515  /* skip over leading space */
516  while (isspace((unsigned char) *optstr))
517  optstr++;
518 
519  if (*optstr == '\0')
520  break;
521 
522  /*
523  * Parse a single option, stopping at the first space, unless it's
524  * escaped.
525  */
526  while (*optstr)
527  {
528  if (isspace((unsigned char) *optstr) && !last_was_escape)
529  break;
530 
531  if (!last_was_escape && *optstr == '\\')
532  last_was_escape = true;
533  else
534  {
535  last_was_escape = false;
536  appendStringInfoChar(&s, *optstr);
537  }
538 
539  optstr++;
540  }
541 
542  /* now store the option in the next argv[] position */
543  argv[(*argcp)++] = pstrdup(s.data);
544  }
545 
546  pfree(s.data);
547 }
548 
549 /*
550  * Initialize MaxBackends value from config options.
551  *
552  * This must be called after modules have had the chance to alter GUCs in
553  * shared_preload_libraries and before shared memory size is determined.
554  *
555  * Note that in EXEC_BACKEND environment, the value is passed down from
556  * postmaster to subprocesses via BackendParameters in SubPostmasterMain; only
557  * postmaster itself and processes not under postmaster control should call
558  * this.
559  */
560 void
562 {
563  Assert(MaxBackends == 0);
564 
565  /* the extra unit accounts for the autovacuum launcher */
568 
569  /* internal error because the values were all checked previously */
571  elog(ERROR, "too many backends configured");
572 }
573 
574 /*
575  * GUC check_hook for max_connections
576  */
577 bool
579 {
580  if (*newval + autovacuum_max_workers + 1 +
582  return false;
583  return true;
584 }
585 
586 /*
587  * GUC check_hook for autovacuum_max_workers
588  */
589 bool
591 {
592  if (MaxConnections + *newval + 1 +
594  return false;
595  return true;
596 }
597 
598 /*
599  * GUC check_hook for max_worker_processes
600  */
601 bool
603 {
606  return false;
607  return true;
608 }
609 
610 /*
611  * GUC check_hook for max_wal_senders
612  */
613 bool
615 {
618  return false;
619  return true;
620 }
621 
622 /*
623  * Early initialization of a backend (either standalone or under postmaster).
624  * This happens even before InitPostgres.
625  *
626  * This is separate from InitPostgres because it is also called by auxiliary
627  * processes, such as the background writer process, which may not call
628  * InitPostgres at all.
629  */
630 void
631 BaseInit(void)
632 {
633  Assert(MyProc != NULL);
634 
635  /*
636  * Initialize our input/output/debugging file descriptors.
637  */
638  DebugFileOpen();
639 
640  /*
641  * Initialize file access. Done early so other subsystems can access
642  * files.
643  */
644  InitFileAccess();
645 
646  /*
647  * Initialize statistics reporting. This needs to happen early to ensure
648  * that pgstat's shutdown callback runs after the shutdown callbacks of
649  * all subsystems that can produce stats (like e.g. transaction commits
650  * can).
651  */
653 
654  /* Do local initialization of storage and buffer managers */
655  InitSync();
656  smgrinit();
658 
659  /*
660  * Initialize temporary file access after pgstat, so that the temporary
661  * file shutdown hook can report temporary file statistics.
662  */
664 
665  /*
666  * Initialize local buffers for WAL record construction, in case we ever
667  * try to insert XLOG.
668  */
669  InitXLogInsert();
670 
671  /*
672  * Initialize replication slots after pgstat. The exit hook might need to
673  * drop ephemeral slots, which in turn triggers stats reporting.
674  */
676 }
677 
678 
679 /* --------------------------------
680  * InitPostgres
681  * Initialize POSTGRES.
682  *
683  * Parameters:
684  * in_dbname, dboid: specify database to connect to, as described below
685  * username, useroid: specify role to connect as, as described below
686  * flags:
687  * - INIT_PG_LOAD_SESSION_LIBS to honor [session|local]_preload_libraries.
688  * - INIT_PG_OVERRIDE_ALLOW_CONNS to connect despite !datallowconn.
689  * - INIT_PG_OVERRIDE_ROLE_LOGIN to connect despite !rolcanlogin.
690  * out_dbname: optional output parameter, see below; pass NULL if not used
691  *
692  * The database can be specified by name, using the in_dbname parameter, or by
693  * OID, using the dboid parameter. Specify NULL or InvalidOid respectively
694  * for the unused parameter. If dboid is provided, the actual database
695  * name can be returned to the caller in out_dbname. If out_dbname isn't
696  * NULL, it must point to a buffer of size NAMEDATALEN.
697  *
698  * Similarly, the role can be passed by name, using the username parameter,
699  * or by OID using the useroid parameter.
700  *
701  * In bootstrap mode the database and username parameters are NULL/InvalidOid.
702  * The autovacuum launcher process doesn't specify these parameters either,
703  * because it only goes far enough to be able to read pg_database; it doesn't
704  * connect to any particular database. An autovacuum worker specifies a
705  * database but not a username; conversely, a physical walsender specifies
706  * username but not database.
707  *
708  * By convention, INIT_PG_LOAD_SESSION_LIBS should be passed in "flags" in
709  * "interactive" sessions (including standalone backends), but not in
710  * background processes such as autovacuum. Note in particular that it
711  * shouldn't be true in parallel worker processes; those have another
712  * mechanism for replicating their leader's set of loaded libraries.
713  *
714  * We expect that InitProcess() was already called, so we already have a
715  * PGPROC struct ... but it's not completely filled in yet.
716  *
717  * Note:
718  * Be very careful with the order of calls in the InitPostgres function.
719  * --------------------------------
720  */
721 void
722 InitPostgres(const char *in_dbname, Oid dboid,
723  const char *username, Oid useroid,
724  bits32 flags,
725  char *out_dbname)
726 {
727  bool bootstrap = IsBootstrapProcessingMode();
728  bool am_superuser;
729  char *fullpath;
730  char dbname[NAMEDATALEN];
731  int nfree = 0;
732 
733  elog(DEBUG3, "InitPostgres");
734 
735  /*
736  * Add my PGPROC struct to the ProcArray.
737  *
738  * Once I have done this, I am visible to other backends!
739  */
741 
742  /*
743  * Initialize my entry in the shared-invalidation manager's array of
744  * per-backend data.
745  *
746  * Sets up MyBackendId, a unique backend identifier.
747  */
749 
750  SharedInvalBackendInit(false);
751 
752  if (MyBackendId > MaxBackends || MyBackendId <= 0)
753  elog(FATAL, "bad backend ID: %d", MyBackendId);
754 
755  /* Now that we have a BackendId, we can participate in ProcSignal */
757 
758  /*
759  * Also set up timeout handlers needed for backend operation. We need
760  * these in every case except bootstrap.
761  */
762  if (!bootstrap)
763  {
774  }
775 
776  /*
777  * If this is either a bootstrap process or a standalone backend, start up
778  * the XLOG machinery, and register to have it closed down at exit. In
779  * other cases, the startup process is responsible for starting up the
780  * XLOG machinery, and the checkpointer for closing it down.
781  */
782  if (!IsUnderPostmaster)
783  {
784  /*
785  * We don't yet have an aux-process resource owner, but StartupXLOG
786  * and ShutdownXLOG will need one. Hence, create said resource owner
787  * (and register a callback to clean it up after ShutdownXLOG runs).
788  */
790 
791  StartupXLOG();
792  /* Release (and warn about) any buffer pins leaked in StartupXLOG */
794  /* Reset CurrentResourceOwner to nothing for the moment */
795  CurrentResourceOwner = NULL;
796 
797  /*
798  * Use before_shmem_exit() so that ShutdownXLOG() can rely on DSM
799  * segments etc to work (which in turn is required for pgstats).
800  */
803  }
804 
805  /*
806  * Initialize the relation cache and the system catalog caches. Note that
807  * no catalog access happens here; we only set up the hashtable structure.
808  * We must do this before starting a transaction because transaction abort
809  * would try to touch these hashtables.
810  */
813  InitPlanCache();
814 
815  /* Initialize portal manager */
817 
818  /* Initialize status reporting */
819  pgstat_beinit();
820 
821  /*
822  * Load relcache entries for the shared system catalogs. This must create
823  * at least entries for pg_database and catalogs used for authentication.
824  */
826 
827  /*
828  * Set up process-exit callback to do pre-shutdown cleanup. This is the
829  * one of the first before_shmem_exit callbacks we register; thus, this
830  * will be one the last things we do before low-level modules like the
831  * buffer manager begin to close down. We need to have this in place
832  * before we begin our first transaction --- if we fail during the
833  * initialization transaction, as is entirely possible, we need the
834  * AbortTransaction call to clean up.
835  */
837 
838  /* The autovacuum launcher is done here */
840  {
841  /* report this backend in the PgBackendStatus array */
842  pgstat_bestart();
843 
844  return;
845  }
846 
847  /*
848  * Start a new transaction here before first access to db, and get a
849  * snapshot. We don't have a use for the snapshot itself, but we're
850  * interested in the secondary effect that it sets RecentGlobalXmin. (This
851  * is critical for anything that reads heap pages, because HOT may decide
852  * to prune them even if the process doesn't attempt to modify any
853  * tuples.)
854  *
855  * FIXME: This comment is inaccurate / the code buggy. A snapshot that is
856  * not pushed/active does not reliably prevent HOT pruning (->xmin could
857  * e.g. be cleared when cache invalidations are processed).
858  */
859  if (!bootstrap)
860  {
861  /* statement_timestamp must be set for timeouts to work correctly */
864 
865  /*
866  * transaction_isolation will have been set to the default by the
867  * above. If the default is "serializable", and we are in hot
868  * standby, we will fail if we don't change it to something lower.
869  * Fortunately, "read committed" is plenty good enough.
870  */
872 
873  (void) GetTransactionSnapshot();
874  }
875 
876  /*
877  * Perform client authentication if necessary, then figure out our
878  * postgres user ID, and see if we are a superuser.
879  *
880  * In standalone mode, autovacuum worker processes and slot sync worker
881  * process, we use a fixed ID, otherwise we figure it out from the
882  * authenticated user name.
883  */
884  if (bootstrap || IsAutoVacuumWorkerProcess() || IsLogicalSlotSyncWorker())
885  {
887  am_superuser = true;
888  }
889  else if (!IsUnderPostmaster)
890  {
892  am_superuser = true;
893  if (!ThereIsAtLeastOneRole())
895  (errcode(ERRCODE_UNDEFINED_OBJECT),
896  errmsg("no roles are defined in this database system"),
897  errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
898  username != NULL ? username : "postgres")));
899  }
900  else if (IsBackgroundWorker)
901  {
902  if (username == NULL && !OidIsValid(useroid))
903  {
905  am_superuser = true;
906  }
907  else
908  {
910  (flags & INIT_PG_OVERRIDE_ROLE_LOGIN) != 0);
911  am_superuser = superuser();
912  }
913  }
914  else
915  {
916  /* normal multiuser case */
917  Assert(MyProcPort != NULL);
919  InitializeSessionUserId(username, useroid, false);
920  /* ensure that auth_method is actually valid, aka authn_id is not NULL */
924  am_superuser = superuser();
925  }
926 
927  /*
928  * Binary upgrades only allowed super-user connections
929  */
930  if (IsBinaryUpgrade && !am_superuser)
931  {
932  ereport(FATAL,
933  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
934  errmsg("must be superuser to connect in binary upgrade mode")));
935  }
936 
937  /*
938  * The last few connection slots are reserved for superusers and roles
939  * with privileges of pg_use_reserved_connections. Replication
940  * connections are drawn from slots reserved with max_wal_senders and are
941  * not limited by max_connections, superuser_reserved_connections, or
942  * reserved_connections.
943  *
944  * Note: At this point, the new backend has already claimed a proc struct,
945  * so we must check whether the number of free slots is strictly less than
946  * the reserved connection limits.
947  */
948  if (!am_superuser && !am_walsender &&
951  {
952  if (nfree < SuperuserReservedConnections)
953  ereport(FATAL,
954  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
955  errmsg("remaining connection slots are reserved for roles with the %s attribute",
956  "SUPERUSER")));
957 
958  if (!has_privs_of_role(GetUserId(), ROLE_PG_USE_RESERVED_CONNECTIONS))
959  ereport(FATAL,
960  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
961  errmsg("remaining connection slots are reserved for roles with privileges of the \"%s\" role",
962  "pg_use_reserved_connections")));
963  }
964 
965  /* Check replication permissions needed for walsender processes. */
966  if (am_walsender)
967  {
968  Assert(!bootstrap);
969 
971  ereport(FATAL,
972  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
973  errmsg("permission denied to start WAL sender"),
974  errdetail("Only roles with the %s attribute may start a WAL sender process.",
975  "REPLICATION")));
976  }
977 
978  /*
979  * If this is a plain walsender only supporting physical replication, we
980  * don't want to connect to any particular database. Just finish the
981  * backend startup by processing any options from the startup packet, and
982  * we're done.
983  */
985  {
986  /* process any options passed in the startup packet */
987  if (MyProcPort != NULL)
988  process_startup_options(MyProcPort, am_superuser);
989 
990  /* Apply PostAuthDelay as soon as we've read all options */
991  if (PostAuthDelay > 0)
992  pg_usleep(PostAuthDelay * 1000000L);
993 
994  /* initialize client encoding */
996 
997  /* report this backend in the PgBackendStatus array */
998  pgstat_bestart();
999 
1000  /* close the transaction we started above */
1002 
1003  return;
1004  }
1005 
1006  /*
1007  * Set up the global variables holding database id and default tablespace.
1008  * But note we won't actually try to touch the database just yet.
1009  *
1010  * We take a shortcut in the bootstrap case, otherwise we have to look up
1011  * the db's entry in pg_database.
1012  */
1013  if (bootstrap)
1014  {
1015  dboid = Template1DbOid;
1016  MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
1017  }
1018  else if (in_dbname != NULL)
1019  {
1020  HeapTuple tuple;
1021  Form_pg_database dbform;
1022 
1023  tuple = GetDatabaseTuple(in_dbname);
1024  if (!HeapTupleIsValid(tuple))
1025  ereport(FATAL,
1026  (errcode(ERRCODE_UNDEFINED_DATABASE),
1027  errmsg("database \"%s\" does not exist", in_dbname)));
1028  dbform = (Form_pg_database) GETSTRUCT(tuple);
1029  dboid = dbform->oid;
1030  }
1031  else if (!OidIsValid(dboid))
1032  {
1033  /*
1034  * If this is a background worker not bound to any particular
1035  * database, we're done now. Everything that follows only makes sense
1036  * if we are bound to a specific database. We do need to close the
1037  * transaction we started before returning.
1038  */
1039  if (!bootstrap)
1040  {
1041  pgstat_bestart();
1043  }
1044  return;
1045  }
1046 
1047  /*
1048  * Now, take a writer's lock on the database we are trying to connect to.
1049  * If there is a concurrently running DROP DATABASE on that database, this
1050  * will block us until it finishes (and has committed its update of
1051  * pg_database).
1052  *
1053  * Note that the lock is not held long, only until the end of this startup
1054  * transaction. This is OK since we will advertise our use of the
1055  * database in the ProcArray before dropping the lock (in fact, that's the
1056  * next thing to do). Anyone trying a DROP DATABASE after this point will
1057  * see us in the array once they have the lock. Ordering is important for
1058  * this because we don't want to advertise ourselves as being in this
1059  * database until we have the lock; otherwise we create what amounts to a
1060  * deadlock with CountOtherDBBackends().
1061  *
1062  * Note: use of RowExclusiveLock here is reasonable because we envision
1063  * our session as being a concurrent writer of the database. If we had a
1064  * way of declaring a session as being guaranteed-read-only, we could use
1065  * AccessShareLock for such sessions and thereby not conflict against
1066  * CREATE DATABASE.
1067  */
1068  if (!bootstrap)
1069  LockSharedObject(DatabaseRelationId, dboid, 0, RowExclusiveLock);
1070 
1071  /*
1072  * Recheck pg_database to make sure the target database hasn't gone away.
1073  * If there was a concurrent DROP DATABASE, this ensures we will die
1074  * cleanly without creating a mess.
1075  */
1076  if (!bootstrap)
1077  {
1078  HeapTuple tuple;
1079  Form_pg_database datform;
1080 
1081  tuple = GetDatabaseTupleByOid(dboid);
1082  if (HeapTupleIsValid(tuple))
1083  datform = (Form_pg_database) GETSTRUCT(tuple);
1084 
1085  if (!HeapTupleIsValid(tuple) ||
1086  (in_dbname && namestrcmp(&datform->datname, in_dbname)))
1087  {
1088  if (in_dbname)
1089  ereport(FATAL,
1090  (errcode(ERRCODE_UNDEFINED_DATABASE),
1091  errmsg("database \"%s\" does not exist", in_dbname),
1092  errdetail("It seems to have just been dropped or renamed.")));
1093  else
1094  ereport(FATAL,
1095  (errcode(ERRCODE_UNDEFINED_DATABASE),
1096  errmsg("database %u does not exist", dboid)));
1097  }
1098 
1099  strlcpy(dbname, NameStr(datform->datname), sizeof(dbname));
1100 
1101  if (database_is_invalid_form(datform))
1102  {
1103  ereport(FATAL,
1104  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1105  errmsg("cannot connect to invalid database \"%s\"", dbname),
1106  errhint("Use DROP DATABASE to drop invalid databases."));
1107  }
1108 
1109  MyDatabaseTableSpace = datform->dattablespace;
1110  MyDatabaseHasLoginEventTriggers = datform->dathasloginevt;
1111  /* pass the database name back to the caller */
1112  if (out_dbname)
1113  strcpy(out_dbname, dbname);
1114  }
1115 
1116  /*
1117  * Now that we rechecked, we are certain to be connected to a database and
1118  * thus can set MyDatabaseId.
1119  *
1120  * It is important that MyDatabaseId only be set once we are sure that the
1121  * target database can no longer be concurrently dropped or renamed. For
1122  * example, without this guarantee, pgstat_update_dbstats() could create
1123  * entries for databases that were just dropped in the pgstat shutdown
1124  * callback, which could confuse other code paths like the autovacuum
1125  * scheduler.
1126  */
1127  MyDatabaseId = dboid;
1128 
1129  /*
1130  * Now we can mark our PGPROC entry with the database ID.
1131  *
1132  * We assume this is an atomic store so no lock is needed; though actually
1133  * things would work fine even if it weren't atomic. Anyone searching the
1134  * ProcArray for this database's ID should hold the database lock, so they
1135  * would not be executing concurrently with this store. A process looking
1136  * for another database's ID could in theory see a chance match if it read
1137  * a partially-updated databaseId value; but as long as all such searches
1138  * wait and retry, as in CountOtherDBBackends(), they will certainly see
1139  * the correct value on their next try.
1140  */
1142 
1143  /*
1144  * We established a catalog snapshot while reading pg_authid and/or
1145  * pg_database; but until we have set up MyDatabaseId, we won't react to
1146  * incoming sinval messages for unshared catalogs, so we won't realize it
1147  * if the snapshot has been invalidated. Assume it's no good anymore.
1148  */
1150 
1151  /*
1152  * Now we should be able to access the database directory safely. Verify
1153  * it's there and looks reasonable.
1154  */
1156 
1157  if (!bootstrap)
1158  {
1159  if (access(fullpath, F_OK) == -1)
1160  {
1161  if (errno == ENOENT)
1162  ereport(FATAL,
1163  (errcode(ERRCODE_UNDEFINED_DATABASE),
1164  errmsg("database \"%s\" does not exist",
1165  dbname),
1166  errdetail("The database subdirectory \"%s\" is missing.",
1167  fullpath)));
1168  else
1169  ereport(FATAL,
1171  errmsg("could not access directory \"%s\": %m",
1172  fullpath)));
1173  }
1174 
1175  ValidatePgVersion(fullpath);
1176  }
1177 
1178  SetDatabasePath(fullpath);
1179  pfree(fullpath);
1180 
1181  /*
1182  * It's now possible to do real access to the system catalogs.
1183  *
1184  * Load relcache entries for the system catalogs. This must create at
1185  * least the minimum set of "nailed-in" cache entries.
1186  */
1188 
1189  /* set up ACL framework (so CheckMyDatabase can check permissions) */
1190  initialize_acl();
1191 
1192  /*
1193  * Re-read the pg_database row for our database, check permissions and set
1194  * up database-specific GUC settings. We can't do this until all the
1195  * database-access infrastructure is up. (Also, it wants to know if the
1196  * user is a superuser, so the above stuff has to happen first.)
1197  */
1198  if (!bootstrap)
1199  CheckMyDatabase(dbname, am_superuser,
1200  (flags & INIT_PG_OVERRIDE_ALLOW_CONNS) != 0);
1201 
1202  /*
1203  * Now process any command-line switches and any additional GUC variable
1204  * settings passed in the startup packet. We couldn't do this before
1205  * because we didn't know if client is a superuser.
1206  */
1207  if (MyProcPort != NULL)
1208  process_startup_options(MyProcPort, am_superuser);
1209 
1210  /* Process pg_db_role_setting options */
1212 
1213  /* Apply PostAuthDelay as soon as we've read all options */
1214  if (PostAuthDelay > 0)
1215  pg_usleep(PostAuthDelay * 1000000L);
1216 
1217  /*
1218  * Initialize various default states that can't be set up until we've
1219  * selected the active user and gotten the right GUC settings.
1220  */
1221 
1222  /* set default namespace search path */
1224 
1225  /* initialize client encoding */
1227 
1228  /* Initialize this backend's session state. */
1230 
1231  /*
1232  * If this is an interactive session, load any libraries that should be
1233  * preloaded at backend start. Since those are determined by GUCs, this
1234  * can't happen until GUC settings are complete, but we want it to happen
1235  * during the initial transaction in case anything that requires database
1236  * access needs to be done.
1237  */
1238  if ((flags & INIT_PG_LOAD_SESSION_LIBS) != 0)
1240 
1241  /* report this backend in the PgBackendStatus array */
1242  if (!bootstrap)
1243  pgstat_bestart();
1244 
1245  /* close the transaction we started above */
1246  if (!bootstrap)
1248 }
1249 
1250 /*
1251  * Process any command-line switches and any additional GUC variable
1252  * settings passed in the startup packet.
1253  */
1254 static void
1255 process_startup_options(Port *port, bool am_superuser)
1256 {
1257  GucContext gucctx;
1258  ListCell *gucopts;
1259 
1260  gucctx = am_superuser ? PGC_SU_BACKEND : PGC_BACKEND;
1261 
1262  /*
1263  * First process any command-line switches that were included in the
1264  * startup packet, if we are in a regular backend.
1265  */
1266  if (port->cmdline_options != NULL)
1267  {
1268  /*
1269  * The maximum possible number of commandline arguments that could
1270  * come from port->cmdline_options is (strlen + 1) / 2; see
1271  * pg_split_opts().
1272  */
1273  char **av;
1274  int maxac;
1275  int ac;
1276 
1277  maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
1278 
1279  av = (char **) palloc(maxac * sizeof(char *));
1280  ac = 0;
1281 
1282  av[ac++] = "postgres";
1283 
1284  pg_split_opts(av, &ac, port->cmdline_options);
1285 
1286  av[ac] = NULL;
1287 
1288  Assert(ac < maxac);
1289 
1290  (void) process_postgres_switches(ac, av, gucctx, NULL);
1291  }
1292 
1293  /*
1294  * Process any additional GUC variable settings passed in startup packet.
1295  * These are handled exactly like command-line variables.
1296  */
1297  gucopts = list_head(port->guc_options);
1298  while (gucopts)
1299  {
1300  char *name;
1301  char *value;
1302 
1303  name = lfirst(gucopts);
1304  gucopts = lnext(port->guc_options, gucopts);
1305 
1306  value = lfirst(gucopts);
1307  gucopts = lnext(port->guc_options, gucopts);
1308 
1310  }
1311 }
1312 
1313 /*
1314  * Load GUC settings from pg_db_role_setting.
1315  *
1316  * We try specific settings for the database/role combination, as well as
1317  * general for this database and for this user.
1318  */
1319 static void
1320 process_settings(Oid databaseid, Oid roleid)
1321 {
1322  Relation relsetting;
1323  Snapshot snapshot;
1324 
1325  if (!IsUnderPostmaster)
1326  return;
1327 
1328  relsetting = table_open(DbRoleSettingRelationId, AccessShareLock);
1329 
1330  /* read all the settings under the same snapshot for efficiency */
1331  snapshot = RegisterSnapshot(GetCatalogSnapshot(DbRoleSettingRelationId));
1332 
1333  /* Later settings are ignored if set earlier. */
1334  ApplySetting(snapshot, databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
1335  ApplySetting(snapshot, InvalidOid, roleid, relsetting, PGC_S_USER);
1336  ApplySetting(snapshot, databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
1337  ApplySetting(snapshot, InvalidOid, InvalidOid, relsetting, PGC_S_GLOBAL);
1338 
1339  UnregisterSnapshot(snapshot);
1340  table_close(relsetting, AccessShareLock);
1341 }
1342 
1343 /*
1344  * Backend-shutdown callback. Do cleanup that we want to be sure happens
1345  * before all the supporting modules begin to nail their doors shut via
1346  * their own callbacks.
1347  *
1348  * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
1349  * via separate callbacks that execute before this one. We don't combine the
1350  * callbacks because we still want this one to happen if the user-level
1351  * cleanup fails.
1352  */
1353 static void
1355 {
1356  /* Make sure we've killed any active transaction */
1358 
1359  /*
1360  * User locks are not released by transaction end, so be sure to release
1361  * them explicitly.
1362  */
1364 }
1365 
1366 
1367 /*
1368  * STATEMENT_TIMEOUT handler: trigger a query-cancel interrupt.
1369  */
1370 static void
1372 {
1373  int sig = SIGINT;
1374 
1375  /*
1376  * During authentication the timeout is used to deal with
1377  * authentication_timeout - we want to quit in response to such timeouts.
1378  */
1380  sig = SIGTERM;
1381 
1382 #ifdef HAVE_SETSID
1383  /* try to signal whole process group */
1384  kill(-MyProcPid, sig);
1385 #endif
1386  kill(MyProcPid, sig);
1387 }
1388 
1389 /*
1390  * LOCK_TIMEOUT handler: trigger a query-cancel interrupt.
1391  */
1392 static void
1394 {
1395 #ifdef HAVE_SETSID
1396  /* try to signal whole process group */
1397  kill(-MyProcPid, SIGINT);
1398 #endif
1399  kill(MyProcPid, SIGINT);
1400 }
1401 
1402 static void
1404 {
1406  InterruptPending = true;
1407  SetLatch(MyLatch);
1408 }
1409 
1410 static void
1412 {
1414  InterruptPending = true;
1415  SetLatch(MyLatch);
1416 }
1417 
1418 static void
1420 {
1422  InterruptPending = true;
1423  SetLatch(MyLatch);
1424 }
1425 
1426 static void
1428 {
1430  InterruptPending = true;
1431  SetLatch(MyLatch);
1432 }
1433 
1434 static void
1436 {
1438  InterruptPending = true;
1439  SetLatch(MyLatch);
1440 }
1441 
1442 /*
1443  * Returns true if at least one role is defined in this database cluster.
1444  */
1445 static bool
1447 {
1448  Relation pg_authid_rel;
1449  TableScanDesc scan;
1450  bool result;
1451 
1452  pg_authid_rel = table_open(AuthIdRelationId, AccessShareLock);
1453 
1454  scan = table_beginscan_catalog(pg_authid_rel, 0, NULL);
1455  result = (heap_getnext(scan, ForwardScanDirection) != NULL);
1456 
1457  table_endscan(scan);
1458  table_close(pg_authid_rel, AccessShareLock);
1459 
1460  return result;
1461 }
void initialize_acl(void)
Definition: acl.c:4870
bool has_privs_of_role(Oid member, Oid role)
Definition: acl.c:5060
@ ACLCHECK_OK
Definition: acl.h:182
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:3878
void ClientAuthentication(Port *port)
Definition: auth.c:384
int autovacuum_max_workers
Definition: autovacuum.c:118
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:3361
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3367
void pgstat_beinit(void)
void pgstat_bestart(void)
#define InvalidBackendId
Definition: backendid.h:23
bool be_gssapi_get_auth(Port *port)
bool be_gssapi_get_enc(Port *port)
const char * be_gssapi_get_princ(Port *port)
bool be_gssapi_get_delegation(Port *port)
const char * be_tls_get_version(Port *port)
int be_tls_get_cipher_bits(Port *port)
const char * be_tls_get_cipher(Port *port)
void InitBufferPoolAccess(void)
Definition: bufmgr.c:3230
#define TextDatumGetCString(d)
Definition: builtins.h:98
#define NameStr(name)
Definition: c.h:735
uint32 bits32
Definition: c.h:504
#define OidIsValid(objectId)
Definition: c.h:764
bool database_is_invalid_form(Form_pg_database datform)
Definition: dbcommands.c:3113
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1162
void DebugFileOpen(void)
Definition: elog.c:2072
int errcode_for_file_access(void)
Definition: elog.c:883
int errdetail(const char *fmt,...)
Definition: elog.c:1208
int errhint(const char *fmt,...)
Definition: elog.c:1322
int errcode(int sqlerrcode)
Definition: elog.c:860
int errmsg(const char *fmt,...)
Definition: elog.c:1075
#define _(x)
Definition: elog.c:91
#define LOG
Definition: elog.h:31
#define DEBUG3
Definition: elog.h:28
#define FATAL
Definition: elog.h:41
#define WARNING
Definition: elog.h:36
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
void InitFileAccess(void)
Definition: fd.c:903
void InitTemporaryFileAccess(void)
Definition: fd.c:933
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:599
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:506
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:387
volatile sig_atomic_t IdleStatsUpdateTimeoutPending
Definition: globals.c:40
bool MyDatabaseHasLoginEventTriggers
Definition: globals.c:94
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
volatile sig_atomic_t IdleSessionTimeoutPending
Definition: globals.c:37
bool IsBinaryUpgrade
Definition: globals.c:117
volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
Definition: globals.c:35
volatile sig_atomic_t TransactionTimeoutPending
Definition: globals.c:36
int MyProcPid
Definition: globals.c:45
bool IsUnderPostmaster
Definition: globals.c:116
int MaxConnections
Definition: globals.c:140
bool IsBackgroundWorker
Definition: globals.c:118
BackendId MyBackendId
Definition: globals.c:86
Oid MyDatabaseTableSpace
Definition: globals.c:92
int MaxBackends
Definition: globals.c:143
struct Port * MyProcPort
Definition: globals.c:48
struct Latch * MyLatch
Definition: globals.c:59
volatile sig_atomic_t CheckClientConnectionPending
Definition: globals.c:33
int max_worker_processes
Definition: globals.c:141
Oid MyDatabaseId
Definition: globals.c:90
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4256
#define newval
GucSource
Definition: guc.h:108
@ PGC_S_DYNAMIC_DEFAULT
Definition: guc.h:110
@ PGC_S_GLOBAL
Definition: guc.h:114
@ PGC_S_DATABASE
Definition: guc.h:115
@ PGC_S_CLIENT
Definition: guc.h:118
@ PGC_S_DATABASE_USER
Definition: guc.h:117
@ PGC_S_USER
Definition: guc.h:116
GucContext
Definition: guc.h:68
@ PGC_INTERNAL
Definition: guc.h:69
@ PGC_SU_BACKEND
Definition: guc.h:72
@ PGC_BACKEND
Definition: guc.h:73
char * HbaFileName
Definition: guc_tables.c:539
bool load_ident(void)
Definition: hba.c:2964
const char * hba_authname(UserAuth auth_method)
Definition: hba.c:3066
bool load_hba(void)
Definition: hba.c:2588
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1086
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:777
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
static struct @148 value
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:337
void SetLatch(Latch *latch)
Definition: latch.c:633
Assert(fmt[strlen(fmt) - 1] !='\n')
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1046
void LockReleaseAll(LOCKMETHODID lockmethodid, bool allLocks)
Definition: lock.c:2130
#define USER_LOCKMETHOD
Definition: lock.h:126
#define AccessShareLock
Definition: lockdefs.h:36
#define RowExclusiveLock
Definition: lockdefs.h:38
void InitializeClientEncoding(void)
Definition: mbutils.c:282
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1274
void SetDatabaseEncoding(int encoding)
Definition: mbutils.c:1162
char * pstrdup(const char *in)
Definition: mcxt.c:1619
void pfree(void *pointer)
Definition: mcxt.c:1431
MemoryContext TopMemoryContext
Definition: mcxt.c:141
MemoryContext PostmasterContext
Definition: mcxt.c:143
void * palloc(Size size)
Definition: mcxt.c:1201
#define AllocSetContextCreate
Definition: memutils.h:128
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:152
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:416
#define INIT_PG_LOAD_SESSION_LIBS
Definition: miscadmin.h:471
#define INIT_PG_OVERRIDE_ROLE_LOGIN
Definition: miscadmin.h:473
#define INIT_PG_OVERRIDE_ALLOW_CONNS
Definition: miscadmin.h:472
void InitializeSessionUserId(const char *rolename, Oid roleid, bool bypass_login_check)
Definition: miscinit.c:734
void InitializeSystemUser(const char *authn_id, const char *auth_method)
Definition: miscinit.c:868
void InitializeSessionUserIdStandalone(void)
Definition: miscinit.c:838
void process_session_preload_libraries(void)
Definition: miscinit.c:1858
Oid GetUserId(void)
Definition: miscinit.c:515
Oid GetSessionUserId(void)
Definition: miscinit.c:549
void SetDatabasePath(const char *path)
Definition: miscinit.c:329
ClientConnectionInfo MyClientConnectionInfo
Definition: miscinit.c:1011
bool has_rolreplication(Oid roleid)
Definition: miscinit.c:712
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1711
int namestrcmp(Name name, const char *str)
Definition: name.c:247
void InitializeSearchPath(void)
Definition: namespace.c:4718
#define ACL_CONNECT
Definition: parsenodes.h:87
void * arg
#define NAMEDATALEN
static int sig
Definition: pg_ctl.c:79
FormData_pg_database * Form_pg_database
Definition: pg_database.h:96
void ApplySetting(Snapshot snapshot, Oid databaseid, Oid roleid, Relation relsetting, GucSource source)
#define lfirst(lc)
Definition: pg_list.h:172
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
void make_icu_collator(const char *iculocstr, const char *icurules, struct pg_locale_struct *resultp)
Definition: pg_locale.c:1412
struct pg_locale_struct default_locale
Definition: pg_locale.c:1409
bool database_ctype_is_c
Definition: pg_locale.c:118
char * get_collation_actual_version(char collprovider, const char *collcollate)
Definition: pg_locale.c:1677
char * pg_perm_setlocale(int category, const char *locale)
Definition: pg_locale.c:213
static int port
Definition: pg_regress.c:116
static rewind_source * source
Definition: pg_rewind.c:89
const char * username
Definition: pgbench.c:296
void pgstat_initialize(void)
Definition: pgstat.c:540
void pgstat_before_server_shutdown(int code, Datum arg)
Definition: pgstat.c:465
void InitPlanCache(void)
Definition: plancache.c:156
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
void EnablePortalManager(void)
Definition: portalmem.c:105
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3782
int PostAuthDelay
Definition: postgres.c:100
uintptr_t Datum
Definition: postgres.h:64
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
static Datum CStringGetDatum(const char *X)
Definition: postgres.h:350
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
static void ShutdownPostgres(int code, Datum arg)
Definition: postinit.c:1354
static void IdleInTransactionSessionTimeoutHandler(void)
Definition: postinit.c:1411
static void LockTimeoutHandler(void)
Definition: postinit.c:1393
bool check_autovacuum_max_workers(int *newval, void **extra, GucSource source)
Definition: postinit.c:590
void InitializeMaxBackends(void)
Definition: postinit.c:561
void pg_split_opts(char **argv, int *argcp, const char *optstr)
Definition: postinit.c:503
static void IdleStatsUpdateTimeoutHandler(void)
Definition: postinit.c:1427
static void process_settings(Oid databaseid, Oid roleid)
Definition: postinit.c:1320
void BaseInit(void)
Definition: postinit.c:631
bool check_max_connections(int *newval, void **extra, GucSource source)
Definition: postinit.c:578
static void IdleSessionTimeoutHandler(void)
Definition: postinit.c:1419
bool check_max_wal_senders(int *newval, void **extra, GucSource source)
Definition: postinit.c:614
static void process_startup_options(Port *port, bool am_superuser)
Definition: postinit.c:1255
static void StatementTimeoutHandler(void)
Definition: postinit.c:1371
static void CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections)
Definition: postinit.c:315
static bool ThereIsAtLeastOneRole(void)
Definition: postinit.c:1446
static void PerformAuthentication(Port *port)
Definition: postinit.c:192
static void ClientCheckTimeoutHandler(void)
Definition: postinit.c:1435
bool check_max_worker_processes(int *newval, void **extra, GucSource source)
Definition: postinit.c:602
static HeapTuple GetDatabaseTuple(const char *dbname)
Definition: postinit.c:103
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition: postinit.c:722
static HeapTuple GetDatabaseTupleByOid(Oid dboid)
Definition: postinit.c:146
static void TransactionTimeoutHandler(void)
Definition: postinit.c:1403
bool Log_connections
Definition: postmaster.c:240
int ReservedConnections
Definition: postmaster.c:226
bool ClientAuthInProgress
Definition: postmaster.c:359
int AuthenticationTimeout
Definition: postmaster.c:237
int SuperuserReservedConnections
Definition: postmaster.c:225
#define MAX_BACKENDS
Definition: postmaster.h:78
short access
Definition: preproc-type.c:36
int CountDBConnections(Oid databaseid)
Definition: procarray.c:3543
void ProcSignalInit(int pss_idx)
Definition: procsignal.c:162
static void set_ps_display(const char *activity)
Definition: ps_status.h:40
bool criticalSharedRelcachesBuilt
Definition: relcache.c:148
void RelationCacheInitializePhase3(void)
Definition: relcache.c:4055
void RelationCacheInitialize(void)
Definition: relcache.c:3950
void RelationCacheInitializePhase2(void)
Definition: relcache.c:3996
char * GetDatabasePath(Oid dbOid, Oid spcOid)
Definition: relpath.c:110
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:1002
ResourceOwner CurrentResourceOwner
Definition: resowner.c:165
void CreateAuxProcessResourceOwner(void)
Definition: resowner.c:982
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11975
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
@ ForwardScanDirection
Definition: sdir.h:28
struct @10::@11 av[32]
void InitializeSession(void)
Definition: session.c:54
void pg_usleep(long microsec)
Definition: signal.c:53
void SharedInvalBackendInit(bool sendOnly)
Definition: sinvaladt.c:266
void ReplicationSlotInitialize(void)
Definition: slot.c:187
bool IsLogicalSlotSyncWorker(void)
Definition: slotsync.c:1438
void smgrinit(void)
Definition: smgr.c:155
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:223
Snapshot GetCatalogSnapshot(Oid relid)
Definition: snapmgr.c:359
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:843
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:801
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:429
PGPROC * MyProc
Definition: proc.c:68
bool HaveNFreeProcs(int n, int *nfree)
Definition: proc.c:691
void CheckDeadLockAlert(void)
Definition: proc.c:1821
void InitProcessPhase2(void)
Definition: proc.c:491
#define BTEqualStrategyNumber
Definition: stratnum.h:31
char * dbname
Definition: streamutil.c:51
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:78
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:97
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:194
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
const char * authn_id
Definition: libpq-be.h:114
UserAuth auth_method
Definition: libpq-be.h:120
Oid databaseId
Definition: proc.h:193
Definition: libpq-be.h:147
bool deterministic
Definition: pg_locale.h:76
bool superuser(void)
Definition: superuser.c:46
void InitSync(void)
Definition: sync.c:129
void InitCatalogCache(void)
Definition: syscache.c:108
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:267
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:219
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:480
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition: syscache.c:511
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:1009
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:560
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:685
TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
Definition: timeout.c:505
@ IDLE_SESSION_TIMEOUT
Definition: timeout.h:35
@ IDLE_IN_TRANSACTION_SESSION_TIMEOUT
Definition: timeout.h:33
@ LOCK_TIMEOUT
Definition: timeout.h:28
@ STATEMENT_TIMEOUT
Definition: timeout.h:29
@ DEADLOCK_TIMEOUT
Definition: timeout.h:27
@ TRANSACTION_TIMEOUT
Definition: timeout.h:34
@ IDLE_STATS_UPDATE_TIMEOUT
Definition: timeout.h:36
@ CLIENT_CONNECTION_CHECK_TIMEOUT
Definition: timeout.h:37
const char * name
bool am_walsender
Definition: walsender.c:118
bool am_db_walsender
Definition: walsender.c:121
int max_wal_senders
Definition: walsender.c:124
#define kill(pid, sig)
Definition: win32_port.h:485
void StartTransactionCommand(void)
Definition: xact.c:2953
int XactIsoLevel
Definition: xact.c:79
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:899
void CommitTransactionCommand(void)
Definition: xact.c:3050
void AbortOutOfAnyTransaction(void)
Definition: xact.c:4728
#define XACT_READ_COMMITTED
Definition: xact.h:37
void StartupXLOG(void)
Definition: xlog.c:5319
void ShutdownXLOG(int code, Datum arg)
Definition: xlog.c:6462
void InitXLogInsert(void)
Definition: xloginsert.c:1349