Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * postinit.c
4 : : * postgres initialization utilities
5 : : *
6 : : * Portions Copyright (c) 1996-2026, 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/tableam.h"
27 : : #include "access/xact.h"
28 : : #include "access/xlog.h"
29 : : #include "access/xloginsert.h"
30 : : #include "catalog/namespace.h"
31 : : #include "catalog/pg_authid.h"
32 : : #include "catalog/pg_collation.h"
33 : : #include "catalog/pg_database.h"
34 : : #include "catalog/pg_db_role_setting.h"
35 : : #include "catalog/pg_tablespace.h"
36 : : #include "libpq/auth.h"
37 : : #include "libpq/libpq-be.h"
38 : : #include "mb/pg_wchar.h"
39 : : #include "miscadmin.h"
40 : : #include "pgstat.h"
41 : : #include "postmaster/autovacuum.h"
42 : : #include "postmaster/postmaster.h"
43 : : #include "replication/slot.h"
44 : : #include "replication/slotsync.h"
45 : : #include "replication/walsender.h"
46 : : #include "storage/aio_subsys.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/procnumber.h"
54 : : #include "storage/procsignal.h"
55 : : #include "storage/sinvaladt.h"
56 : : #include "storage/smgr.h"
57 : : #include "storage/sync.h"
58 : : #include "tcop/backend_startup.h"
59 : : #include "tcop/tcopprot.h"
60 : : #include "utils/acl.h"
61 : : #include "utils/builtins.h"
62 : : #include "utils/fmgroids.h"
63 : : #include "utils/guc_hooks.h"
64 : : #include "utils/injection_point.h"
65 : : #include "utils/memutils.h"
66 : : #include "utils/pg_locale.h"
67 : : #include "utils/portal.h"
68 : : #include "utils/ps_status.h"
69 : : #include "utils/snapmgr.h"
70 : : #include "utils/syscache.h"
71 : : #include "utils/timeout.h"
72 : :
73 : : /* has this backend called EmitConnectionWarnings()? */
74 : : static bool ConnectionWarningsEmitted;
75 : :
76 : : /* content of warnings to send via EmitConnectionWarnings() */
77 : : static List *ConnectionWarningMessages;
78 : : static List *ConnectionWarningDetails;
79 : :
80 : : static HeapTuple GetDatabaseTuple(const char *dbname);
81 : : static HeapTuple GetDatabaseTupleByOid(Oid dboid);
82 : : static void PerformAuthentication(Port *port);
83 : : static void CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections);
84 : : static void ShutdownPostgres(int code, Datum arg);
85 : : static void StatementTimeoutHandler(void);
86 : : static void LockTimeoutHandler(void);
87 : : static void IdleInTransactionSessionTimeoutHandler(void);
88 : : static void TransactionTimeoutHandler(void);
89 : : static void IdleSessionTimeoutHandler(void);
90 : : static void IdleStatsUpdateTimeoutHandler(void);
91 : : static void ClientCheckTimeoutHandler(void);
92 : : static bool ThereIsAtLeastOneRole(void);
93 : : static void process_startup_options(Port *port, bool am_superuser);
94 : : static void process_settings(Oid databaseid, Oid roleid);
95 : : static void EmitConnectionWarnings(void);
96 : :
97 : :
98 : : /*** InitPostgres support ***/
99 : :
100 : :
101 : : /*
102 : : * GetDatabaseTuple -- fetch the pg_database row for a database
103 : : *
104 : : * This is used during backend startup when we don't yet have any access to
105 : : * system catalogs in general. In the worst case, we can seqscan pg_database
106 : : * using nothing but the hard-wired descriptor that relcache.c creates for
107 : : * pg_database. In more typical cases, relcache.c was able to load
108 : : * descriptors for both pg_database and its indexes from the shared relcache
109 : : * cache file, and so we can do an indexscan. criticalSharedRelcachesBuilt
110 : : * tells whether we got the cached descriptors.
111 : : */
112 : : static HeapTuple
6059 tgl@sss.pgh.pa.us 113 :CBC 13315 : GetDatabaseTuple(const char *dbname)
114 : : {
115 : : HeapTuple tuple;
116 : : Relation relation;
117 : : SysScanDesc scan;
118 : : ScanKeyData key[1];
119 : :
120 : : /*
121 : : * form a scan key
122 : : */
123 : 13315 : ScanKeyInit(&key[0],
124 : : Anum_pg_database_datname,
125 : : BTEqualStrategyNumber, F_NAMEEQ,
126 : : CStringGetDatum(dbname));
127 : :
128 : : /*
129 : : * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
130 : : * built the critical shared relcache entries (i.e., we're starting up
131 : : * without a shared relcache cache file).
132 : : */
2610 andres@anarazel.de 133 : 13315 : relation = table_open(DatabaseRelationId, AccessShareLock);
6059 tgl@sss.pgh.pa.us 134 : 13315 : scan = systable_beginscan(relation, DatabaseNameIndexId,
135 : : criticalSharedRelcachesBuilt,
136 : : NULL,
137 : : 1, key);
138 : :
139 : 13315 : tuple = systable_getnext(scan);
140 : :
141 : : /* Must copy tuple before releasing buffer */
142 [ + + ]: 13315 : if (HeapTupleIsValid(tuple))
143 : 13309 : tuple = heap_copytuple(tuple);
144 : :
145 : : /* all done */
146 : 13315 : systable_endscan(scan);
2610 andres@anarazel.de 147 : 13315 : table_close(relation, AccessShareLock);
148 : :
6059 tgl@sss.pgh.pa.us 149 : 13315 : return tuple;
150 : : }
151 : :
152 : : /*
153 : : * GetDatabaseTupleByOid -- as above, but search by database OID
154 : : */
155 : : static HeapTuple
156 : 15425 : GetDatabaseTupleByOid(Oid dboid)
157 : : {
158 : : HeapTuple tuple;
159 : : Relation relation;
160 : : SysScanDesc scan;
161 : : ScanKeyData key[1];
162 : :
163 : : /*
164 : : * form a scan key
165 : : */
166 : 15425 : ScanKeyInit(&key[0],
167 : : Anum_pg_database_oid,
168 : : BTEqualStrategyNumber, F_OIDEQ,
169 : : ObjectIdGetDatum(dboid));
170 : :
171 : : /*
172 : : * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
173 : : * built the critical shared relcache entries (i.e., we're starting up
174 : : * without a shared relcache cache file).
175 : : */
2610 andres@anarazel.de 176 : 15425 : relation = table_open(DatabaseRelationId, AccessShareLock);
6059 tgl@sss.pgh.pa.us 177 : 15425 : scan = systable_beginscan(relation, DatabaseOidIndexId,
178 : : criticalSharedRelcachesBuilt,
179 : : NULL,
180 : : 1, key);
181 : :
182 : 15425 : tuple = systable_getnext(scan);
183 : :
184 : : /* Must copy tuple before releasing buffer */
185 [ + - ]: 15425 : if (HeapTupleIsValid(tuple))
186 : 15425 : tuple = heap_copytuple(tuple);
187 : :
188 : : /* all done */
189 : 15425 : systable_endscan(scan);
2610 andres@anarazel.de 190 : 15425 : table_close(relation, AccessShareLock);
191 : :
6059 tgl@sss.pgh.pa.us 192 : 15425 : return tuple;
193 : : }
194 : :
195 : :
196 : : /*
197 : : * PerformAuthentication -- authenticate a remote client
198 : : *
199 : : * returns: nothing. Will not return at all if there's any failure.
200 : : */
201 : : static void
6042 202 : 13926 : PerformAuthentication(Port *port)
203 : : {
204 : : /* This should be set already, but let's make sure */
205 : 13926 : ClientAuthInProgress = true; /* limit visibility of log messages */
206 : :
207 : : /*
208 : : * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
209 : : * etcetera from the postmaster, and have to load them ourselves.
210 : : *
211 : : * FIXME: [fork/exec] Ugh. Is there a way around this overhead?
212 : : */
213 : : #ifdef EXEC_BACKEND
214 : :
215 : : /*
216 : : * load_hba() and load_ident() want to work within the PostmasterContext,
217 : : * so create that if it doesn't exist (which it won't). We'll delete it
218 : : * again later, in PostgresMain.
219 : : */
220 : : if (PostmasterContext == NULL)
221 : : PostmasterContext = AllocSetContextCreate(TopMemoryContext,
222 : : "Postmaster",
223 : : ALLOCSET_DEFAULT_SIZES);
224 : :
225 : : if (!load_hba())
226 : : {
227 : : /*
228 : : * It makes no sense to continue if we fail to load the HBA file,
229 : : * since there is no way to connect to the database in this case.
230 : : */
231 : : ereport(FATAL,
232 : : /* translator: %s is a configuration file */
233 : : (errmsg("could not load %s", HbaFileName)));
234 : : }
235 : :
236 : : if (!load_ident())
237 : : {
238 : : /*
239 : : * It is ok to continue if we fail to load the IDENT file, although it
240 : : * means that you cannot log in using any of the authentication
241 : : * methods that need a user name mapping. load_ident() already logged
242 : : * the details of error to the log.
243 : : */
244 : : }
245 : : #endif
246 : :
247 : : /* Capture authentication start time for logging */
368 melanieplageman@gmai 248 : 13926 : conn_timing.auth_start = GetCurrentTimestamp();
249 : :
250 : : /*
251 : : * Set up a timeout in case a buggy or malicious client fails to respond
252 : : * during authentication. Since we're inside a transaction and might do
253 : : * database access, we have to use the statement_timeout infrastructure.
254 : : */
4990 alvherre@alvh.no-ip. 255 : 13926 : enable_timeout_after(STATEMENT_TIMEOUT, AuthenticationTimeout * 1000);
256 : :
257 : : /*
258 : : * Now perform authentication exchange.
259 : : */
2195 peter@eisentraut.org 260 : 13926 : set_ps_display("authentication");
6042 tgl@sss.pgh.pa.us 261 : 13926 : ClientAuthentication(port); /* might not return, if failure */
262 : :
263 : : /*
264 : : * Done with authentication. Disable the timeout, and log if needed.
265 : : */
4990 alvherre@alvh.no-ip. 266 : 13735 : disable_timeout(STATEMENT_TIMEOUT, false);
267 : :
268 : : /* Capture authentication end time for logging */
368 melanieplageman@gmai 269 : 13735 : conn_timing.auth_end = GetCurrentTimestamp();
270 : :
271 [ + + ]: 13735 : if (log_connections & LOG_CONNECTION_AUTHORIZATION)
272 : : {
273 : : StringInfoData logmsg;
274 : :
1929 sfrost@snowman.net 275 : 380 : initStringInfo(&logmsg);
5535 magnus@hagander.net 276 [ - + ]: 380 : if (am_walsender)
1929 sfrost@snowman.net 277 :UBC 0 : appendStringInfo(&logmsg, _("replication connection authorized: user=%s"),
278 : : port->user_name);
279 : : else
1929 sfrost@snowman.net 280 :CBC 380 : appendStringInfo(&logmsg, _("connection authorized: user=%s"),
281 : : port->user_name);
282 [ + - ]: 380 : if (!am_walsender)
283 : 380 : appendStringInfo(&logmsg, _(" database=%s"), port->database_name);
284 : :
285 [ + + ]: 380 : if (port->application_name != NULL)
286 : 377 : appendStringInfo(&logmsg, _(" application_name=%s"),
287 : : port->application_name);
288 : :
289 : : #ifdef USE_SSL
290 [ + + ]: 380 : if (port->ssl_in_use)
1832 michael@paquier.xyz 291 : 106 : appendStringInfo(&logmsg, _(" SSL enabled (protocol=%s, cipher=%s, bits=%d)"),
292 : : be_tls_get_version(port),
293 : : be_tls_get_cipher(port),
294 : : be_tls_get_cipher_bits(port));
295 : : #endif
296 : : #ifdef ENABLE_GSS
1903 tgl@sss.pgh.pa.us 297 [ + + ]: 380 : if (port->gss)
298 : : {
299 : 90 : const char *princ = be_gssapi_get_princ(port);
300 : :
301 [ + + ]: 90 : if (princ)
302 [ + + + + : 117 : appendStringInfo(&logmsg,
+ - ]
1029 303 : 39 : _(" GSS (authenticated=%s, encrypted=%s, delegated_credentials=%s, principal=%s)"),
1903 304 : 78 : be_gssapi_get_auth(port) ? _("yes") : _("no"),
305 : 78 : be_gssapi_get_enc(port) ? _("yes") : _("no"),
1030 bruce@momjian.us 306 : 78 : be_gssapi_get_delegation(port) ? _("yes") : _("no"),
307 : : princ);
308 : : else
1903 tgl@sss.pgh.pa.us 309 [ - + + - : 153 : appendStringInfo(&logmsg,
- + ]
1029 310 : 51 : _(" GSS (authenticated=%s, encrypted=%s, delegated_credentials=%s)"),
1903 311 : 102 : be_gssapi_get_auth(port) ? _("yes") : _("no"),
1067 sfrost@snowman.net 312 : 102 : be_gssapi_get_enc(port) ? _("yes") : _("no"),
1030 bruce@momjian.us 313 : 102 : be_gssapi_get_delegation(port) ? _("yes") : _("no"));
314 : : }
315 : : #endif
316 : :
1929 sfrost@snowman.net 317 [ + - ]: 380 : ereport(LOG, errmsg_internal("%s", logmsg.data));
318 : 380 : pfree(logmsg.data);
319 : : }
320 : :
2195 peter@eisentraut.org 321 : 13735 : set_ps_display("startup");
322 : :
3189 tgl@sss.pgh.pa.us 323 : 13735 : ClientAuthInProgress = false; /* client_min_messages is active now */
6042 324 : 13735 : }
325 : :
326 : :
327 : : /*
328 : : * CheckMyDatabase -- fetch information from the pg_database entry for our DB
329 : : */
330 : : static void
2901 magnus@hagander.net 331 : 15418 : CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections)
332 : : {
333 : : HeapTuple tup;
334 : : Form_pg_database dbform;
335 : : Datum datum;
336 : : bool isnull;
337 : : char *collate;
338 : : char *ctype;
339 : :
340 : : /* Fetch our pg_database row normally, via syscache */
5873 rhaas@postgresql.org 341 : 15418 : tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
7255 tgl@sss.pgh.pa.us 342 [ - + ]: 15418 : if (!HeapTupleIsValid(tup))
7255 tgl@sss.pgh.pa.us 343 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
7255 tgl@sss.pgh.pa.us 344 :CBC 15418 : dbform = (Form_pg_database) GETSTRUCT(tup);
345 : :
346 : : /* This recheck is strictly paranoia */
347 [ - + ]: 15418 : if (strcmp(name, NameStr(dbform->datname)) != 0)
8269 tgl@sss.pgh.pa.us 348 [ # # ]:UBC 0 : ereport(FATAL,
349 : : (errcode(ERRCODE_UNDEFINED_DATABASE),
350 : : errmsg("database \"%s\" has disappeared from pg_database",
351 : : name),
352 : : errdetail("Database OID %u now seems to belong to \"%s\".",
353 : : MyDatabaseId, NameStr(dbform->datname))));
354 : :
355 : : /*
356 : : * Check permissions to connect to the database.
357 : : *
358 : : * These checks are not enforced when in standalone mode, so that there is
359 : : * a way to recover from disabling all access to all databases, for
360 : : * example "UPDATE pg_database SET datallowconn = false;".
361 : : */
442 tgl@sss.pgh.pa.us 362 [ + + ]:CBC 15418 : if (IsUnderPostmaster)
363 : : {
364 : : /*
365 : : * Check that the database is currently allowing connections.
366 : : * (Background processes can override this test and the next one by
367 : : * setting override_allow_connections.)
368 : : */
2901 magnus@hagander.net 369 [ + + + + ]: 15348 : if (!dbform->datallowconn && !override_allow_connections)
7532 tgl@sss.pgh.pa.us 370 [ + - ]: 1 : ereport(FATAL,
371 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
372 : : errmsg("database \"%s\" is not currently accepting connections",
373 : : name)));
374 : :
375 : : /*
376 : : * Check privilege to connect to the database. (The am_superuser test
377 : : * is redundant, but since we have the flag, might as well check it
378 : : * and save a few cycles.)
379 : : */
442 380 [ + + + + : 15761 : if (!am_superuser && !override_allow_connections &&
- + ]
1218 peter@eisentraut.org 381 : 414 : object_aclcheck(DatabaseRelationId, MyDatabaseId, GetUserId(),
382 : : ACL_CONNECT) != ACLCHECK_OK)
7259 tgl@sss.pgh.pa.us 383 [ # # ]:UBC 0 : ereport(FATAL,
384 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
385 : : errmsg("permission denied for database \"%s\"", name),
386 : : errdetail("User does not have CONNECT privilege.")));
387 : :
388 : : /*
389 : : * Check connection limit for this database. We enforce the limit
390 : : * only for regular backends, since other process types have their own
391 : : * PGPROC pools.
392 : : *
393 : : * There is a race condition here --- we create our PGPROC before
394 : : * checking for other PGPROCs. If two backends did this at about the
395 : : * same time, they might both think they were over the limit, while
396 : : * ideally one should succeed and one fail. Getting that to work
397 : : * exactly seems more trouble than it is worth, however; instead we
398 : : * just document that the connection limit is approximate.
399 : : */
7532 tgl@sss.pgh.pa.us 400 [ - + ]:CBC 15347 : if (dbform->datconnlimit >= 0 &&
442 tgl@sss.pgh.pa.us 401 [ # # ]:UBC 0 : AmRegularBackendProcess() &&
7259 402 [ # # ]: 0 : !am_superuser &&
3329 andrew@dunslane.net 403 [ # # ]: 0 : CountDBConnections(MyDatabaseId) > dbform->datconnlimit)
7532 tgl@sss.pgh.pa.us 404 [ # # ]: 0 : ereport(FATAL,
405 : : (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
406 : : errmsg("too many connections for database \"%s\"",
407 : : name)));
408 : : }
409 : :
410 : : /*
411 : : * OK, we're golden. Next to-do item is to save the encoding info out of
412 : : * the pg_database tuple.
413 : : */
9252 tgl@sss.pgh.pa.us 414 :CBC 15417 : SetDatabaseEncoding(dbform->encoding);
415 : : /* Record it as a GUC internal option, too */
8360 416 : 15417 : SetConfigOption("server_encoding", GetDatabaseEncodingName(),
417 : : PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
418 : : /* If we have no other source of client_encoding, use server encoding */
8703 419 : 15417 : SetConfigOption("client_encoding", GetDatabaseEncodingName(),
420 : : PGC_BACKEND, PGC_S_DYNAMIC_DEFAULT);
421 : :
422 : : /* assign locale variables */
1086 dgustafsson@postgres 423 : 15417 : datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datcollate);
1508 peter@eisentraut.org 424 : 15417 : collate = TextDatumGetCString(datum);
1086 dgustafsson@postgres 425 : 15417 : datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datctype);
1508 peter@eisentraut.org 426 : 15417 : ctype = TextDatumGetCString(datum);
427 : :
428 : : /*
429 : : * Historically, we set LC_COLLATE from datcollate, as well. That's no
430 : : * longer necessary because all collation behavior is handled through
431 : : * pg_locale_t.
432 : : */
433 : :
6094 heikki.linnakangas@i 434 [ - + ]: 15417 : if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
6121 bruce@momjian.us 435 [ # # ]:UBC 0 : ereport(FATAL,
436 : : (errmsg("database locale is incompatible with operating system"),
437 : : errdetail("The database was initialized with LC_CTYPE \"%s\", "
438 : : " which is not recognized by setlocale().", ctype),
439 : : errhint("Recreate the database with another locale or install the missing locale.")));
440 : :
595 jdavis@postgresql.or 441 :CBC 15417 : init_database_collation();
442 : :
443 : : /*
444 : : * Check collation version. See similar code in
445 : : * pg_newlocale_from_collation(). Note that here we warn instead of error
446 : : * in any case, so that we don't prevent connecting.
447 : : */
1490 peter@eisentraut.org 448 : 15415 : datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_datcollversion,
449 : : &isnull);
450 [ + + ]: 15415 : if (!isnull)
451 : : {
452 : : char *actual_versionstr;
453 : : char *collversionstr;
454 : : char *locale;
455 : :
456 : 920 : collversionstr = TextDatumGetCString(datum);
457 : :
732 jdavis@postgresql.or 458 [ - + ]: 920 : if (dbform->datlocprovider == COLLPROVIDER_LIBC)
732 jdavis@postgresql.or 459 :UBC 0 : locale = collate;
460 : : else
461 : : {
595 jdavis@postgresql.or 462 :CBC 920 : datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datlocale);
463 : 920 : locale = TextDatumGetCString(datum);
464 : : }
465 : :
732 466 : 920 : actual_versionstr = get_collation_actual_version(dbform->datlocprovider, locale);
1490 peter@eisentraut.org 467 [ - + ]: 920 : if (!actual_versionstr)
468 : : /* should not happen */
1285 alvherre@alvh.no-ip. 469 [ # # ]:UBC 0 : elog(WARNING,
470 : : "database \"%s\" has no actual collation version, but a version was recorded",
471 : : name);
1483 peter@eisentraut.org 472 [ - + ]:CBC 920 : else if (strcmp(actual_versionstr, collversionstr) != 0)
1490 peter@eisentraut.org 473 [ # # ]:UBC 0 : ereport(WARNING,
474 : : (errmsg("database \"%s\" has a collation version mismatch",
475 : : name),
476 : : errdetail("The database was created using collation version %s, "
477 : : "but the operating system provides version %s.",
478 : : collversionstr, actual_versionstr),
479 : : errhint("Rebuild all objects in this database that use the default collation and run "
480 : : "ALTER DATABASE %s REFRESH COLLATION VERSION, "
481 : : "or build PostgreSQL with the right library version.",
482 : : quote_identifier(name))));
483 : : }
484 : :
7255 tgl@sss.pgh.pa.us 485 :CBC 15415 : ReleaseSysCache(tup);
9669 486 : 15415 : }
487 : :
488 : :
489 : : /*
490 : : * pg_split_opts -- split a string of options and append it to an argv array
491 : : *
492 : : * The caller is responsible for ensuring the argv array is large enough. The
493 : : * maximum possible number of arguments added by this routine is
494 : : * (strlen(optstr) + 1) / 2.
495 : : *
496 : : * Because some option values can contain spaces we allow escaping using
497 : : * backslashes, with \\ representing a literal backslash.
498 : : */
499 : : void
3912 500 : 3787 : pg_split_opts(char **argv, int *argcp, const char *optstr)
501 : : {
502 : : StringInfoData s;
503 : :
4217 andres@anarazel.de 504 : 3787 : initStringInfo(&s);
505 : :
6042 tgl@sss.pgh.pa.us 506 [ + + ]: 14105 : while (*optstr)
507 : : {
4201 508 : 10318 : bool last_was_escape = false;
509 : :
4217 andres@anarazel.de 510 : 10318 : resetStringInfo(&s);
511 : :
512 : : /* skip over leading space */
6042 tgl@sss.pgh.pa.us 513 [ + + ]: 19709 : while (isspace((unsigned char) *optstr))
514 : 9391 : optstr++;
515 : :
516 [ - + ]: 10318 : if (*optstr == '\0')
6042 tgl@sss.pgh.pa.us 517 :UBC 0 : break;
518 : :
519 : : /*
520 : : * Parse a single option, stopping at the first space, unless it's
521 : : * escaped.
522 : : */
4217 andres@anarazel.de 523 [ + + ]:CBC 156207 : while (*optstr)
524 : : {
4213 tgl@sss.pgh.pa.us 525 [ + + + + ]: 152420 : if (isspace((unsigned char) *optstr) && !last_was_escape)
4217 andres@anarazel.de 526 : 6531 : break;
527 : :
528 [ + + + + ]: 145889 : if (!last_was_escape && *optstr == '\\')
529 : 20 : last_was_escape = true;
530 : : else
531 : : {
532 : 145869 : last_was_escape = false;
533 : 145869 : appendStringInfoChar(&s, *optstr);
534 : : }
535 : :
6042 tgl@sss.pgh.pa.us 536 : 145889 : optstr++;
537 : : }
538 : :
539 : : /* now store the option in the next argv[] position */
4217 andres@anarazel.de 540 : 10318 : argv[(*argcp)++] = pstrdup(s.data);
541 : : }
542 : :
3912 tgl@sss.pgh.pa.us 543 : 3787 : pfree(s.data);
6042 544 : 3787 : }
545 : :
546 : : /*
547 : : * Initialize MaxBackends value from config options.
548 : : *
549 : : * This must be called after modules have had the chance to alter GUCs in
550 : : * shared_preload_libraries and before shared memory size is determined.
551 : : *
552 : : * Note that in EXEC_BACKEND environment, the value is passed down from
553 : : * postmaster to subprocesses via BackendParameters in SubPostmasterMain; only
554 : : * postmaster itself and processes not under postmaster control should call
555 : : * this.
556 : : */
557 : : void
4820 alvherre@alvh.no-ip. 558 : 1148 : InitializeMaxBackends(void)
559 : : {
1433 rhaas@postgresql.org 560 [ - + ]: 1148 : Assert(MaxBackends == 0);
561 : :
562 : : /* Note that this does not include "auxiliary" processes */
433 nathan@postgresql.or 563 : 1148 : MaxBackends = MaxConnections + autovacuum_worker_slots +
442 tgl@sss.pgh.pa.us 564 : 1148 : max_worker_processes + max_wal_senders + NUM_SPECIAL_WORKER_PROCS;
565 : :
1433 rhaas@postgresql.org 566 [ - + ]: 1148 : if (MaxBackends > MAX_BACKENDS)
618 nathan@postgresql.or 567 [ # # ]:UBC 0 : ereport(ERROR,
568 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
569 : : errmsg("too many server processes configured"),
570 : : errdetail("\"max_connections\" (%d) plus \"autovacuum_worker_slots\" (%d) plus \"max_worker_processes\" (%d) plus \"max_wal_senders\" (%d) must be less than %d.",
571 : : MaxConnections, autovacuum_worker_slots,
572 : : max_worker_processes, max_wal_senders,
573 : : MAX_BACKENDS - (NUM_SPECIAL_WORKER_PROCS - 1))));
1279 tgl@sss.pgh.pa.us 574 :CBC 1148 : }
575 : :
576 : : /*
577 : : * Initialize the number of fast-path lock slots in PGPROC.
578 : : *
579 : : * This must be called after modules have had the chance to alter GUCs in
580 : : * shared_preload_libraries and before shared memory size is determined.
581 : : */
582 : : void
540 tomas.vondra@postgre 583 : 1148 : InitializeFastPathLocks(void)
584 : : {
585 : : /* Should be initialized only once. */
586 [ - + ]: 1148 : Assert(FastPathLockGroupsPerBackend == 0);
587 : :
588 : : /*
589 : : * Based on the max_locks_per_transaction GUC, as that's a good indicator
590 : : * of the expected number of locks, figure out the value for
591 : : * FastPathLockGroupsPerBackend. This must be a power-of-two. We cap the
592 : : * value at FP_LOCK_GROUPS_PER_BACKEND_MAX and insist the value is at
593 : : * least 1.
594 : : *
595 : : * The default max_locks_per_transaction = 64 means 4 groups by default.
596 : : */
322 drowley@postgresql.o 597 : 1148 : FastPathLockGroupsPerBackend =
598 [ + - + - : 1148 : Max(Min(pg_nextpower2_32(max_locks_per_xact) / FP_LOCK_SLOTS_PER_GROUP,
+ - ]
599 : : FP_LOCK_GROUPS_PER_BACKEND_MAX), 1);
600 : :
601 : : /* Validate we did get a power-of-two */
602 [ - + ]: 1148 : Assert(FastPathLockGroupsPerBackend ==
603 : : pg_nextpower2_32(FastPathLockGroupsPerBackend));
540 tomas.vondra@postgre 604 : 1148 : }
605 : :
606 : : /*
607 : : * Early initialization of a backend (either standalone or under postmaster).
608 : : * This happens even before InitPostgres.
609 : : *
610 : : * This is separate from InitPostgres because it is also called by auxiliary
611 : : * processes, such as the background writer process, which may not call
612 : : * InitPostgres at all.
613 : : */
614 : : void
9218 tgl@sss.pgh.pa.us 615 : 21646 : BaseInit(void)
616 : : {
1683 andres@anarazel.de 617 [ - + ]: 21646 : Assert(MyProc != NULL);
618 : :
619 : : /*
620 : : * Initialize our input/output/debugging file descriptors.
621 : : */
9218 tgl@sss.pgh.pa.us 622 : 21646 : DebugFileOpen();
623 : :
624 : : /*
625 : : * Initialize file access. Done early so other subsystems can access
626 : : * files.
627 : : */
1681 andres@anarazel.de 628 : 21646 : InitFileAccess();
629 : :
630 : : /*
631 : : * Initialize statistics reporting. This needs to happen early to ensure
632 : : * that pgstat's shutdown callback runs after the shutdown callbacks of
633 : : * all subsystems that can produce stats (like e.g. transaction commits
634 : : * can).
635 : : */
1682 636 : 21646 : pgstat_initialize();
637 : :
638 : : /*
639 : : * Initialize AIO before infrastructure that might need to actually
640 : : * execute AIO.
641 : : */
363 642 : 21646 : pgaio_init_backend();
643 : :
644 : : /* Do local initialization of storage and buffer managers */
2537 tmunro@postgresql.or 645 : 21646 : InitSync();
9218 tgl@sss.pgh.pa.us 646 : 21646 : smgrinit();
563 heikki.linnakangas@i 647 : 21646 : InitBufferManagerAccess();
648 : :
649 : : /*
650 : : * Initialize temporary file access after pgstat, so that the temporary
651 : : * file shutdown hook can report temporary file statistics.
652 : : */
1681 andres@anarazel.de 653 : 21646 : InitTemporaryFileAccess();
654 : :
655 : : /*
656 : : * Initialize local buffers for WAL record construction, in case we ever
657 : : * try to insert XLOG.
658 : : */
1580 rhaas@postgresql.org 659 : 21646 : InitXLogInsert();
660 : :
661 : : /* Initialize lock manager's local structs */
563 heikki.linnakangas@i 662 : 21646 : InitLockManagerAccess();
663 : :
664 : : /* Initialize logical info WAL logging state */
82 msawada@postgresql.o 665 :GNC 21646 : InitializeProcessXLogLogicalInfo();
666 : :
667 : : /*
668 : : * Initialize replication slots after pgstat. The exit hook might need to
669 : : * drop ephemeral slots, which in turn triggers stats reporting.
670 : : */
1490 andres@anarazel.de 671 :CBC 21646 : ReplicationSlotInitialize();
9218 tgl@sss.pgh.pa.us 672 : 21646 : }
673 : :
674 : :
675 : : /* --------------------------------
676 : : * InitPostgres
677 : : * Initialize POSTGRES.
678 : : *
679 : : * Parameters:
680 : : * in_dbname, dboid: specify database to connect to, as described below
681 : : * username, useroid: specify role to connect as, as described below
682 : : * flags:
683 : : * - INIT_PG_LOAD_SESSION_LIBS to honor [session|local]_preload_libraries.
684 : : * - INIT_PG_OVERRIDE_ALLOW_CONNS to connect despite !datallowconn.
685 : : * - INIT_PG_OVERRIDE_ROLE_LOGIN to connect despite !rolcanlogin.
686 : : * out_dbname: optional output parameter, see below; pass NULL if not used
687 : : *
688 : : * The database can be specified by name, using the in_dbname parameter, or by
689 : : * OID, using the dboid parameter. Specify NULL or InvalidOid respectively
690 : : * for the unused parameter. If dboid is provided, the actual database
691 : : * name can be returned to the caller in out_dbname. If out_dbname isn't
692 : : * NULL, it must point to a buffer of size NAMEDATALEN.
693 : : *
694 : : * Similarly, the role can be passed by name, using the username parameter,
695 : : * or by OID using the useroid parameter.
696 : : *
697 : : * In bootstrap mode the database and username parameters are NULL/InvalidOid.
698 : : * The autovacuum launcher process doesn't specify these parameters either,
699 : : * because it only goes far enough to be able to read pg_database; it doesn't
700 : : * connect to any particular database. An autovacuum worker specifies a
701 : : * database but not a username; conversely, a physical walsender specifies
702 : : * username but not database.
703 : : *
704 : : * By convention, INIT_PG_LOAD_SESSION_LIBS should be passed in "flags" in
705 : : * "interactive" sessions (including standalone backends), but not in
706 : : * background processes such as autovacuum. Note in particular that it
707 : : * shouldn't be true in parallel worker processes; those have another
708 : : * mechanism for replicating their leader's set of loaded libraries.
709 : : *
710 : : * We expect that InitProcess() was already called, so we already have a
711 : : * PGPROC struct ... but it's not completely filled in yet.
712 : : *
713 : : * Note:
714 : : * Be very careful with the order of calls in the InitPostgres function.
715 : : * --------------------------------
716 : : */
717 : : void
1329 718 : 17056 : InitPostgres(const char *in_dbname, Oid dboid,
719 : : const char *username, Oid useroid,
720 : : bits32 flags,
721 : : char *out_dbname)
722 : : {
9558 peter_e@gmx.net 723 : 17056 : bool bootstrap = IsBootstrapProcessingMode();
724 : : bool am_superuser;
725 : : char *fullpath;
726 : : char dbname[NAMEDATALEN];
1150 rhaas@postgresql.org 727 : 17056 : int nfree = 0;
728 : :
6042 tgl@sss.pgh.pa.us 729 [ + + ]: 17056 : elog(DEBUG3, "InitPostgres");
730 : :
731 : : /*
732 : : * Add my PGPROC struct to the ProcArray.
733 : : *
734 : : * Once I have done this, I am visible to other backends!
735 : : */
7375 736 : 17056 : InitProcessPhase2();
737 : :
738 : : /* Initialize status reporting */
376 michael@paquier.xyz 739 : 17056 : pgstat_beinit();
740 : :
741 : : /*
742 : : * And initialize an entry in the PgBackendStatus array. That way, if
743 : : * LWLocks or third-party authentication should happen to hang, it is
744 : : * possible to retrieve some information about what is going on.
745 : : */
746 [ + + ]: 17056 : if (!bootstrap)
747 : : {
748 : 17005 : pgstat_bestart_initial();
309 749 : 17005 : INJECTION_POINT("init-pre-auth", NULL);
750 : : }
751 : :
752 : : /*
753 : : * Initialize my entry in the shared-invalidation manager's array of
754 : : * per-backend data.
755 : : */
5930 simon@2ndQuadrant.co 756 : 17056 : SharedInvalBackendInit(false);
757 : :
347 heikki.linnakangas@i 758 : 17056 : ProcSignalInit(MyCancelKey, MyCancelKeyLength);
759 : :
760 : : /*
761 : : * Also set up timeout handlers needed for backend operation. We need
762 : : * these in every case except bootstrap.
763 : : */
4990 alvherre@alvh.no-ip. 764 [ + + ]: 17056 : if (!bootstrap)
765 : : {
4058 andres@anarazel.de 766 : 17005 : RegisterTimeout(DEADLOCK_TIMEOUT, CheckDeadLockAlert);
4990 alvherre@alvh.no-ip. 767 : 17005 : RegisterTimeout(STATEMENT_TIMEOUT, StatementTimeoutHandler);
4747 tgl@sss.pgh.pa.us 768 : 17005 : RegisterTimeout(LOCK_TIMEOUT, LockTimeoutHandler);
3651 rhaas@postgresql.org 769 : 17005 : RegisterTimeout(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
770 : : IdleInTransactionSessionTimeoutHandler);
759 akorotkov@postgresql 771 : 17005 : RegisterTimeout(TRANSACTION_TIMEOUT, TransactionTimeoutHandler);
1894 tgl@sss.pgh.pa.us 772 : 17005 : RegisterTimeout(IDLE_SESSION_TIMEOUT, IdleSessionTimeoutHandler);
1807 tmunro@postgresql.or 773 : 17005 : RegisterTimeout(CLIENT_CONNECTION_CHECK_TIMEOUT, ClientCheckTimeoutHandler);
1439 andres@anarazel.de 774 : 17005 : RegisterTimeout(IDLE_STATS_UPDATE_TIMEOUT,
775 : : IdleStatsUpdateTimeoutHandler);
776 : : }
777 : :
778 : : /*
779 : : * If this is either a bootstrap process or a standalone backend, start up
780 : : * the XLOG machinery, and register to have it closed down at exit. In
781 : : * other cases, the startup process is responsible for starting up the
782 : : * XLOG machinery, and the checkpointer for closing it down.
783 : : */
1553 rhaas@postgresql.org 784 [ + + ]: 17056 : if (!IsUnderPostmaster)
785 : : {
786 : : /*
787 : : * We don't yet have an aux-process resource owner, but StartupXLOG
788 : : * and ShutdownXLOG will need one. Hence, create said resource owner
789 : : * (and register a callback to clean it up after ShutdownXLOG runs).
790 : : */
2797 tgl@sss.pgh.pa.us 791 : 121 : CreateAuxProcessResourceOwner();
792 : :
5808 793 : 121 : StartupXLOG();
794 : : /* Release (and warn about) any buffer pins leaked in StartupXLOG */
2797 795 : 121 : ReleaseAuxProcessResources(true);
796 : : /* Reset CurrentResourceOwner to nothing for the moment */
797 : 121 : CurrentResourceOwner = NULL;
798 : :
799 : : /*
800 : : * Use before_shmem_exit() so that ShutdownXLOG() can rely on DSM
801 : : * segments etc to work (which in turn is required for pgstats).
802 : : */
1439 andres@anarazel.de 803 : 121 : before_shmem_exit(pgstat_before_server_shutdown, 0);
1815 804 : 121 : before_shmem_exit(ShutdownXLOG, 0);
805 : : }
806 : :
807 : : /*
808 : : * Initialize the relation cache and the system catalog caches. Note that
809 : : * no catalog access happens here; we only set up the hashtable structure.
810 : : * We must do this before starting a transaction because transaction abort
811 : : * would try to touch these hashtables.
812 : : */
8968 tgl@sss.pgh.pa.us 813 : 17056 : RelationCacheInitialize();
10416 bruce@momjian.us 814 : 17056 : InitCatalogCache();
6942 tgl@sss.pgh.pa.us 815 : 17056 : InitPlanCache();
816 : :
817 : : /* Initialize portal manager */
9038 818 : 17056 : EnablePortalManager();
819 : :
820 : : /*
821 : : * Load relcache entries for the shared system catalogs. This must create
822 : : * at least entries for pg_database and catalogs used for authentication.
823 : : */
6040 824 : 17056 : RelationCacheInitializePhase2();
825 : :
826 : : /*
827 : : * Set up process-exit callback to do pre-shutdown cleanup. This is one
828 : : * of the first before_shmem_exit callbacks we register; thus, this will
829 : : * be one of the last things we do before low-level modules like the
830 : : * buffer manager begin to close down. We need to have this in place
831 : : * before we begin our first transaction --- if we fail during the
832 : : * initialization transaction, as is entirely possible, we need the
833 : : * AbortTransaction call to clean up.
834 : : */
4470 rhaas@postgresql.org 835 : 17056 : before_shmem_exit(ShutdownPostgres, 0);
836 : :
837 : : /* The autovacuum launcher is done here */
741 heikki.linnakangas@i 838 [ + + ]: 17056 : if (AmAutoVacuumLauncherProcess())
839 : : {
840 : : /* fill in the remainder of this entry in the PgBackendStatus array */
376 michael@paquier.xyz 841 : 428 : pgstat_bestart_final();
842 : :
6039 tgl@sss.pgh.pa.us 843 : 1376 : return;
844 : : }
845 : :
846 : : /*
847 : : * Start a new transaction here before first access to db.
848 : : */
9580 inoue@tpf.co.jp 849 [ + + ]: 16628 : if (!bootstrap)
850 : : {
851 : : /* statement_timestamp must be set for timeouts to work correctly */
5328 tgl@sss.pgh.pa.us 852 : 16577 : SetCurrentStatementStartTimestamp();
8341 853 : 16577 : StartTransactionCommand();
854 : :
855 : : /*
856 : : * transaction_isolation will have been set to the default by the
857 : : * above. If the default is "serializable", and we are in hot
858 : : * standby, we will fail if we don't change it to something lower.
859 : : * Fortunately, "read committed" is plenty good enough.
860 : : */
4951 861 : 16577 : XactIsoLevel = XACT_READ_COMMITTED;
862 : : }
863 : :
864 : : /*
865 : : * Perform client authentication if necessary, then figure out our
866 : : * postgres user ID, and see if we are a superuser.
867 : : *
868 : : * In standalone mode, autovacuum worker processes and slot sync worker
869 : : * process, we use a fixed ID, otherwise we figure it out from the
870 : : * authenticated user name.
871 : : */
741 heikki.linnakangas@i 872 [ + + + + : 16628 : if (bootstrap || AmAutoVacuumWorkerProcess() || AmLogicalSlotSyncWorkerProcess())
+ + ]
873 : : {
5808 tgl@sss.pgh.pa.us 874 : 94 : InitializeSessionUserIdStandalone();
875 : 94 : am_superuser = true;
876 : : }
877 [ + + ]: 16534 : else if (!IsUnderPostmaster)
878 : : {
879 : 70 : InitializeSessionUserIdStandalone();
880 : 70 : am_superuser = true;
881 [ - + ]: 70 : if (!ThereIsAtLeastOneRole())
5808 tgl@sss.pgh.pa.us 882 [ # # # # ]:UBC 0 : ereport(WARNING,
883 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
884 : : errmsg("no roles are defined in this database system"),
885 : : errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
886 : : username != NULL ? username : "postgres")));
887 : : }
741 heikki.linnakangas@i 888 [ + + ]:CBC 16464 : else if (AmBackgroundWorkerProcess())
889 : : {
4059 rhaas@postgresql.org 890 [ + - + + ]: 2538 : if (username == NULL && !OidIsValid(useroid))
891 : : {
4847 alvherre@alvh.no-ip. 892 : 466 : InitializeSessionUserIdStandalone();
893 : 466 : am_superuser = true;
894 : : }
895 : : else
896 : : {
885 michael@paquier.xyz 897 : 2072 : InitializeSessionUserId(username, useroid,
898 : 2072 : (flags & INIT_PG_OVERRIDE_ROLE_LOGIN) != 0);
442 tgl@sss.pgh.pa.us 899 : 2071 : am_superuser = superuser();
900 : : }
901 : : }
902 : : else
903 : : {
904 : : /* normal multiuser case */
5808 905 [ - + ]: 13926 : Assert(MyProcPort != NULL);
906 : 13926 : PerformAuthentication(MyProcPort);
885 michael@paquier.xyz 907 : 13735 : InitializeSessionUserId(username, useroid, false);
908 : : /* ensure that auth_method is actually valid, aka authn_id is not NULL */
1263 909 [ + + ]: 13731 : if (MyClientConnectionInfo.authn_id)
910 : 179 : InitializeSystemUser(MyClientConnectionInfo.authn_id,
911 : : hba_authname(MyClientConnectionInfo.auth_method));
5808 tgl@sss.pgh.pa.us 912 : 13731 : am_superuser = superuser();
913 : : }
914 : :
915 : : /* Report any SSL/GSS details for the session. */
376 michael@paquier.xyz 916 [ + + ]: 16432 : if (MyProcPort != NULL)
917 : : {
918 [ - + ]: 13731 : Assert(!bootstrap);
919 : :
920 : 13731 : pgstat_bestart_security();
921 : : }
922 : :
923 : : /*
924 : : * Binary upgrades only allowed super-user connections
925 : : */
5438 bruce@momjian.us 926 [ + + - + ]: 16432 : if (IsBinaryUpgrade && !am_superuser)
927 : : {
5393 bruce@momjian.us 928 [ # # ]:UBC 0 : ereport(FATAL,
929 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
930 : : errmsg("must be superuser to connect in binary upgrade mode")));
931 : : }
932 : :
933 : : /*
934 : : * The last few regular connection slots are reserved for superusers and
935 : : * roles with privileges of pg_use_reserved_connections. We do not apply
936 : : * these limits to background processes, since they all have their own
937 : : * pools of PGPROC slots.
938 : : *
939 : : * Note: At this point, the new backend has already claimed a proc struct,
940 : : * so we must check whether the number of free slots is strictly less than
941 : : * the reserved connection limits.
942 : : */
442 tgl@sss.pgh.pa.us 943 [ + + + + ]:CBC 16432 : if (AmRegularBackendProcess() && !am_superuser &&
1150 rhaas@postgresql.org 944 [ + - ]: 383 : (SuperuserReservedConnections + ReservedConnections) > 0 &&
945 [ + + ]: 383 : !HaveNFreeProcs(SuperuserReservedConnections + ReservedConnections, &nfree))
946 : : {
947 [ + + ]: 4 : if (nfree < SuperuserReservedConnections)
948 [ + - ]: 1 : ereport(FATAL,
949 : : (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
950 : : errmsg("remaining connection slots are reserved for roles with the %s attribute",
951 : : "SUPERUSER")));
952 : :
953 [ + + ]: 3 : if (!has_privs_of_role(GetUserId(), ROLE_PG_USE_RESERVED_CONNECTIONS))
954 [ + - ]: 1 : ereport(FATAL,
955 : : (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
956 : : errmsg("remaining connection slots are reserved for roles with privileges of the \"%s\" role",
957 : : "pg_use_reserved_connections")));
958 : : }
959 : :
960 : : /* Check replication permissions needed for walsender processes. */
5808 tgl@sss.pgh.pa.us 961 [ + + ]: 16430 : if (am_walsender)
962 : : {
963 [ - + ]: 1253 : Assert(!bootstrap);
964 : :
1095 peter@eisentraut.org 965 [ - + ]: 1253 : if (!has_rolreplication(GetUserId()))
5807 tgl@sss.pgh.pa.us 966 [ # # ]:UBC 0 : ereport(FATAL,
967 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
968 : : errmsg("permission denied to start WAL sender"),
969 : : errdetail("Only roles with the %s attribute may start a WAL sender process.",
970 : : "REPLICATION")));
971 : : }
972 : :
973 : : /*
974 : : * If this is a plain walsender only supporting physical replication, we
975 : : * don't want to connect to any particular database. Just finish the
976 : : * backend startup by processing any options from the startup packet, and
977 : : * we're done.
978 : : */
4388 rhaas@postgresql.org 979 [ + + + + ]:CBC 16430 : if (am_walsender && !am_db_walsender)
980 : : {
981 : : /* process any options passed in the startup packet */
5662 heikki.linnakangas@i 982 [ + - ]: 489 : if (MyProcPort != NULL)
983 : 489 : process_startup_options(MyProcPort, am_superuser);
984 : :
985 : : /* Apply PostAuthDelay as soon as we've read all options */
986 [ - + ]: 489 : if (PostAuthDelay > 0)
5662 heikki.linnakangas@i 987 :UBC 0 : pg_usleep(PostAuthDelay * 1000000L);
988 : :
989 : : /* initialize client encoding */
5662 heikki.linnakangas@i 990 :CBC 489 : InitializeClientEncoding();
991 : :
992 : : /* fill in the remainder of this entry in the PgBackendStatus array */
376 michael@paquier.xyz 993 : 489 : pgstat_bestart_final();
994 : :
995 : : /* close the transaction we started above */
5808 tgl@sss.pgh.pa.us 996 : 489 : CommitTransactionCommand();
997 : :
998 : : /* send any WARNINGs we've accumulated during initialization */
32 nathan@postgresql.or 999 :GNC 489 : EmitConnectionWarnings();
1000 : :
5808 tgl@sss.pgh.pa.us 1001 :CBC 489 : return;
1002 : : }
1003 : :
1004 : : /*
1005 : : * Set up the global variables holding database id and default tablespace.
1006 : : * But note we won't actually try to touch the database just yet.
1007 : : *
1008 : : * We take a shortcut in the bootstrap case, otherwise we have to look up
1009 : : * the db's entry in pg_database.
1010 : : */
1011 [ + + ]: 15941 : if (bootstrap)
1012 : : {
923 michael@paquier.xyz 1013 : 51 : dboid = Template1DbOid;
6059 tgl@sss.pgh.pa.us 1014 : 51 : MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
1015 : : }
1016 [ + + ]: 15890 : else if (in_dbname != NULL)
1017 : : {
1018 : : HeapTuple tuple;
1019 : : Form_pg_database dbform;
1020 : :
1021 : 13315 : tuple = GetDatabaseTuple(in_dbname);
1022 [ + + ]: 13315 : if (!HeapTupleIsValid(tuple))
1023 [ + - ]: 6 : ereport(FATAL,
1024 : : (errcode(ERRCODE_UNDEFINED_DATABASE),
1025 : : errmsg("database \"%s\" does not exist", in_dbname)));
1026 : 13309 : dbform = (Form_pg_database) GETSTRUCT(tuple);
923 michael@paquier.xyz 1027 : 13309 : dboid = dbform->oid;
1028 : : }
1029 [ + + ]: 2575 : else if (!OidIsValid(dboid))
1030 : : {
1031 : : /*
1032 : : * If this is a background worker not bound to any particular
1033 : : * database, we're done now. Everything that follows only makes sense
1034 : : * if we are bound to a specific database. We do need to close the
1035 : : * transaction we started before returning.
1036 : : */
3916 rhaas@postgresql.org 1037 [ + - ]: 459 : if (!bootstrap)
1038 : : {
376 michael@paquier.xyz 1039 : 459 : pgstat_bestart_final();
3916 rhaas@postgresql.org 1040 : 459 : CommitTransactionCommand();
1041 : : }
1042 : 459 : return;
1043 : : }
1044 : :
1045 : : /*
1046 : : * Now, take a writer's lock on the database we are trying to connect to.
1047 : : * If there is a concurrently running DROP DATABASE on that database, this
1048 : : * will block us until it finishes (and has committed its update of
1049 : : * pg_database).
1050 : : *
1051 : : * Note that the lock is not held long, only until the end of this startup
1052 : : * transaction. This is OK since we will advertise our use of the
1053 : : * database in the ProcArray before dropping the lock (in fact, that's the
1054 : : * next thing to do). Anyone trying a DROP DATABASE after this point will
1055 : : * see us in the array once they have the lock. Ordering is important for
1056 : : * this because we don't want to advertise ourselves as being in this
1057 : : * database until we have the lock; otherwise we create what amounts to a
1058 : : * deadlock with CountOtherDBBackends().
1059 : : *
1060 : : * Note: use of RowExclusiveLock here is reasonable because we envision
1061 : : * our session as being a concurrent writer of the database. If we had a
1062 : : * way of declaring a session as being guaranteed-read-only, we could use
1063 : : * AccessShareLock for such sessions and thereby not conflict against
1064 : : * CREATE DATABASE.
1065 : : */
5808 tgl@sss.pgh.pa.us 1066 [ + + ]: 15476 : if (!bootstrap)
923 michael@paquier.xyz 1067 : 15425 : LockSharedObject(DatabaseRelationId, dboid, 0, RowExclusiveLock);
1068 : :
1069 : : /*
1070 : : * Recheck pg_database to make sure the target database hasn't gone away.
1071 : : * If there was a concurrent DROP DATABASE, this ensures we will die
1072 : : * cleanly without creating a mess.
1073 : : */
1074 [ + + ]: 15476 : if (!bootstrap)
1075 : : {
1076 : : HeapTuple tuple;
1077 : : Form_pg_database datform;
1078 : :
1079 : 15425 : tuple = GetDatabaseTupleByOid(dboid);
1080 [ + - ]: 15425 : if (HeapTupleIsValid(tuple))
1081 : 15425 : datform = (Form_pg_database) GETSTRUCT(tuple);
1082 : :
1083 [ + - + + ]: 15425 : if (!HeapTupleIsValid(tuple) ||
1084 [ - + ]: 13309 : (in_dbname && namestrcmp(&datform->datname, in_dbname)))
1085 : : {
923 michael@paquier.xyz 1086 [ # # ]:UBC 0 : if (in_dbname)
1087 [ # # ]: 0 : ereport(FATAL,
1088 : : (errcode(ERRCODE_UNDEFINED_DATABASE),
1089 : : errmsg("database \"%s\" does not exist", in_dbname),
1090 : : errdetail("It seems to have just been dropped or renamed.")));
1091 : : else
1092 [ # # ]: 0 : ereport(FATAL,
1093 : : (errcode(ERRCODE_UNDEFINED_DATABASE),
1094 : : errmsg("database %u does not exist", dboid)));
1095 : : }
1096 : :
923 michael@paquier.xyz 1097 :CBC 15425 : strlcpy(dbname, NameStr(datform->datname), sizeof(dbname));
1098 : :
1099 [ + + ]: 15425 : if (database_is_invalid_form(datform))
1100 : : {
1101 [ + - ]: 4 : ereport(FATAL,
1102 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1103 : : errmsg("cannot connect to invalid database \"%s\"", dbname),
1104 : : errhint("Use DROP DATABASE to drop invalid databases."));
1105 : : }
1106 : :
1107 : 15421 : MyDatabaseTableSpace = datform->dattablespace;
881 akorotkov@postgresql 1108 : 15421 : MyDatabaseHasLoginEventTriggers = datform->dathasloginevt;
1109 : : /* pass the database name back to the caller */
923 michael@paquier.xyz 1110 [ + + ]: 15421 : if (out_dbname)
1111 : 38 : strcpy(out_dbname, dbname);
1112 : : }
1113 : :
1114 : : /*
1115 : : * Now that we rechecked, we are certain to be connected to a database and
1116 : : * thus can set MyDatabaseId.
1117 : : *
1118 : : * It is important that MyDatabaseId only be set once we are sure that the
1119 : : * target database can no longer be concurrently dropped or renamed. For
1120 : : * example, without this guarantee, pgstat_update_dbstats() could create
1121 : : * entries for databases that were just dropped in the pgstat shutdown
1122 : : * callback, which could confuse other code paths like the autovacuum
1123 : : * scheduler.
1124 : : */
1125 : 15472 : MyDatabaseId = dboid;
1126 : :
1127 : : /*
1128 : : * Now we can mark our PGPROC entry with the database ID.
1129 : : *
1130 : : * We assume this is an atomic store so no lock is needed; though actually
1131 : : * things would work fine even if it weren't atomic. Anyone searching the
1132 : : * ProcArray for this database's ID should hold the database lock, so they
1133 : : * would not be executing concurrently with this store. A process looking
1134 : : * for another database's ID could in theory see a chance match if it read
1135 : : * a partially-updated databaseId value; but as long as all such searches
1136 : : * wait and retry, as in CountOtherDBBackends(), they will certainly see
1137 : : * the correct value on their next try.
1138 : : */
3936 tgl@sss.pgh.pa.us 1139 : 15472 : MyProc->databaseId = MyDatabaseId;
1140 : :
1141 : : /*
1142 : : * We established a catalog snapshot while reading pg_authid and/or
1143 : : * pg_database; but until we have set up MyDatabaseId, we won't react to
1144 : : * incoming sinval messages for unshared catalogs, so we won't realize it
1145 : : * if the snapshot has been invalidated. Assume it's no good anymore.
1146 : : */
1147 : 15472 : InvalidateCatalogSnapshot();
1148 : :
1149 : : /*
1150 : : * Now we should be able to access the database directory safely. Verify
1151 : : * it's there and looks reasonable.
1152 : : */
6059 1153 : 15472 : fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
1154 : :
5808 1155 [ + + ]: 15472 : if (!bootstrap)
1156 : : {
7255 1157 [ - + ]: 15421 : if (access(fullpath, F_OK) == -1)
1158 : : {
7255 tgl@sss.pgh.pa.us 1159 [ # # ]:UBC 0 : if (errno == ENOENT)
1160 [ # # ]: 0 : ereport(FATAL,
1161 : : (errcode(ERRCODE_UNDEFINED_DATABASE),
1162 : : errmsg("database \"%s\" does not exist",
1163 : : dbname),
1164 : : errdetail("The database subdirectory \"%s\" is missing.",
1165 : : fullpath)));
1166 : : else
1167 [ # # ]: 0 : ereport(FATAL,
1168 : : (errcode_for_file_access(),
1169 : : errmsg("could not access directory \"%s\": %m",
1170 : : fullpath)));
1171 : : }
1172 : :
7255 tgl@sss.pgh.pa.us 1173 :CBC 15421 : ValidatePgVersion(fullpath);
1174 : : }
1175 : :
6059 1176 : 15472 : SetDatabasePath(fullpath);
1420 alvherre@alvh.no-ip. 1177 : 15472 : pfree(fullpath);
1178 : :
1179 : : /*
1180 : : * It's now possible to do real access to the system catalogs.
1181 : : *
1182 : : * Load relcache entries for the system catalogs. This must create at
1183 : : * least the minimum set of "nailed-in" cache entries.
1184 : : */
6059 tgl@sss.pgh.pa.us 1185 : 15472 : RelationCacheInitializePhase3();
1186 : :
1187 : : /* set up ACL framework (so CheckMyDatabase can check permissions) */
7259 1188 : 15469 : initialize_acl();
1189 : :
1190 : : /*
1191 : : * Re-read the pg_database row for our database, check permissions and set
1192 : : * up database-specific GUC settings. We can't do this until all the
1193 : : * database-access infrastructure is up. (Also, it wants to know if the
1194 : : * user is a superuser, so the above stuff has to happen first.)
1195 : : */
5808 1196 [ + + ]: 15469 : if (!bootstrap)
886 michael@paquier.xyz 1197 : 15418 : CheckMyDatabase(dbname, am_superuser,
1198 : 15418 : (flags & INIT_PG_OVERRIDE_ALLOW_CONNS) != 0);
1199 : :
1200 : : /*
1201 : : * Now process any command-line switches and any additional GUC variable
1202 : : * settings passed in the startup packet. We couldn't do this before
1203 : : * because we didn't know if client is a superuser.
1204 : : */
5662 heikki.linnakangas@i 1205 [ + + ]: 15466 : if (MyProcPort != NULL)
1206 : 13230 : process_startup_options(MyProcPort, am_superuser);
1207 : :
1208 : : /* Process pg_db_role_setting options */
1209 : 15466 : process_settings(MyDatabaseId, GetSessionUserId());
1210 : :
1211 : : /* Apply PostAuthDelay as soon as we've read all options */
1212 [ - + ]: 15466 : if (PostAuthDelay > 0)
5662 heikki.linnakangas@i 1213 :UBC 0 : pg_usleep(PostAuthDelay * 1000000L);
1214 : :
1215 : : /*
1216 : : * Initialize various default states that can't be set up until we've
1217 : : * selected the active user and gotten the right GUC settings.
1218 : : */
1219 : :
1220 : : /* set default namespace search path */
5662 heikki.linnakangas@i 1221 :CBC 15466 : InitializeSearchPath();
1222 : :
1223 : : /* initialize client encoding */
1224 : 15466 : InitializeClientEncoding();
1225 : :
1226 : : /* Initialize this backend's session state. */
3104 andres@anarazel.de 1227 : 15466 : InitializeSession();
1228 : :
1229 : : /*
1230 : : * If this is an interactive session, load any libraries that should be
1231 : : * preloaded at backend start. Since those are determined by GUCs, this
1232 : : * can't happen until GUC settings are complete, but we want it to happen
1233 : : * during the initial transaction in case anything that requires database
1234 : : * access needs to be done.
1235 : : */
886 michael@paquier.xyz 1236 [ + + ]: 15466 : if ((flags & INIT_PG_LOAD_SESSION_LIBS) != 0)
1329 tgl@sss.pgh.pa.us 1237 : 12534 : process_session_preload_libraries();
1238 : :
1239 : : /* fill in the remainder of this entry in the PgBackendStatus array */
5662 heikki.linnakangas@i 1240 [ + + ]: 15466 : if (!bootstrap)
376 michael@paquier.xyz 1241 : 15415 : pgstat_bestart_final();
1242 : :
1243 : : /* close the transaction we started above */
5662 heikki.linnakangas@i 1244 [ + + ]: 15466 : if (!bootstrap)
1245 : 15415 : CommitTransactionCommand();
1246 : :
1247 : : /* send any WARNINGs we've accumulated during initialization */
32 nathan@postgresql.or 1248 :GNC 15466 : EmitConnectionWarnings();
1249 : : }
1250 : :
1251 : : /*
1252 : : * Process any command-line switches and any additional GUC variable
1253 : : * settings passed in the startup packet.
1254 : : */
1255 : : static void
5662 heikki.linnakangas@i 1256 :CBC 13719 : process_startup_options(Port *port, bool am_superuser)
1257 : : {
1258 : : GucContext gucctx;
1259 : : ListCell *gucopts;
1260 : :
4201 tgl@sss.pgh.pa.us 1261 [ + + ]: 13719 : gucctx = am_superuser ? PGC_SU_BACKEND : PGC_BACKEND;
1262 : :
1263 : : /*
1264 : : * First process any command-line switches that were included in the
1265 : : * startup packet, if we are in a regular backend.
1266 : : */
5662 heikki.linnakangas@i 1267 [ + + ]: 13719 : if (port->cmdline_options != NULL)
1268 : : {
1269 : : /*
1270 : : * The maximum possible number of commandline arguments that could
1271 : : * come from port->cmdline_options is (strlen + 1) / 2; see
1272 : : * pg_split_opts().
1273 : : */
1274 : : char **av;
1275 : : int maxac;
1276 : : int ac;
1277 : :
1278 : 3787 : maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
1279 : :
95 michael@paquier.xyz 1280 :GNC 3787 : av = palloc_array(char *, maxac);
6039 tgl@sss.pgh.pa.us 1281 :CBC 3787 : ac = 0;
1282 : :
1283 : 3787 : av[ac++] = "postgres";
1284 : :
5662 heikki.linnakangas@i 1285 : 3787 : pg_split_opts(av, &ac, port->cmdline_options);
1286 : :
6039 tgl@sss.pgh.pa.us 1287 : 3787 : av[ac] = NULL;
1288 : :
1289 [ - + ]: 3787 : Assert(ac < maxac);
1290 : :
4731 1291 : 3787 : (void) process_postgres_switches(ac, av, gucctx, NULL);
1292 : : }
1293 : :
1294 : : /*
1295 : : * Process any additional GUC variable settings passed in startup packet.
1296 : : * These are handled exactly like command-line variables.
1297 : : */
5662 heikki.linnakangas@i 1298 : 13719 : gucopts = list_head(port->guc_options);
1299 [ + + ]: 32638 : while (gucopts)
1300 : : {
1301 : : char *name;
1302 : : char *value;
1303 : :
1304 : 18919 : name = lfirst(gucopts);
2435 tgl@sss.pgh.pa.us 1305 : 18919 : gucopts = lnext(port->guc_options, gucopts);
1306 : :
5662 heikki.linnakangas@i 1307 : 18919 : value = lfirst(gucopts);
2435 tgl@sss.pgh.pa.us 1308 : 18919 : gucopts = lnext(port->guc_options, gucopts);
1309 : :
5662 heikki.linnakangas@i 1310 : 18919 : SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
1311 : : }
9218 tgl@sss.pgh.pa.us 1312 : 13719 : }
1313 : :
1314 : : /*
1315 : : * Load GUC settings from pg_db_role_setting.
1316 : : *
1317 : : * We try specific settings for the database/role combination, as well as
1318 : : * general for this database and for this user.
1319 : : */
1320 : : static void
6003 alvherre@alvh.no-ip. 1321 : 15466 : process_settings(Oid databaseid, Oid roleid)
1322 : : {
1323 : : Relation relsetting;
1324 : : Snapshot snapshot;
1325 : :
1326 [ + + ]: 15466 : if (!IsUnderPostmaster)
1327 : 119 : return;
1328 : :
2610 andres@anarazel.de 1329 : 15347 : relsetting = table_open(DbRoleSettingRelationId, AccessShareLock);
1330 : :
1331 : : /* read all the settings under the same snapshot for efficiency */
4639 rhaas@postgresql.org 1332 : 15347 : snapshot = RegisterSnapshot(GetCatalogSnapshot(DbRoleSettingRelationId));
1333 : :
1334 : : /* Later settings are ignored if set earlier. */
1335 : 15347 : ApplySetting(snapshot, databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
1336 : 15347 : ApplySetting(snapshot, InvalidOid, roleid, relsetting, PGC_S_USER);
1337 : 15347 : ApplySetting(snapshot, databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
1338 : 15347 : ApplySetting(snapshot, InvalidOid, InvalidOid, relsetting, PGC_S_GLOBAL);
1339 : :
1340 : 15347 : UnregisterSnapshot(snapshot);
2610 andres@anarazel.de 1341 : 15347 : table_close(relsetting, AccessShareLock);
1342 : : }
1343 : :
1344 : : /*
1345 : : * Backend-shutdown callback. Do cleanup that we want to be sure happens
1346 : : * before all the supporting modules begin to nail their doors shut via
1347 : : * their own callbacks.
1348 : : *
1349 : : * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
1350 : : * via separate callbacks that execute before this one. We don't combine the
1351 : : * callbacks because we still want this one to happen if the user-level
1352 : : * cleanup fails.
1353 : : */
1354 : : static void
8129 peter_e@gmx.net 1355 : 17056 : ShutdownPostgres(int code, Datum arg)
1356 : : {
1357 : : /* Make sure we've killed any active transaction */
7524 tgl@sss.pgh.pa.us 1358 : 17056 : AbortOutOfAnyTransaction();
1359 : :
1360 : : /*
1361 : : * User locks are not released by transaction end, so be sure to release
1362 : : * them explicitly.
1363 : : */
1364 : 17056 : LockReleaseAll(USER_LOCKMETHOD, true);
9657 vadim4o@yahoo.com 1365 : 17056 : }
1366 : :
1367 : :
1368 : : /*
1369 : : * STATEMENT_TIMEOUT handler: trigger a query-cancel interrupt.
1370 : : */
1371 : : static void
4990 alvherre@alvh.no-ip. 1372 : 6 : StatementTimeoutHandler(void)
1373 : : {
3949 bruce@momjian.us 1374 : 6 : int sig = SIGINT;
1375 : :
1376 : : /*
1377 : : * During authentication the timeout is used to deal with
1378 : : * authentication_timeout - we want to quit in response to such timeouts.
1379 : : */
4058 andres@anarazel.de 1380 [ - + ]: 6 : if (ClientAuthInProgress)
4058 andres@anarazel.de 1381 :UBC 0 : sig = SIGTERM;
1382 : :
1383 : : #ifdef HAVE_SETSID
1384 : : /* try to signal whole process group */
4058 andres@anarazel.de 1385 :CBC 6 : kill(-MyProcPid, sig);
1386 : : #endif
1387 : 6 : kill(MyProcPid, sig);
4990 alvherre@alvh.no-ip. 1388 : 6 : }
1389 : :
1390 : : /*
1391 : : * LOCK_TIMEOUT handler: trigger a query-cancel interrupt.
1392 : : */
1393 : : static void
4747 tgl@sss.pgh.pa.us 1394 : 4 : LockTimeoutHandler(void)
1395 : : {
1396 : : #ifdef HAVE_SETSID
1397 : : /* try to signal whole process group */
1398 : 4 : kill(-MyProcPid, SIGINT);
1399 : : #endif
1400 : 4 : kill(MyProcPid, SIGINT);
1401 : 4 : }
1402 : :
1403 : : static void
759 akorotkov@postgresql 1404 : 1 : TransactionTimeoutHandler(void)
1405 : : {
1406 : 1 : TransactionTimeoutPending = true;
1407 : 1 : InterruptPending = true;
1408 : 1 : SetLatch(MyLatch);
1409 : 1 : }
1410 : :
1411 : : static void
3651 rhaas@postgresql.org 1412 : 1 : IdleInTransactionSessionTimeoutHandler(void)
1413 : : {
1414 : 1 : IdleInTransactionSessionTimeoutPending = true;
1415 : 1 : InterruptPending = true;
1416 : 1 : SetLatch(MyLatch);
1417 : 1 : }
1418 : :
1419 : : static void
1894 tgl@sss.pgh.pa.us 1420 : 1 : IdleSessionTimeoutHandler(void)
1421 : : {
1422 : 1 : IdleSessionTimeoutPending = true;
1423 : 1 : InterruptPending = true;
1424 : 1 : SetLatch(MyLatch);
1425 : 1 : }
1426 : :
1427 : : static void
1439 andres@anarazel.de 1428 : 27 : IdleStatsUpdateTimeoutHandler(void)
1429 : : {
1430 : 27 : IdleStatsUpdateTimeoutPending = true;
1431 : 27 : InterruptPending = true;
1432 : 27 : SetLatch(MyLatch);
1433 : 27 : }
1434 : :
1435 : : static void
1807 tmunro@postgresql.or 1436 :UBC 0 : ClientCheckTimeoutHandler(void)
1437 : : {
1438 : 0 : CheckClientConnectionPending = true;
1439 : 0 : InterruptPending = true;
1440 : 0 : SetLatch(MyLatch);
1441 : 0 : }
1442 : :
1443 : : /*
1444 : : * Returns true if at least one role is defined in this database cluster.
1445 : : */
1446 : : static bool
7565 tgl@sss.pgh.pa.us 1447 :CBC 70 : ThereIsAtLeastOneRole(void)
1448 : : {
1449 : : Relation pg_authid_rel;
1450 : : TableScanDesc scan;
1451 : : bool result;
1452 : :
2610 andres@anarazel.de 1453 : 70 : pg_authid_rel = table_open(AuthIdRelationId, AccessShareLock);
1454 : :
2561 1455 : 70 : scan = table_beginscan_catalog(pg_authid_rel, 0, NULL);
8700 tgl@sss.pgh.pa.us 1456 : 70 : result = (heap_getnext(scan, ForwardScanDirection) != NULL);
1457 : :
2561 andres@anarazel.de 1458 : 70 : table_endscan(scan);
2610 1459 : 70 : table_close(pg_authid_rel, AccessShareLock);
1460 : :
8954 peter_e@gmx.net 1461 : 70 : return result;
1462 : : }
1463 : :
1464 : : /*
1465 : : * Stores a warning message to be sent later via EmitConnectionWarnings().
1466 : : * Both msg and detail must be non-NULL.
1467 : : *
1468 : : * NB: Caller should ensure the strings are allocated in a long-lived context
1469 : : * like TopMemoryContext.
1470 : : */
1471 : : void
32 nathan@postgresql.or 1472 :GNC 2 : StoreConnectionWarning(char *msg, char *detail)
1473 : : {
1474 : : MemoryContext oldcontext;
1475 : :
1476 [ - + ]: 2 : Assert(msg);
1477 [ - + ]: 2 : Assert(detail);
1478 : :
1479 [ - + ]: 2 : if (ConnectionWarningsEmitted)
32 nathan@postgresql.or 1480 [ # # ]:UNC 0 : elog(ERROR, "StoreConnectionWarning() called after EmitConnectionWarnings()");
1481 : :
32 nathan@postgresql.or 1482 :GNC 2 : oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1483 : :
1484 : 2 : ConnectionWarningMessages = lappend(ConnectionWarningMessages, msg);
1485 : 2 : ConnectionWarningDetails = lappend(ConnectionWarningDetails, detail);
1486 : :
1487 : 2 : MemoryContextSwitchTo(oldcontext);
1488 : 2 : }
1489 : :
1490 : : /*
1491 : : * Sends the warning messages saved via StoreConnectionWarning() and frees the
1492 : : * strings and lists.
1493 : : *
1494 : : * NB: This can only be called once per backend.
1495 : : */
1496 : : static void
1497 : 15955 : EmitConnectionWarnings(void)
1498 : : {
1499 : : ListCell *lc_msg;
1500 : : ListCell *lc_detail;
1501 : :
1502 [ - + ]: 15955 : if (ConnectionWarningsEmitted)
32 nathan@postgresql.or 1503 [ # # ]:UNC 0 : elog(ERROR, "EmitConnectionWarnings() called more than once");
1504 : : else
32 nathan@postgresql.or 1505 :GNC 15955 : ConnectionWarningsEmitted = true;
1506 : :
1507 [ + + + + : 15957 : forboth(lc_msg, ConnectionWarningMessages,
+ + + + +
+ + - +
+ ]
1508 : : lc_detail, ConnectionWarningDetails)
1509 : : {
1510 [ + - ]: 2 : ereport(WARNING,
1511 : : (errmsg("%s", (char *) lfirst(lc_msg)),
1512 : : errdetail("%s", (char *) lfirst(lc_detail))));
1513 : : }
1514 : :
1515 : 15955 : list_free_deep(ConnectionWarningMessages);
1516 : 15955 : list_free_deep(ConnectionWarningDetails);
1517 : 15955 : }
|