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