Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * connection.c
4 : : * Connection management functions for postgres_fdw
5 : : *
6 : : * Portions Copyright (c) 2012-2026, PostgreSQL Global Development Group
7 : : *
8 : : * IDENTIFICATION
9 : : * contrib/postgres_fdw/connection.c
10 : : *
11 : : *-------------------------------------------------------------------------
12 : : */
13 : : #include "postgres.h"
14 : :
15 : : #if HAVE_POLL_H
16 : : #include <poll.h>
17 : : #endif
18 : :
19 : : #include "access/htup_details.h"
20 : : #include "access/xact.h"
21 : : #include "catalog/pg_user_mapping.h"
22 : : #include "commands/defrem.h"
23 : : #include "common/base64.h"
24 : : #include "funcapi.h"
25 : : #include "libpq/libpq-be.h"
26 : : #include "libpq/libpq-be-fe-helpers.h"
27 : : #include "mb/pg_wchar.h"
28 : : #include "miscadmin.h"
29 : : #include "pgstat.h"
30 : : #include "postgres_fdw.h"
31 : : #include "storage/latch.h"
32 : : #include "utils/builtins.h"
33 : : #include "utils/hsearch.h"
34 : : #include "utils/inval.h"
35 : : #include "utils/syscache.h"
36 : :
37 : : /*
38 : : * Connection cache hash table entry
39 : : *
40 : : * The lookup key in this hash table is the user mapping OID. We use just one
41 : : * connection per user mapping ID, which ensures that all the scans use the
42 : : * same snapshot during a query. Using the user mapping OID rather than
43 : : * the foreign server OID + user OID avoids creating multiple connections when
44 : : * the public user mapping applies to all user OIDs.
45 : : *
46 : : * The "conn" pointer can be NULL if we don't currently have a live connection.
47 : : * When we do have a connection, xact_depth tracks the current depth of
48 : : * transactions and subtransactions open on the remote side. We need to issue
49 : : * commands at the same nesting depth on the remote as we're executing at
50 : : * ourselves, so that rolling back a subtransaction will kill the right
51 : : * queries and not the wrong ones.
52 : : */
53 : : typedef Oid ConnCacheKey;
54 : :
55 : : typedef struct ConnCacheEntry
56 : : {
57 : : ConnCacheKey key; /* hash key (must be first) */
58 : : PGconn *conn; /* connection to foreign server, or NULL */
59 : : /* Remaining fields are invalid when conn is NULL: */
60 : : int xact_depth; /* 0 = no xact open, 1 = main xact open, 2 =
61 : : * one level of subxact open, etc */
62 : : bool have_prep_stmt; /* have we prepared any stmts in this xact? */
63 : : bool have_error; /* have any subxacts aborted in this xact? */
64 : : bool changing_xact_state; /* xact state change in process */
65 : : bool parallel_commit; /* do we commit (sub)xacts in parallel? */
66 : : bool parallel_abort; /* do we abort (sub)xacts in parallel? */
67 : : bool invalidated; /* true if reconnect is pending */
68 : : bool keep_connections; /* setting value of keep_connections
69 : : * server option */
70 : : Oid serverid; /* foreign server OID used to get server name */
71 : : uint32 server_hashvalue; /* hash value of foreign server OID */
72 : : uint32 mapping_hashvalue; /* hash value of user mapping OID */
73 : : PgFdwConnState state; /* extra per-connection state */
74 : : } ConnCacheEntry;
75 : :
76 : : /*
77 : : * Connection cache (initialized on first use)
78 : : */
79 : : static HTAB *ConnectionHash = NULL;
80 : :
81 : : /* for assigning cursor numbers and prepared statement numbers */
82 : : static unsigned int cursor_number = 0;
83 : : static unsigned int prep_stmt_number = 0;
84 : :
85 : : /* tracks whether any work is needed in callback functions */
86 : : static bool xact_got_connection = false;
87 : :
88 : : /* custom wait event values, retrieved from shared memory */
89 : : static uint32 pgfdw_we_cleanup_result = 0;
90 : : static uint32 pgfdw_we_connect = 0;
91 : : static uint32 pgfdw_we_get_result = 0;
92 : :
93 : : /*
94 : : * Milliseconds to wait to cancel an in-progress query or execute a cleanup
95 : : * query; if it takes longer than 30 seconds to do these, we assume the
96 : : * connection is dead.
97 : : */
98 : : #define CONNECTION_CLEANUP_TIMEOUT 30000
99 : :
100 : : /*
101 : : * Milliseconds to wait before issuing another cancel request. This covers
102 : : * the race condition where the remote session ignored our cancel request
103 : : * because it arrived while idle.
104 : : */
105 : : #define RETRY_CANCEL_TIMEOUT 1000
106 : :
107 : : /* Macro for constructing abort command to be sent */
108 : : #define CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel) \
109 : : do { \
110 : : if (toplevel) \
111 : : snprintf((sql), sizeof(sql), \
112 : : "ABORT TRANSACTION"); \
113 : : else \
114 : : snprintf((sql), sizeof(sql), \
115 : : "ROLLBACK TO SAVEPOINT s%d; RELEASE SAVEPOINT s%d", \
116 : : (entry)->xact_depth, (entry)->xact_depth); \
117 : : } while(0)
118 : :
119 : : /*
120 : : * Extension version number, for supporting older extension versions' objects
121 : : */
122 : : enum pgfdwVersion
123 : : {
124 : : PGFDW_V1_1 = 0,
125 : : PGFDW_V1_2,
126 : : };
127 : :
128 : : /*
129 : : * SQL functions
130 : : */
1882 fujii@postgresql.org 131 :CBC 5 : PG_FUNCTION_INFO_V1(postgres_fdw_get_connections);
597 132 : 6 : PG_FUNCTION_INFO_V1(postgres_fdw_get_connections_1_2);
1874 133 : 6 : PG_FUNCTION_INFO_V1(postgres_fdw_disconnect);
134 : 6 : PG_FUNCTION_INFO_V1(postgres_fdw_disconnect_all);
9 jdavis@postgresql.or 135 :GNC 10 : PG_FUNCTION_INFO_V1(postgres_fdw_connection);
136 : :
137 : : /* prototypes of private functions */
138 : : static void make_new_connection(ConnCacheEntry *entry, UserMapping *user);
139 : : static PGconn *connect_pg_server(ForeignServer *server, UserMapping *user);
140 : : static void disconnect_pg_server(ConnCacheEntry *entry);
141 : : static void check_conn_params(const char **keywords, const char **values, UserMapping *user);
142 : : static void configure_remote_session(PGconn *conn);
143 : : static void do_sql_command_begin(PGconn *conn, const char *sql);
144 : : static void do_sql_command_end(PGconn *conn, const char *sql,
145 : : bool consume_input);
146 : : static void begin_remote_xact(ConnCacheEntry *entry);
147 : : static void pgfdw_report_internal(int elevel, PGresult *res, PGconn *conn,
148 : : const char *sql);
149 : : static void pgfdw_xact_callback(XactEvent event, void *arg);
150 : : static void pgfdw_subxact_callback(SubXactEvent event,
151 : : SubTransactionId mySubid,
152 : : SubTransactionId parentSubid,
153 : : void *arg);
154 : : static void pgfdw_inval_callback(Datum arg, SysCacheIdentifier cacheid,
155 : : uint32 hashvalue);
156 : : static void pgfdw_reject_incomplete_xact_state_change(ConnCacheEntry *entry);
157 : : static void pgfdw_reset_xact_state(ConnCacheEntry *entry, bool toplevel);
158 : : static bool pgfdw_cancel_query(PGconn *conn);
159 : : static bool pgfdw_cancel_query_begin(PGconn *conn, TimestampTz endtime);
160 : : static bool pgfdw_cancel_query_end(PGconn *conn, TimestampTz endtime,
161 : : TimestampTz retrycanceltime,
162 : : bool consume_input);
163 : : static bool pgfdw_exec_cleanup_query(PGconn *conn, const char *query,
164 : : bool ignore_errors);
165 : : static bool pgfdw_exec_cleanup_query_begin(PGconn *conn, const char *query);
166 : : static bool pgfdw_exec_cleanup_query_end(PGconn *conn, const char *query,
167 : : TimestampTz endtime,
168 : : bool consume_input,
169 : : bool ignore_errors);
170 : : static bool pgfdw_get_cleanup_result(PGconn *conn, TimestampTz endtime,
171 : : TimestampTz retrycanceltime,
172 : : PGresult **result, bool *timed_out);
173 : : static void pgfdw_abort_cleanup(ConnCacheEntry *entry, bool toplevel);
174 : : static bool pgfdw_abort_cleanup_begin(ConnCacheEntry *entry, bool toplevel,
175 : : List **pending_entries,
176 : : List **cancel_requested);
177 : : static void pgfdw_finish_pre_commit_cleanup(List *pending_entries);
178 : : static void pgfdw_finish_pre_subcommit_cleanup(List *pending_entries,
179 : : int curlevel);
180 : : static void pgfdw_finish_abort_cleanup(List *pending_entries,
181 : : List *cancel_requested,
182 : : bool toplevel);
183 : : static void pgfdw_security_check(const char **keywords, const char **values,
184 : : UserMapping *user, PGconn *conn);
185 : : static bool UserMappingPasswordRequired(UserMapping *user);
186 : : static bool UseScramPassthrough(ForeignServer *server, UserMapping *user);
187 : : static bool disconnect_cached_connections(Oid serverid);
188 : : static void postgres_fdw_get_connections_internal(FunctionCallInfo fcinfo,
189 : : enum pgfdwVersion api_version);
190 : : static int pgfdw_conn_check(PGconn *conn);
191 : : static bool pgfdw_conn_checkable(void);
192 : : static bool pgfdw_has_required_scram_options(const char **keywords, const char **values);
193 : :
194 : : /*
195 : : * Get a PGconn which can be used to execute queries on the remote PostgreSQL
196 : : * server with the user's authorization. A new connection is established
197 : : * if we don't already have a suitable one, and a transaction is opened at
198 : : * the right subtransaction nesting depth if we didn't do that already.
199 : : *
200 : : * will_prep_stmt must be true if caller intends to create any prepared
201 : : * statements. Since those don't go away automatically at transaction end
202 : : * (not even on error), we need this flag to cue manual cleanup.
203 : : *
204 : : * If state is not NULL, *state receives the per-connection state associated
205 : : * with the PGconn.
206 : : */
207 : : PGconn *
1810 efujita@postgresql.o 208 :CBC 2253 : GetConnection(UserMapping *user, bool will_prep_stmt, PgFdwConnState **state)
209 : : {
210 : : bool found;
1976 fujii@postgresql.org 211 : 2253 : bool retry = false;
212 : : ConnCacheEntry *entry;
213 : : ConnCacheKey key;
214 : 2253 : MemoryContext ccxt = CurrentMemoryContext;
215 : :
216 : : /* First time through, initialize connection cache hashtable */
4770 tgl@sss.pgh.pa.us 217 [ + + ]: 2253 : if (ConnectionHash == NULL)
218 : : {
219 : : HASHCTL ctl;
220 : :
797 noah@leadboat.com 221 [ + - ]: 17 : if (pgfdw_we_get_result == 0)
222 : 17 : pgfdw_we_get_result =
223 : 17 : WaitEventExtensionNew("PostgresFdwGetResult");
224 : :
4770 tgl@sss.pgh.pa.us 225 : 17 : ctl.keysize = sizeof(ConnCacheKey);
226 : 17 : ctl.entrysize = sizeof(ConnCacheEntry);
227 : 17 : ConnectionHash = hash_create("postgres_fdw connections", 8,
228 : : &ctl,
229 : : HASH_ELEM | HASH_BLOBS);
230 : :
231 : : /*
232 : : * Register some callback functions that manage connection cleanup.
233 : : * This should be done just once in each backend.
234 : : */
235 : 17 : RegisterXactCallback(pgfdw_xact_callback, NULL);
236 : 17 : RegisterSubXactCallback(pgfdw_subxact_callback, NULL);
3159 237 : 17 : CacheRegisterSyscacheCallback(FOREIGNSERVEROID,
238 : : pgfdw_inval_callback, (Datum) 0);
239 : 17 : CacheRegisterSyscacheCallback(USERMAPPINGOID,
240 : : pgfdw_inval_callback, (Datum) 0);
241 : : }
242 : :
243 : : /* Set flag that we did GetConnection during the current transaction */
4770 244 : 2253 : xact_got_connection = true;
245 : :
246 : : /* Create hash key for the entry. Assume no pad bytes in key struct */
3699 rhaas@postgresql.org 247 : 2253 : key = user->umid;
248 : :
249 : : /*
250 : : * Find or create cached entry for requested connection.
251 : : */
4770 tgl@sss.pgh.pa.us 252 : 2253 : entry = hash_search(ConnectionHash, &key, HASH_ENTER, &found);
253 [ + + ]: 2253 : if (!found)
254 : : {
255 : : /*
256 : : * We need only clear "conn" here; remaining fields will be filled
257 : : * later when "conn" is set.
258 : : */
259 : 28 : entry->conn = NULL;
260 : : }
261 : :
262 : : /* Reject further use of connections which failed abort cleanup. */
3203 rhaas@postgresql.org 263 : 2253 : pgfdw_reject_incomplete_xact_state_change(entry);
264 : :
265 : : /*
266 : : * If the connection needs to be remade due to invalidation, disconnect as
267 : : * soon as we're out of all transactions.
268 : : */
1976 fujii@postgresql.org 269 [ + + - + : 2253 : if (entry->conn != NULL && entry->invalidated && entry->xact_depth == 0)
- - ]
270 : : {
1976 fujii@postgresql.org 271 [ # # ]:UBC 0 : elog(DEBUG3, "closing connection %p for option changes to take effect",
272 : : entry->conn);
3159 tgl@sss.pgh.pa.us 273 : 0 : disconnect_pg_server(entry);
274 : : }
275 : :
276 : : /*
277 : : * If cache entry doesn't have a connection, we have to establish a new
278 : : * connection. (If connect_pg_server throws an error, the cache entry
279 : : * will remain in a valid empty state, ie conn == NULL.)
280 : : */
4770 tgl@sss.pgh.pa.us 281 [ + + ]:CBC 2253 : if (entry->conn == NULL)
1976 fujii@postgresql.org 282 : 88 : make_new_connection(entry, user);
283 : :
284 : : /*
285 : : * We check the health of the cached connection here when using it. In
286 : : * cases where we're out of all transactions, if a broken connection is
287 : : * detected, we try to reestablish a new connection later.
288 : : */
1986 289 [ + + ]: 2244 : PG_TRY();
290 : : {
291 : : /* Process a pending asynchronous request if any. */
1810 efujita@postgresql.o 292 [ - + ]: 2244 : if (entry->state.pendingAreq)
1810 efujita@postgresql.o 293 :UBC 0 : process_pending_request(entry->state.pendingAreq);
294 : : /* Start a new transaction or subtransaction if needed. */
1986 fujii@postgresql.org 295 :CBC 2244 : begin_remote_xact(entry);
296 : : }
297 : 2 : PG_CATCH();
298 : : {
1976 299 : 2 : MemoryContext ecxt = MemoryContextSwitchTo(ccxt);
300 : 2 : ErrorData *errdata = CopyErrorData();
301 : :
302 : : /*
303 : : * Determine whether to try to reestablish the connection.
304 : : *
305 : : * After a broken connection is detected in libpq, any error other
306 : : * than connection failure (e.g., out-of-memory) can be thrown
307 : : * somewhere between return from libpq and the expected ereport() call
308 : : * in pgfdw_report_error(). In this case, since PQstatus() indicates
309 : : * CONNECTION_BAD, checking only PQstatus() causes the false detection
310 : : * of connection failure. To avoid this, we also verify that the
311 : : * error's sqlstate is ERRCODE_CONNECTION_FAILURE. Note that also
312 : : * checking only the sqlstate can cause another false detection
313 : : * because pgfdw_report_error() may report ERRCODE_CONNECTION_FAILURE
314 : : * for any libpq-originated error condition.
315 : : */
316 [ + - ]: 2 : if (errdata->sqlerrcode != ERRCODE_CONNECTION_FAILURE ||
317 [ + - ]: 2 : PQstatus(entry->conn) != CONNECTION_BAD ||
318 [ + + ]: 2 : entry->xact_depth > 0)
319 : : {
320 : 1 : MemoryContextSwitchTo(ecxt);
1986 321 : 1 : PG_RE_THROW();
322 : : }
323 : :
324 : : /* Clean up the error state */
1976 325 : 1 : FlushErrorState();
326 : 1 : FreeErrorData(errdata);
327 : 1 : errdata = NULL;
328 : :
329 : 1 : retry = true;
330 : : }
1986 331 [ - + ]: 2243 : PG_END_TRY();
332 : :
333 : : /*
334 : : * If a broken connection is detected, disconnect it, reestablish a new
335 : : * connection and retry a new remote transaction. If connection failure is
336 : : * reported again, we give up getting a connection.
337 : : */
1976 338 [ + + ]: 2243 : if (retry)
339 : : {
340 [ - + ]: 1 : Assert(entry->xact_depth == 0);
341 : :
1986 342 [ - + ]: 1 : ereport(DEBUG3,
343 : : (errmsg_internal("could not start remote transaction on connection %p",
344 : : entry->conn)),
345 : : errdetail_internal("%s", pchomp(PQerrorMessage(entry->conn))));
346 : :
1976 347 [ - + ]: 1 : elog(DEBUG3, "closing connection %p to reestablish a new one",
348 : : entry->conn);
349 : 1 : disconnect_pg_server(entry);
350 : :
1094 efujita@postgresql.o 351 : 1 : make_new_connection(entry, user);
352 : :
1976 fujii@postgresql.org 353 : 1 : begin_remote_xact(entry);
354 : : }
355 : :
356 : : /* Remember if caller will prepare statements */
4753 tgl@sss.pgh.pa.us 357 : 2243 : entry->have_prep_stmt |= will_prep_stmt;
358 : :
359 : : /* If caller needs access to the per-connection state, return it. */
1810 efujita@postgresql.o 360 [ + + ]: 2243 : if (state)
361 : 762 : *state = &entry->state;
362 : :
4770 tgl@sss.pgh.pa.us 363 : 2243 : return entry->conn;
364 : : }
365 : :
366 : : /*
367 : : * Reset all transient state fields in the cached connection entry and
368 : : * establish new connection to the remote server.
369 : : */
370 : : static void
1976 fujii@postgresql.org 371 : 89 : make_new_connection(ConnCacheEntry *entry, UserMapping *user)
372 : : {
373 : 89 : ForeignServer *server = GetForeignServer(user->serverid);
374 : : ListCell *lc;
375 : :
376 [ - + ]: 89 : Assert(entry->conn == NULL);
377 : :
378 : : /* Reset all transient state fields, to be sure all are clean */
379 : 89 : entry->xact_depth = 0;
380 : 89 : entry->have_prep_stmt = false;
381 : 89 : entry->have_error = false;
382 : 89 : entry->changing_xact_state = false;
383 : 89 : entry->invalidated = false;
1885 384 : 89 : entry->serverid = server->serverid;
1976 385 : 89 : entry->server_hashvalue =
386 : 89 : GetSysCacheHashValue1(FOREIGNSERVEROID,
387 : : ObjectIdGetDatum(server->serverid));
388 : 89 : entry->mapping_hashvalue =
389 : 89 : GetSysCacheHashValue1(USERMAPPINGOID,
390 : : ObjectIdGetDatum(user->umid));
1810 efujita@postgresql.o 391 : 89 : memset(&entry->state, 0, sizeof(entry->state));
392 : :
393 : : /*
394 : : * Determine whether to keep the connection that we're about to make here
395 : : * open even after the transaction using it ends, so that the subsequent
396 : : * transactions can re-use it.
397 : : *
398 : : * By default, all the connections to any foreign servers are kept open.
399 : : *
400 : : * Also determine whether to commit/abort (sub)transactions opened on the
401 : : * remote server in parallel at (sub)transaction end, which is disabled by
402 : : * default.
403 : : *
404 : : * Note: it's enough to determine these only when making a new connection
405 : : * because if these settings for it are changed, it will be closed and
406 : : * re-made later.
407 : : */
1808 fujii@postgresql.org 408 : 89 : entry->keep_connections = true;
1480 efujita@postgresql.o 409 : 89 : entry->parallel_commit = false;
1074 410 : 89 : entry->parallel_abort = false;
1808 fujii@postgresql.org 411 [ + - + + : 406 : foreach(lc, server->options)
+ + ]
412 : : {
413 : 317 : DefElem *def = (DefElem *) lfirst(lc);
414 : :
415 [ + + ]: 317 : if (strcmp(def->defname, "keep_connections") == 0)
416 : 13 : entry->keep_connections = defGetBoolean(def);
1480 efujita@postgresql.o 417 [ + + ]: 304 : else if (strcmp(def->defname, "parallel_commit") == 0)
418 : 2 : entry->parallel_commit = defGetBoolean(def);
1074 419 [ + + ]: 302 : else if (strcmp(def->defname, "parallel_abort") == 0)
420 : 2 : entry->parallel_abort = defGetBoolean(def);
421 : : }
422 : :
423 : : /* Now try to make the connection */
1976 fujii@postgresql.org 424 : 89 : entry->conn = connect_pg_server(server, user);
425 : :
426 [ - + ]: 80 : elog(DEBUG3, "new postgres_fdw connection %p for server \"%s\" (user mapping oid %u, userid %u)",
427 : : entry->conn, server->servername, user->umid, user->userid);
428 : 80 : }
429 : :
430 : : /*
431 : : * Check that non-superuser has used password or delegated credentials
432 : : * to establish connection; otherwise, he's piggybacking on the
433 : : * postgres server's user identity. See also dblink_security_check()
434 : : * in contrib/dblink and check_conn_params.
435 : : */
436 : : static void
1067 sfrost@snowman.net 437 : 83 : pgfdw_security_check(const char **keywords, const char **values, UserMapping *user, PGconn *conn)
438 : : {
439 : : /* Superusers bypass the check */
440 [ + + ]: 83 : if (superuser_arg(user->userid))
441 : 72 : return;
442 : :
443 : : #ifdef ENABLE_GSS
444 : : /* Connected via GSSAPI with delegated credentials- all good. */
1030 bruce@momjian.us 445 [ + + + - ]: 11 : if (PQconnectionUsedGSSAPI(conn) && be_gssapi_get_delegation(MyProcPort))
1067 sfrost@snowman.net 446 : 2 : return;
447 : : #endif
448 : :
449 : : /* Ok if superuser set PW required false. */
450 [ + + ]: 9 : if (!UserMappingPasswordRequired(user))
451 : 2 : return;
452 : :
453 : : /* Connected via PW, with PW required true, and provided non-empty PW. */
454 [ + + ]: 7 : if (PQconnectionUsedPassword(conn))
455 : : {
456 : : /* ok if params contain a non-empty password */
457 [ + + ]: 47 : for (int i = 0; keywords[i] != NULL; i++)
458 : : {
459 [ - + - - ]: 42 : if (strcmp(keywords[i], "password") == 0 && values[i][0] != '\0')
1067 sfrost@snowman.net 460 :UBC 0 : return;
461 : : }
462 : : }
463 : :
464 : : /*
465 : : * Ok if SCRAM pass-through is being used and all required SCRAM options
466 : : * are set correctly. If pgfdw_has_required_scram_options returns true we
467 : : * assume that UseScramPassthrough is also true since SCRAM options are
468 : : * only set when UseScramPassthrough is enabled.
469 : : */
219 peter@eisentraut.org 470 [ + - + + :CBC 7 : if (MyProcPort != NULL && MyProcPort->has_scram_keys && pgfdw_has_required_scram_options(keywords, values))
+ - ]
356 471 : 4 : return;
472 : :
1067 sfrost@snowman.net 473 [ + - ]: 3 : ereport(ERROR,
474 : : (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
475 : : errmsg("password or GSSAPI delegated credentials required"),
476 : : errdetail("Non-superuser cannot connect if the server does not request a password or use GSSAPI with delegated credentials."),
477 : : errhint("Target server's authentication method must be changed or password_required=false set in the user mapping attributes.")));
478 : : }
479 : :
480 : : /*
481 : : * Construct connection params from generic options of ForeignServer and
482 : : * UserMapping. (Some of them might not be libpq options, in which case we'll
483 : : * just waste a few array slots.)
484 : : */
485 : : static void
9 jdavis@postgresql.or 486 :GNC 95 : construct_connection_params(ForeignServer *server, UserMapping *user,
487 : : const char ***p_keywords, const char ***p_values,
488 : : char **p_appname)
489 : : {
490 : : const char **keywords;
491 : : const char **values;
492 : 95 : char *appname = NULL;
493 : : int n;
494 : :
495 : : /*
496 : : * Add 4 extra slots for application_name, fallback_application_name,
497 : : * client_encoding, end marker, and 3 extra slots for scram keys and
498 : : * required scram pass-through options.
499 : : */
500 : 95 : n = list_length(server->options) + list_length(user->options) + 4 + 3;
501 : 95 : keywords = (const char **) palloc(n * sizeof(char *));
502 : 95 : values = (const char **) palloc(n * sizeof(char *));
503 : :
504 : 95 : n = 0;
505 : 190 : n += ExtractConnectionOptions(server->options,
506 : 95 : keywords + n, values + n);
507 : 190 : n += ExtractConnectionOptions(user->options,
508 : 95 : keywords + n, values + n);
509 : :
510 : : /*
511 : : * Use pgfdw_application_name as application_name if set.
512 : : *
513 : : * PQconnectdbParams() processes the parameter arrays from start to end.
514 : : * If any key word is repeated, the last value is used. Therefore note
515 : : * that pgfdw_application_name must be added to the arrays after options
516 : : * of ForeignServer are, so that it can override application_name set in
517 : : * ForeignServer.
518 : : */
519 [ + + + - ]: 95 : if (pgfdw_application_name && *pgfdw_application_name != '\0')
520 : : {
521 : 1 : keywords[n] = "application_name";
522 : 1 : values[n] = pgfdw_application_name;
523 : 1 : n++;
524 : : }
525 : :
526 : : /*
527 : : * Search the parameter arrays to find application_name setting, and
528 : : * replace escape sequences in it with status information if found. The
529 : : * arrays are searched backwards because the last value is used if
530 : : * application_name is repeatedly set.
531 : : */
532 [ + + ]: 298 : for (int i = n - 1; i >= 0; i--)
533 : : {
534 [ + + ]: 228 : if (strcmp(keywords[i], "application_name") == 0 &&
535 [ + - ]: 25 : *(values[i]) != '\0')
536 : : {
537 : : /*
538 : : * Use this application_name setting if it's not empty string even
539 : : * after any escape sequences in it are replaced.
540 : : */
541 : 25 : appname = process_pgfdw_appname(values[i]);
542 [ + - ]: 25 : if (appname[0] != '\0')
543 : : {
544 : 25 : values[i] = appname;
545 : 25 : break;
546 : : }
547 : :
548 : : /*
549 : : * This empty application_name is not used, so we set values[i] to
550 : : * NULL and keep searching the array to find the next one.
551 : : */
9 jdavis@postgresql.or 552 :UNC 0 : values[i] = NULL;
553 : 0 : pfree(appname);
554 : 0 : appname = NULL;
555 : : }
556 : : }
557 : :
9 jdavis@postgresql.or 558 :GNC 95 : *p_appname = appname;
559 : :
560 : : /* Use "postgres_fdw" as fallback_application_name */
561 : 95 : keywords[n] = "fallback_application_name";
562 : 95 : values[n] = "postgres_fdw";
563 : 95 : n++;
564 : :
565 : : /* Set client_encoding so that libpq can convert encoding properly. */
566 : 95 : keywords[n] = "client_encoding";
567 : 95 : values[n] = GetDatabaseEncodingName();
568 : 95 : n++;
569 : :
570 : : /* Add required SCRAM pass-through connection options if it's enabled. */
571 [ + + + + : 95 : if (MyProcPort != NULL && MyProcPort->has_scram_keys && UseScramPassthrough(server, user))
+ - ]
572 : : {
573 : : int len;
574 : : int encoded_len;
575 : :
576 : 4 : keywords[n] = "scram_client_key";
577 : 4 : len = pg_b64_enc_len(sizeof(MyProcPort->scram_ClientKey));
578 : : /* don't forget the zero-terminator */
579 : 4 : values[n] = palloc0(len + 1);
580 : 4 : encoded_len = pg_b64_encode(MyProcPort->scram_ClientKey,
581 : : sizeof(MyProcPort->scram_ClientKey),
582 : 4 : (char *) values[n], len);
583 [ - + ]: 4 : if (encoded_len < 0)
9 jdavis@postgresql.or 584 [ # # ]:UNC 0 : elog(ERROR, "could not encode SCRAM client key");
4770 tgl@sss.pgh.pa.us 585 :CBC 4 : n++;
586 : :
9 jdavis@postgresql.or 587 :GNC 4 : keywords[n] = "scram_server_key";
588 : 4 : len = pg_b64_enc_len(sizeof(MyProcPort->scram_ServerKey));
589 : : /* don't forget the zero-terminator */
590 : 4 : values[n] = palloc0(len + 1);
591 : 4 : encoded_len = pg_b64_encode(MyProcPort->scram_ServerKey,
592 : : sizeof(MyProcPort->scram_ServerKey),
593 : 4 : (char *) values[n], len);
594 [ - + ]: 4 : if (encoded_len < 0)
9 jdavis@postgresql.or 595 [ # # ]:UNC 0 : elog(ERROR, "could not encode SCRAM server key");
4770 tgl@sss.pgh.pa.us 596 :CBC 4 : n++;
597 : :
598 : : /*
599 : : * Require scram-sha-256 to ensure that no other auth method is used
600 : : * when connecting with foreign server.
601 : : */
9 jdavis@postgresql.or 602 :GNC 4 : keywords[n] = "require_auth";
603 : 4 : values[n] = "scram-sha-256";
604 : 4 : n++;
605 : : }
606 : :
607 : 95 : keywords[n] = values[n] = NULL;
608 : :
609 : : /* Verify the set of connection parameters. */
610 : 95 : check_conn_params(keywords, values, user);
611 : :
612 : 91 : *p_keywords = keywords;
613 : 91 : *p_values = values;
614 : 91 : }
615 : :
616 : : /*
617 : : * Connect to remote server using specified server and user mapping properties.
618 : : */
619 : : static PGconn *
620 : 89 : connect_pg_server(ForeignServer *server, UserMapping *user)
621 : : {
622 : 89 : PGconn *volatile conn = NULL;
623 : :
624 : : /*
625 : : * Use PG_TRY block to ensure closing connection on error.
626 : : */
627 [ + + ]: 89 : PG_TRY();
628 : : {
629 : : const char **keywords;
630 : : const char **values;
631 : : char *appname;
632 : :
633 : 89 : construct_connection_params(server, user, &keywords, &values, &appname);
634 : :
635 : : /* first time, allocate or get the custom wait event */
892 michael@paquier.xyz 636 [ + + ]:CBC 85 : if (pgfdw_we_connect == 0)
637 : 15 : pgfdw_we_connect = WaitEventExtensionNew("PostgresFdwConnect");
638 : :
639 : : /* OK to make connection */
1147 andres@anarazel.de 640 : 85 : conn = libpqsrv_connect_params(keywords, values,
641 : : false, /* expand_dbname */
642 : : pgfdw_we_connect);
643 : :
4770 tgl@sss.pgh.pa.us 644 [ + - + + ]: 85 : if (!conn || PQstatus(conn) != CONNECTION_OK)
645 [ + - ]: 2 : ereport(ERROR,
646 : : (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
647 : : errmsg("could not connect to server \"%s\"",
648 : : server->servername),
649 : : errdetail_internal("%s", pchomp(PQerrorMessage(conn)))));
650 : :
236 fujii@postgresql.org 651 :GNC 83 : PQsetNoticeReceiver(conn, libpqsrv_notice_receiver,
652 : : "received message via remote connection");
653 : :
654 : : /* Perform post-connection security checks. */
356 peter@eisentraut.org 655 :CBC 83 : pgfdw_security_check(keywords, values, user, conn);
656 : :
657 : : /* Prepare new session for use */
4769 tgl@sss.pgh.pa.us 658 : 80 : configure_remote_session(conn);
659 : :
1542 fujii@postgresql.org 660 [ + + ]: 80 : if (appname != NULL)
661 : 23 : pfree(appname);
4770 tgl@sss.pgh.pa.us 662 : 80 : pfree(keywords);
663 : 80 : pfree(values);
664 : : }
665 : 9 : PG_CATCH();
666 : : {
1147 andres@anarazel.de 667 : 9 : libpqsrv_disconnect(conn);
4770 tgl@sss.pgh.pa.us 668 : 9 : PG_RE_THROW();
669 : : }
670 [ - + ]: 80 : PG_END_TRY();
671 : :
672 : 80 : return conn;
673 : : }
674 : :
675 : : /*
676 : : * Disconnect any open connection for a connection cache entry.
677 : : */
678 : : static void
3159 679 : 66 : disconnect_pg_server(ConnCacheEntry *entry)
680 : : {
681 [ + - ]: 66 : if (entry->conn != NULL)
682 : : {
1147 andres@anarazel.de 683 : 66 : libpqsrv_disconnect(entry->conn);
3159 tgl@sss.pgh.pa.us 684 : 66 : entry->conn = NULL;
685 : : }
686 : 66 : }
687 : :
688 : : /*
689 : : * Check and return the value of password_required, if defined; otherwise,
690 : : * return true, which is the default value of it. The mapping has been
691 : : * pre-validated.
692 : : */
693 : : static bool
2277 andrew@dunslane.net 694 : 18 : UserMappingPasswordRequired(UserMapping *user)
695 : : {
696 : : ListCell *cell;
697 : :
698 [ + + + + : 32 : foreach(cell, user->options)
+ + ]
699 : : {
700 : 17 : DefElem *def = (DefElem *) lfirst(cell);
701 : :
702 [ + + ]: 17 : if (strcmp(def->defname, "password_required") == 0)
703 : 3 : return defGetBoolean(def);
704 : : }
705 : :
706 : 15 : return true;
707 : : }
708 : :
709 : : static bool
424 peter@eisentraut.org 710 : 4 : UseScramPassthrough(ForeignServer *server, UserMapping *user)
711 : : {
712 : : ListCell *cell;
713 : :
714 [ + - + - : 16 : foreach(cell, server->options)
+ - ]
715 : : {
716 : 16 : DefElem *def = (DefElem *) lfirst(cell);
717 : :
718 [ + + ]: 16 : if (strcmp(def->defname, "use_scram_passthrough") == 0)
719 : 4 : return defGetBoolean(def);
720 : : }
721 : :
424 peter@eisentraut.org 722 [ # # # # :UBC 0 : foreach(cell, user->options)
# # ]
723 : : {
724 : 0 : DefElem *def = (DefElem *) lfirst(cell);
725 : :
726 [ # # ]: 0 : if (strcmp(def->defname, "use_scram_passthrough") == 0)
727 : 0 : return defGetBoolean(def);
728 : : }
729 : :
730 : 0 : return false;
731 : : }
732 : :
733 : : /*
734 : : * For non-superusers, insist that the connstr specify a password or that the
735 : : * user provided their own GSSAPI delegated credentials. This
736 : : * prevents a password from being picked up from .pgpass, a service file, the
737 : : * environment, etc. We don't want the postgres user's passwords,
738 : : * certificates, etc to be accessible to non-superusers. (See also
739 : : * dblink_connstr_check in contrib/dblink.)
740 : : */
741 : : static void
3022 rhaas@postgresql.org 742 :CBC 95 : check_conn_params(const char **keywords, const char **values, UserMapping *user)
743 : : {
744 : : int i;
745 : :
746 : : /* no check required if superuser */
747 [ + + ]: 95 : if (superuser_arg(user->userid))
4770 tgl@sss.pgh.pa.us 748 : 80 : return;
749 : :
750 : : #ifdef ENABLE_GSS
751 : : /* ok if the user provided their own delegated credentials */
1030 bruce@momjian.us 752 [ + + ]: 15 : if (be_gssapi_get_delegation(MyProcPort))
1067 sfrost@snowman.net 753 : 3 : return;
754 : : #endif
755 : :
756 : : /* ok if params contain a non-empty password */
4770 tgl@sss.pgh.pa.us 757 [ + + ]: 79 : for (i = 0; keywords[i] != NULL; i++)
758 : : {
759 [ + + + - ]: 70 : if (strcmp(keywords[i], "password") == 0 && values[i][0] != '\0')
760 : 3 : return;
761 : : }
762 : :
763 : : /* ok if the superuser explicitly said so at user mapping creation time */
2277 andrew@dunslane.net 764 [ + + ]: 9 : if (!UserMappingPasswordRequired(user))
765 : 1 : return;
766 : :
767 : : /*
768 : : * Ok if SCRAM pass-through is being used and all required scram options
769 : : * are set correctly. If pgfdw_has_required_scram_options returns true we
770 : : * assume that UseScramPassthrough is also true since SCRAM options are
771 : : * only set when UseScramPassthrough is enabled.
772 : : */
219 peter@eisentraut.org 773 [ + - + + : 8 : if (MyProcPort != NULL && MyProcPort->has_scram_keys && pgfdw_has_required_scram_options(keywords, values))
+ - ]
356 774 : 4 : return;
775 : :
4770 tgl@sss.pgh.pa.us 776 [ + - ]: 4 : ereport(ERROR,
777 : : (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
778 : : errmsg("password or GSSAPI delegated credentials required"),
779 : : errdetail("Non-superusers must delegate GSSAPI credentials, provide a password, or enable SCRAM pass-through in user mapping.")));
780 : : }
781 : :
782 : : /*
783 : : * Issue SET commands to make sure remote session is configured properly.
784 : : *
785 : : * We do this just once at connection, assuming nothing will change the
786 : : * values later. Since we'll never send volatile function calls to the
787 : : * remote, there shouldn't be any way to break this assumption from our end.
788 : : * It's possible to think of ways to break it at the remote end, eg making
789 : : * a foreign table point to a view that includes a set_config call ---
790 : : * but once you admit the possibility of a malicious view definition,
791 : : * there are any number of ways to break things.
792 : : */
793 : : static void
4769 794 : 80 : configure_remote_session(PGconn *conn)
795 : : {
4752 796 : 80 : int remoteversion = PQserverVersion(conn);
797 : :
798 : : /* Force the search path to contain only pg_catalog (see deparse.c) */
799 : 80 : do_sql_command(conn, "SET search_path = pg_catalog");
800 : :
801 : : /*
802 : : * Set remote timezone; this is basically just cosmetic, since all
803 : : * transmitted and returned timestamptzs should specify a zone explicitly
804 : : * anyway. However it makes the regression test outputs more predictable.
805 : : *
806 : : * We don't risk setting remote zone equal to ours, since the remote
807 : : * server might use a different timezone database. Instead, use GMT
808 : : * (quoted, because very old servers are picky about case). That's
809 : : * guaranteed to work regardless of the remote's timezone database,
810 : : * because pg_tzset() hard-wires it (at least in PG 9.2 and later).
811 : : */
693 812 : 80 : do_sql_command(conn, "SET timezone = 'GMT'");
813 : :
814 : : /*
815 : : * Set values needed to ensure unambiguous data output from remote. (This
816 : : * logic should match what pg_dump does. See also set_transmission_modes
817 : : * in postgres_fdw.c.)
818 : : */
4752 819 : 80 : do_sql_command(conn, "SET datestyle = ISO");
820 [ + - ]: 80 : if (remoteversion >= 80400)
821 : 80 : do_sql_command(conn, "SET intervalstyle = postgres");
822 [ + - ]: 80 : if (remoteversion >= 90000)
823 : 80 : do_sql_command(conn, "SET extra_float_digits = 3");
824 : : else
4752 tgl@sss.pgh.pa.us 825 :UBC 0 : do_sql_command(conn, "SET extra_float_digits = 2");
4752 tgl@sss.pgh.pa.us 826 :CBC 80 : }
827 : :
828 : : /*
829 : : * Convenience subroutine to issue a non-data-returning SQL command to remote
830 : : */
831 : : void
832 : 1881 : do_sql_command(PGconn *conn, const char *sql)
833 : : {
1480 efujita@postgresql.o 834 : 1881 : do_sql_command_begin(conn, sql);
835 : 1881 : do_sql_command_end(conn, sql, false);
836 : 1878 : }
837 : :
838 : : static void
839 : 1899 : do_sql_command_begin(PGconn *conn, const char *sql)
840 : : {
3203 rhaas@postgresql.org 841 [ - + ]: 1899 : if (!PQsendQuery(conn, sql))
229 tgl@sss.pgh.pa.us 842 :UNC 0 : pgfdw_report_error(NULL, conn, sql);
1480 efujita@postgresql.o 843 :CBC 1899 : }
844 : :
845 : : static void
846 : 1899 : do_sql_command_end(PGconn *conn, const char *sql, bool consume_input)
847 : : {
848 : : PGresult *res;
849 : :
850 : : /*
851 : : * If requested, consume whatever data is available from the socket. (Note
852 : : * that if all data is available, this allows pgfdw_get_result to call
853 : : * PQgetResult without forcing the overhead of WaitLatchOrSocket, which
854 : : * would be large compared to the overhead of PQconsumeInput.)
855 : : */
856 [ + + - + ]: 1899 : if (consume_input && !PQconsumeInput(conn))
229 tgl@sss.pgh.pa.us 857 :UNC 0 : pgfdw_report_error(NULL, conn, sql);
797 noah@leadboat.com 858 :CBC 1899 : res = pgfdw_get_result(conn);
4769 tgl@sss.pgh.pa.us 859 [ + + ]: 1899 : if (PQresultStatus(res) != PGRES_COMMAND_OK)
229 tgl@sss.pgh.pa.us 860 :GNC 3 : pgfdw_report_error(res, conn, sql);
4769 tgl@sss.pgh.pa.us 861 :CBC 1896 : PQclear(res);
862 : 1896 : }
863 : :
864 : : /*
865 : : * Start remote transaction or subtransaction, if needed.
866 : : *
867 : : * Note that we always use at least REPEATABLE READ in the remote session.
868 : : * This is so that, if a query initiates multiple scans of the same or
869 : : * different foreign tables, we will get snapshot-consistent results from
870 : : * those scans. A disadvantage is that we can't provide sane emulation of
871 : : * READ COMMITTED behavior --- it would be nice if we had some other way to
872 : : * control which remote queries share a snapshot.
873 : : */
874 : : static void
4770 875 : 2245 : begin_remote_xact(ConnCacheEntry *entry)
876 : : {
877 : 2245 : int curlevel = GetCurrentTransactionNestLevel();
878 : :
879 : : /* Start main transaction if we haven't yet */
880 [ + + ]: 2245 : if (entry->xact_depth <= 0)
881 : : {
882 : : const char *sql;
883 : :
884 [ - + ]: 759 : elog(DEBUG3, "starting remote transaction on connection %p",
885 : : entry->conn);
886 : :
887 [ - + ]: 759 : if (IsolationIsSerializable())
280 efujita@postgresql.o 888 :UBC 0 : sql = "START TRANSACTION ISOLATION LEVEL SERIALIZABLE";
889 : : else
280 efujita@postgresql.o 890 :CBC 759 : sql = "START TRANSACTION ISOLATION LEVEL REPEATABLE READ";
3203 rhaas@postgresql.org 891 : 759 : entry->changing_xact_state = true;
280 efujita@postgresql.o 892 : 759 : do_sql_command(entry->conn, sql);
4770 tgl@sss.pgh.pa.us 893 : 758 : entry->xact_depth = 1;
3203 rhaas@postgresql.org 894 : 758 : entry->changing_xact_state = false;
895 : : }
896 : :
897 : : /*
898 : : * If we're in a subtransaction, stack up savepoints to match our level.
899 : : * This ensures we can rollback just the desired effects when a
900 : : * subtransaction aborts.
901 : : */
4770 tgl@sss.pgh.pa.us 902 [ + + ]: 2258 : while (entry->xact_depth < curlevel)
903 : : {
904 : : char sql[64];
905 : :
280 efujita@postgresql.o 906 : 15 : snprintf(sql, sizeof(sql), "SAVEPOINT s%d", entry->xact_depth + 1);
3203 rhaas@postgresql.org 907 : 15 : entry->changing_xact_state = true;
280 efujita@postgresql.o 908 : 15 : do_sql_command(entry->conn, sql);
4770 tgl@sss.pgh.pa.us 909 : 14 : entry->xact_depth++;
3203 rhaas@postgresql.org 910 : 14 : entry->changing_xact_state = false;
911 : : }
4770 tgl@sss.pgh.pa.us 912 : 2243 : }
913 : :
914 : : /*
915 : : * Release connection reference count created by calling GetConnection.
916 : : */
917 : : void
918 : 2178 : ReleaseConnection(PGconn *conn)
919 : : {
920 : : /*
921 : : * Currently, we don't actually track connection references because all
922 : : * cleanup is managed on a transaction or subtransaction basis instead. So
923 : : * there's nothing to do here.
924 : : */
925 : 2178 : }
926 : :
927 : : /*
928 : : * Assign a "unique" number for a cursor.
929 : : *
930 : : * These really only need to be unique per connection within a transaction.
931 : : * For the moment we ignore the per-connection point and assign them across
932 : : * all connections in the transaction, but we ask for the connection to be
933 : : * supplied in case we want to refine that.
934 : : *
935 : : * Note that even if wraparound happens in a very long transaction, actual
936 : : * collisions are highly improbable; just be sure to use %u not %d to print.
937 : : */
938 : : unsigned int
939 : 555 : GetCursorNumber(PGconn *conn)
940 : : {
941 : 555 : return ++cursor_number;
942 : : }
943 : :
944 : : /*
945 : : * Assign a "unique" number for a prepared statement.
946 : : *
947 : : * This works much like GetCursorNumber, except that we never reset the counter
948 : : * within a session. That's because we can't be 100% sure we've gotten rid
949 : : * of all prepared statements on all connections, and it's not really worth
950 : : * increasing the risk of prepared-statement name collisions by resetting.
951 : : */
952 : : unsigned int
4753 953 : 187 : GetPrepStmtNumber(PGconn *conn)
954 : : {
955 : 187 : return ++prep_stmt_number;
956 : : }
957 : :
958 : : /*
959 : : * Submit a query and wait for the result.
960 : : *
961 : : * Since we don't use non-blocking mode, this can't process interrupts while
962 : : * pushing the query text to the server. That risk is relatively small, so we
963 : : * ignore that for now.
964 : : *
965 : : * Caller is responsible for the error handling on the result.
966 : : */
967 : : PGresult *
1810 efujita@postgresql.o 968 : 4142 : pgfdw_exec_query(PGconn *conn, const char *query, PgFdwConnState *state)
969 : : {
970 : : /* First, process a pending asynchronous request, if any. */
971 [ + + + + ]: 4142 : if (state && state->pendingAreq)
972 : 4 : process_pending_request(state->pendingAreq);
973 : :
3615 rhaas@postgresql.org 974 [ - + ]: 4142 : if (!PQsendQuery(conn, query))
797 noah@leadboat.com 975 :UBC 0 : return NULL;
797 noah@leadboat.com 976 :CBC 4142 : return pgfdw_get_result(conn);
977 : : }
978 : :
979 : : /*
980 : : * Wrap libpqsrv_get_result_last(), adding wait event.
981 : : *
982 : : * Caller is responsible for the error handling on the result.
983 : : */
984 : : PGresult *
985 : 8344 : pgfdw_get_result(PGconn *conn)
986 : : {
987 : 8344 : return libpqsrv_get_result_last(conn, pgfdw_we_get_result);
988 : : }
989 : :
990 : : /*
991 : : * Report an error we got from the remote server.
992 : : *
993 : : * Callers should use pgfdw_report_error() to throw an error, or use
994 : : * pgfdw_report() for lesser message levels. (We make this distinction
995 : : * so that pgfdw_report_error() can be marked noreturn.)
996 : : *
997 : : * res: PGresult containing the error (might be NULL)
998 : : * conn: connection we did the query on
999 : : * sql: NULL, or text of remote command we tried to execute
1000 : : *
1001 : : * If "res" is not NULL, it'll be PQclear'ed here (unless we throw error,
1002 : : * in which case memory context cleanup will clear it eventually).
1003 : : *
1004 : : * Note: callers that choose not to throw ERROR for a remote error are
1005 : : * responsible for making sure that the associated ConnCacheEntry gets
1006 : : * marked with have_error = true.
1007 : : */
1008 : : void
229 tgl@sss.pgh.pa.us 1009 :GNC 16 : pgfdw_report_error(PGresult *res, PGconn *conn, const char *sql)
1010 : : {
1011 : 16 : pgfdw_report_internal(ERROR, res, conn, sql);
229 tgl@sss.pgh.pa.us 1012 :UNC 0 : pg_unreachable();
1013 : : }
1014 : :
1015 : : void
1016 : 0 : pgfdw_report(int elevel, PGresult *res, PGconn *conn, const char *sql)
1017 : : {
1018 [ # # ]: 0 : Assert(elevel < ERROR); /* use pgfdw_report_error for that */
1019 : 0 : pgfdw_report_internal(elevel, res, conn, sql);
1020 : 0 : }
1021 : :
1022 : : static void
229 tgl@sss.pgh.pa.us 1023 :GNC 16 : pgfdw_report_internal(int elevel, PGresult *res, PGconn *conn,
1024 : : const char *sql)
1025 : : {
233 1026 : 16 : char *diag_sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
1027 : 16 : char *message_primary = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
1028 : 16 : char *message_detail = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL);
1029 : 16 : char *message_hint = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT);
1030 : 16 : char *message_context = PQresultErrorField(res, PG_DIAG_CONTEXT);
1031 : : int sqlstate;
1032 : :
1033 [ + + ]: 16 : if (diag_sqlstate)
1034 : 14 : sqlstate = MAKE_SQLSTATE(diag_sqlstate[0],
1035 : : diag_sqlstate[1],
1036 : : diag_sqlstate[2],
1037 : : diag_sqlstate[3],
1038 : : diag_sqlstate[4]);
1039 : : else
1040 : 2 : sqlstate = ERRCODE_CONNECTION_FAILURE;
1041 : :
1042 : : /*
1043 : : * If we don't get a message from the PGresult, try the PGconn. This is
1044 : : * needed because for connection-level failures, PQgetResult may just
1045 : : * return NULL, not a PGresult at all.
1046 : : */
1047 [ + + ]: 16 : if (message_primary == NULL)
1048 : 2 : message_primary = pchomp(PQerrorMessage(conn));
1049 : :
1050 [ + - + - : 16 : ereport(elevel,
+ - + + +
+ - + +
- ]
1051 : : (errcode(sqlstate),
1052 : : (message_primary != NULL && message_primary[0] != '\0') ?
1053 : : errmsg_internal("%s", message_primary) :
1054 : : errmsg("could not obtain message string for remote error"),
1055 : : message_detail ? errdetail_internal("%s", message_detail) : 0,
1056 : : message_hint ? errhint("%s", message_hint) : 0,
1057 : : message_context ? errcontext("%s", message_context) : 0,
1058 : : sql ? errcontext("remote SQL command: %s", sql) : 0));
233 tgl@sss.pgh.pa.us 1059 :UNC 0 : PQclear(res);
4770 tgl@sss.pgh.pa.us 1060 :UBC 0 : }
1061 : :
1062 : : /*
1063 : : * pgfdw_xact_callback --- cleanup at main-transaction end.
1064 : : *
1065 : : * This runs just late enough that it must not enter user-defined code
1066 : : * locally. (Entering such code on the remote side is fine. Its remote
1067 : : * COMMIT TRANSACTION may run deferred triggers.)
1068 : : */
1069 : : static void
4770 tgl@sss.pgh.pa.us 1070 :CBC 4093 : pgfdw_xact_callback(XactEvent event, void *arg)
1071 : : {
1072 : : HASH_SEQ_STATUS scan;
1073 : : ConnCacheEntry *entry;
1480 efujita@postgresql.o 1074 : 4093 : List *pending_entries = NIL;
1074 1075 : 4093 : List *cancel_requested = NIL;
1076 : :
1077 : : /* Quick exit if no connections were touched in this transaction. */
4770 tgl@sss.pgh.pa.us 1078 [ + + ]: 4093 : if (!xact_got_connection)
1079 : 3363 : return;
1080 : :
1081 : : /*
1082 : : * Scan all connection cache entries to find open remote transactions, and
1083 : : * close them.
1084 : : */
1085 : 730 : hash_seq_init(&scan, ConnectionHash);
1086 [ + + ]: 3737 : while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
1087 : : {
1088 : : PGresult *res;
1089 : :
1090 : : /* Ignore cache entry if no open connection right now */
4423 1091 [ + + ]: 3008 : if (entry->conn == NULL)
4770 1092 : 1711 : continue;
1093 : :
1094 : : /* If it has an open remote transaction, try to close it */
4423 1095 [ + + ]: 1297 : if (entry->xact_depth > 0)
1096 : : {
1097 [ - + ]: 759 : elog(DEBUG3, "closing remote transaction on connection %p",
1098 : : entry->conn);
1099 : :
1100 [ + + - + : 759 : switch (event)
- ]
1101 : : {
3972 rhaas@postgresql.org 1102 : 706 : case XACT_EVENT_PARALLEL_PRE_COMMIT:
1103 : : case XACT_EVENT_PRE_COMMIT:
1104 : :
1105 : : /*
1106 : : * If abort cleanup previously failed for this connection,
1107 : : * we can't issue any more commands against it.
1108 : : */
3203 1109 : 706 : pgfdw_reject_incomplete_xact_state_change(entry);
1110 : :
1111 : : /* Commit all remote transactions during pre-commit */
1112 : 706 : entry->changing_xact_state = true;
1480 efujita@postgresql.o 1113 [ + + ]: 706 : if (entry->parallel_commit)
1114 : : {
1115 : 16 : do_sql_command_begin(entry->conn, "COMMIT TRANSACTION");
1116 : 16 : pending_entries = lappend(pending_entries, entry);
1117 : 16 : continue;
1118 : : }
4423 tgl@sss.pgh.pa.us 1119 : 690 : do_sql_command(entry->conn, "COMMIT TRANSACTION");
3203 rhaas@postgresql.org 1120 : 690 : entry->changing_xact_state = false;
1121 : :
1122 : : /*
1123 : : * If there were any errors in subtransactions, and we
1124 : : * made prepared statements, do a DEALLOCATE ALL to make
1125 : : * sure we get rid of all prepared statements. This is
1126 : : * annoying and not terribly bulletproof, but it's
1127 : : * probably not worth trying harder.
1128 : : *
1129 : : * DEALLOCATE ALL only exists in 8.3 and later, so this
1130 : : * constrains how old a server postgres_fdw can
1131 : : * communicate with. We intentionally ignore errors in
1132 : : * the DEALLOCATE, so that we can hobble along to some
1133 : : * extent with older servers (leaking prepared statements
1134 : : * as we go; but we don't really support update operations
1135 : : * pre-8.3 anyway).
1136 : : */
4753 tgl@sss.pgh.pa.us 1137 [ + + - + ]: 690 : if (entry->have_prep_stmt && entry->have_error)
1138 : : {
797 noah@leadboat.com 1139 :UBC 0 : res = pgfdw_exec_query(entry->conn, "DEALLOCATE ALL",
1140 : : NULL);
4753 tgl@sss.pgh.pa.us 1141 : 0 : PQclear(res);
1142 : : }
4753 tgl@sss.pgh.pa.us 1143 :CBC 690 : entry->have_prep_stmt = false;
1144 : 690 : entry->have_error = false;
4423 1145 : 690 : break;
1146 : 1 : case XACT_EVENT_PRE_PREPARE:
1147 : :
1148 : : /*
1149 : : * We disallow any remote transactions, since it's not
1150 : : * very reasonable to hold them open until the prepared
1151 : : * transaction is committed. For the moment, throw error
1152 : : * unconditionally; later we might allow read-only cases.
1153 : : * Note that the error will cause us to come right back
1154 : : * here with event == XACT_EVENT_ABORT, so we'll clean up
1155 : : * the connection state at that point.
1156 : : */
1157 [ + - ]: 1 : ereport(ERROR,
1158 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1159 : : errmsg("cannot PREPARE a transaction that has operated on postgres_fdw foreign tables")));
1160 : : break;
3972 rhaas@postgresql.org 1161 :UBC 0 : case XACT_EVENT_PARALLEL_COMMIT:
1162 : : case XACT_EVENT_COMMIT:
1163 : : case XACT_EVENT_PREPARE:
1164 : : /* Pre-commit should have closed the open transaction */
4423 tgl@sss.pgh.pa.us 1165 [ # # ]: 0 : elog(ERROR, "missed cleaning up connection during pre-commit");
1166 : : break;
3972 rhaas@postgresql.org 1167 :CBC 52 : case XACT_EVENT_PARALLEL_ABORT:
1168 : : case XACT_EVENT_ABORT:
1169 : : /* Rollback all remote transactions during abort */
1074 efujita@postgresql.o 1170 [ + + ]: 52 : if (entry->parallel_abort)
1171 : : {
1172 [ + - ]: 4 : if (pgfdw_abort_cleanup_begin(entry, true,
1173 : : &pending_entries,
1174 : : &cancel_requested))
1175 : 4 : continue;
1176 : : }
1177 : : else
1178 : 48 : pgfdw_abort_cleanup(entry, true);
4423 tgl@sss.pgh.pa.us 1179 : 48 : break;
1180 : : }
1181 : : }
1182 : :
1183 : : /* Reset state to show we're out of a transaction */
1480 efujita@postgresql.o 1184 : 1276 : pgfdw_reset_xact_state(entry, true);
1185 : : }
1186 : :
1187 : : /* If there are any pending connections, finish cleaning them up */
1074 1188 [ + + - + ]: 729 : if (pending_entries || cancel_requested)
1189 : : {
1190 [ + - + + ]: 15 : if (event == XACT_EVENT_PARALLEL_PRE_COMMIT ||
1191 : : event == XACT_EVENT_PRE_COMMIT)
1192 : : {
1193 [ - + ]: 13 : Assert(cancel_requested == NIL);
1194 : 13 : pgfdw_finish_pre_commit_cleanup(pending_entries);
1195 : : }
1196 : : else
1197 : : {
1198 [ + - - + ]: 2 : Assert(event == XACT_EVENT_PARALLEL_ABORT ||
1199 : : event == XACT_EVENT_ABORT);
1200 : 2 : pgfdw_finish_abort_cleanup(pending_entries, cancel_requested,
1201 : : true);
1202 : : }
1203 : : }
1204 : :
1205 : : /*
1206 : : * Regardless of the event type, we can now mark ourselves as out of the
1207 : : * transaction. (Note: if we are here during PRE_COMMIT or PRE_PREPARE,
1208 : : * this saves a useless scan of the hashtable during COMMIT or PREPARE.)
1209 : : */
4770 tgl@sss.pgh.pa.us 1210 : 729 : xact_got_connection = false;
1211 : :
1212 : : /* Also reset cursor numbering for next transaction */
1213 : 729 : cursor_number = 0;
1214 : : }
1215 : :
1216 : : /*
1217 : : * pgfdw_subxact_callback --- cleanup at subtransaction end.
1218 : : */
1219 : : static void
1220 : 38 : pgfdw_subxact_callback(SubXactEvent event, SubTransactionId mySubid,
1221 : : SubTransactionId parentSubid, void *arg)
1222 : : {
1223 : : HASH_SEQ_STATUS scan;
1224 : : ConnCacheEntry *entry;
1225 : : int curlevel;
1480 efujita@postgresql.o 1226 : 38 : List *pending_entries = NIL;
1074 1227 : 38 : List *cancel_requested = NIL;
1228 : :
1229 : : /* Nothing to do at subxact start, nor after commit. */
4770 tgl@sss.pgh.pa.us 1230 [ + + + + ]: 38 : if (!(event == SUBXACT_EVENT_PRE_COMMIT_SUB ||
1231 : : event == SUBXACT_EVENT_ABORT_SUB))
1232 : 23 : return;
1233 : :
1234 : : /* Quick exit if no connections were touched in this transaction. */
1235 [ - + ]: 15 : if (!xact_got_connection)
4770 tgl@sss.pgh.pa.us 1236 :UBC 0 : return;
1237 : :
1238 : : /*
1239 : : * Scan all connection cache entries to find open remote subtransactions
1240 : : * of the current level, and close them.
1241 : : */
4770 tgl@sss.pgh.pa.us 1242 :CBC 15 : curlevel = GetCurrentTransactionNestLevel();
1243 : 15 : hash_seq_init(&scan, ConnectionHash);
1244 [ + + ]: 102 : while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
1245 : : {
1246 : : char sql[100];
1247 : :
1248 : : /*
1249 : : * We only care about connections with open remote subtransactions of
1250 : : * the current level.
1251 : : */
1252 [ + + + + ]: 87 : if (entry->conn == NULL || entry->xact_depth < curlevel)
1253 : 79 : continue;
1254 : :
1255 [ - + ]: 14 : if (entry->xact_depth > curlevel)
4770 tgl@sss.pgh.pa.us 1256 [ # # ]:UBC 0 : elog(ERROR, "missed cleaning up remote subtransaction at level %d",
1257 : : entry->xact_depth);
1258 : :
4770 tgl@sss.pgh.pa.us 1259 [ + + ]:CBC 14 : if (event == SUBXACT_EVENT_PRE_COMMIT_SUB)
1260 : : {
1261 : : /*
1262 : : * If abort cleanup previously failed for this connection, we
1263 : : * can't issue any more commands against it.
1264 : : */
3203 rhaas@postgresql.org 1265 : 7 : pgfdw_reject_incomplete_xact_state_change(entry);
1266 : :
1267 : : /* Commit all remote subtransactions during pre-commit */
4770 tgl@sss.pgh.pa.us 1268 : 7 : snprintf(sql, sizeof(sql), "RELEASE SAVEPOINT s%d", curlevel);
3203 rhaas@postgresql.org 1269 : 7 : entry->changing_xact_state = true;
1480 efujita@postgresql.o 1270 [ + + ]: 7 : if (entry->parallel_commit)
1271 : : {
1272 : 2 : do_sql_command_begin(entry->conn, sql);
1273 : 2 : pending_entries = lappend(pending_entries, entry);
1274 : 2 : continue;
1275 : : }
4752 tgl@sss.pgh.pa.us 1276 : 5 : do_sql_command(entry->conn, sql);
3203 rhaas@postgresql.org 1277 : 5 : entry->changing_xact_state = false;
1278 : : }
1279 : : else
1280 : : {
1281 : : /* Rollback all remote subtransactions during abort */
1074 efujita@postgresql.o 1282 [ + + ]: 7 : if (entry->parallel_abort)
1283 : : {
1284 [ + - ]: 4 : if (pgfdw_abort_cleanup_begin(entry, false,
1285 : : &pending_entries,
1286 : : &cancel_requested))
1287 : 4 : continue;
1288 : : }
1289 : : else
1290 : 3 : pgfdw_abort_cleanup(entry, false);
1291 : : }
1292 : :
1293 : : /* OK, we're outta that level of subtransaction */
1480 1294 : 8 : pgfdw_reset_xact_state(entry, false);
1295 : : }
1296 : :
1297 : : /* If there are any pending connections, finish cleaning them up */
1074 1298 [ + + - + ]: 15 : if (pending_entries || cancel_requested)
1299 : : {
1300 [ + + ]: 3 : if (event == SUBXACT_EVENT_PRE_COMMIT_SUB)
1301 : : {
1302 [ - + ]: 1 : Assert(cancel_requested == NIL);
1303 : 1 : pgfdw_finish_pre_subcommit_cleanup(pending_entries, curlevel);
1304 : : }
1305 : : else
1306 : : {
1307 [ - + ]: 2 : Assert(event == SUBXACT_EVENT_ABORT_SUB);
1308 : 2 : pgfdw_finish_abort_cleanup(pending_entries, cancel_requested,
1309 : : false);
1310 : : }
1311 : : }
1312 : : }
1313 : :
1314 : : /*
1315 : : * Connection invalidation callback function
1316 : : *
1317 : : * After a change to a pg_foreign_server or pg_user_mapping catalog entry,
1318 : : * close connections depending on that entry immediately if current transaction
1319 : : * has not used those connections yet. Otherwise, mark those connections as
1320 : : * invalid and then make pgfdw_xact_callback() close them at the end of current
1321 : : * transaction, since they cannot be closed in the midst of the transaction
1322 : : * using them. Closed connections will be remade at the next opportunity if
1323 : : * necessary.
1324 : : *
1325 : : * Although most cache invalidation callbacks blow away all the related stuff
1326 : : * regardless of the given hashvalue, connections are expensive enough that
1327 : : * it's worth trying to avoid that.
1328 : : *
1329 : : * NB: We could avoid unnecessary disconnection more strictly by examining
1330 : : * individual option values, but it seems too much effort for the gain.
1331 : : */
1332 : : static void
25 michael@paquier.xyz 1333 :GNC 188 : pgfdw_inval_callback(Datum arg, SysCacheIdentifier cacheid, uint32 hashvalue)
1334 : : {
1335 : : HASH_SEQ_STATUS scan;
1336 : : ConnCacheEntry *entry;
1337 : :
3159 tgl@sss.pgh.pa.us 1338 [ + + - + ]:CBC 188 : Assert(cacheid == FOREIGNSERVEROID || cacheid == USERMAPPINGOID);
1339 : :
1340 : : /* ConnectionHash must exist already, if we're registered */
1341 : 188 : hash_seq_init(&scan, ConnectionHash);
1342 [ + + ]: 1222 : while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
1343 : : {
1344 : : /* Ignore invalid entries */
1345 [ + + ]: 1034 : if (entry->conn == NULL)
1346 : 839 : continue;
1347 : :
1348 : : /* hashvalue == 0 means a cache reset, must clear all state */
1349 [ + - + + ]: 195 : if (hashvalue == 0 ||
1350 : 139 : (cacheid == FOREIGNSERVEROID &&
1351 [ + + + + ]: 195 : entry->server_hashvalue == hashvalue) ||
1352 : 56 : (cacheid == USERMAPPINGOID &&
1353 [ + + ]: 56 : entry->mapping_hashvalue == hashvalue))
1354 : : {
1355 : : /*
1356 : : * Close the connection immediately if it's not used yet in this
1357 : : * transaction. Otherwise mark it as invalid so that
1358 : : * pgfdw_xact_callback() can close it at the end of this
1359 : : * transaction.
1360 : : */
1903 fujii@postgresql.org 1361 [ + + ]: 58 : if (entry->xact_depth == 0)
1362 : : {
1363 [ - + ]: 55 : elog(DEBUG3, "discarding connection %p", entry->conn);
1364 : 55 : disconnect_pg_server(entry);
1365 : : }
1366 : : else
1367 : 3 : entry->invalidated = true;
1368 : : }
1369 : : }
3159 tgl@sss.pgh.pa.us 1370 : 188 : }
1371 : :
1372 : : /*
1373 : : * Raise an error if the given connection cache entry is marked as being
1374 : : * in the middle of an xact state change. This should be called at which no
1375 : : * such change is expected to be in progress; if one is found to be in
1376 : : * progress, it means that we aborted in the middle of a previous state change
1377 : : * and now don't know what the remote transaction state actually is.
1378 : : * Such connections can't safely be further used. Re-establishing the
1379 : : * connection would change the snapshot and roll back any writes already
1380 : : * performed, so that's not an option, either. Thus, we must abort.
1381 : : */
1382 : : static void
3203 rhaas@postgresql.org 1383 : 2966 : pgfdw_reject_incomplete_xact_state_change(ConnCacheEntry *entry)
1384 : : {
1385 : : ForeignServer *server;
1386 : :
1387 : : /* nothing to do for inactive entries and entries of sane state */
3159 tgl@sss.pgh.pa.us 1388 [ + + + - ]: 2966 : if (entry->conn == NULL || !entry->changing_xact_state)
3203 rhaas@postgresql.org 1389 : 2966 : return;
1390 : :
1391 : : /* make sure this entry is inactive */
3159 tgl@sss.pgh.pa.us 1392 :UBC 0 : disconnect_pg_server(entry);
1393 : :
1394 : : /* find server name to be shown in the message below */
1885 fujii@postgresql.org 1395 : 0 : server = GetForeignServer(entry->serverid);
1396 : :
3203 rhaas@postgresql.org 1397 [ # # ]: 0 : ereport(ERROR,
1398 : : (errcode(ERRCODE_CONNECTION_EXCEPTION),
1399 : : errmsg("connection to server \"%s\" was lost",
1400 : : server->servername)));
1401 : : }
1402 : :
1403 : : /*
1404 : : * Reset state to show we're out of a (sub)transaction.
1405 : : */
1406 : : static void
1480 efujita@postgresql.o 1407 :CBC 1310 : pgfdw_reset_xact_state(ConnCacheEntry *entry, bool toplevel)
1408 : : {
1409 [ + + ]: 1310 : if (toplevel)
1410 : : {
1411 : : /* Reset state to show we're out of a transaction */
1412 : 1296 : entry->xact_depth = 0;
1413 : :
1414 : : /*
1415 : : * If the connection isn't in a good idle state, it is marked as
1416 : : * invalid or keep_connections option of its server is disabled, then
1417 : : * discard it to recover. Next GetConnection will open a new
1418 : : * connection.
1419 : : */
1420 [ + + + - ]: 2591 : if (PQstatus(entry->conn) != CONNECTION_OK ||
1421 : 1295 : PQtransactionStatus(entry->conn) != PQTRANS_IDLE ||
1422 [ + - ]: 1295 : entry->changing_xact_state ||
1423 [ + + ]: 1295 : entry->invalidated ||
1424 [ + + ]: 1293 : !entry->keep_connections)
1425 : : {
1426 [ - + ]: 4 : elog(DEBUG3, "discarding connection %p", entry->conn);
1427 : 4 : disconnect_pg_server(entry);
1428 : : }
1429 : : }
1430 : : else
1431 : : {
1432 : : /* Reset state to show we're out of a subtransaction */
1433 : 14 : entry->xact_depth--;
1434 : : }
1435 : 1310 : }
1436 : :
1437 : : /*
1438 : : * Cancel the currently-in-progress query (whose query text we do not have)
1439 : : * and ignore the result. Returns true if we successfully cancel the query
1440 : : * and discard any pending result, and false if not.
1441 : : *
1442 : : * It's not a huge problem if we throw an ERROR here, but if we get into error
1443 : : * recursion trouble, we'll end up slamming the connection shut, which will
1444 : : * necessitate failing the entire toplevel transaction even if subtransactions
1445 : : * were used. Try to use WARNING where we can.
1446 : : *
1447 : : * XXX: if the query was one sent by fetch_more_data_begin(), we could get the
1448 : : * query text from the pendingAreq saved in the per-connection state, then
1449 : : * report the query using it.
1450 : : */
1451 : : static bool
3203 rhaas@postgresql.org 1452 : 2 : pgfdw_cancel_query(PGconn *conn)
1453 : : {
447 tgl@sss.pgh.pa.us 1454 : 2 : TimestampTz now = GetCurrentTimestamp();
1455 : : TimestampTz endtime;
1456 : : TimestampTz retrycanceltime;
1457 : :
1458 : : /*
1459 : : * If it takes too long to cancel the query and discard the result, assume
1460 : : * the connection is dead.
1461 : : */
1462 : 2 : endtime = TimestampTzPlusMilliseconds(now, CONNECTION_CLEANUP_TIMEOUT);
1463 : :
1464 : : /*
1465 : : * Also, lose patience and re-issue the cancel request after a little bit.
1466 : : * (This serves to close some race conditions.)
1467 : : */
1468 : 2 : retrycanceltime = TimestampTzPlusMilliseconds(now, RETRY_CANCEL_TIMEOUT);
1469 : :
717 alvherre@alvh.no-ip. 1470 [ - + ]: 2 : if (!pgfdw_cancel_query_begin(conn, endtime))
1074 efujita@postgresql.o 1471 :UBC 0 : return false;
447 tgl@sss.pgh.pa.us 1472 :CBC 2 : return pgfdw_cancel_query_end(conn, endtime, retrycanceltime, false);
1473 : : }
1474 : :
1475 : : /*
1476 : : * Submit a cancel request to the given connection, waiting only until
1477 : : * the given time.
1478 : : *
1479 : : * We sleep interruptibly until we receive confirmation that the cancel
1480 : : * request has been accepted, and if it is, return true; if the timeout
1481 : : * lapses without that, or the request fails for whatever reason, return
1482 : : * false.
1483 : : */
1484 : : static bool
717 alvherre@alvh.no-ip. 1485 : 2 : pgfdw_cancel_query_begin(PGconn *conn, TimestampTz endtime)
1486 : : {
709 1487 : 2 : const char *errormsg = libpqsrv_cancel(conn, endtime);
1488 : :
717 1489 [ - + ]: 2 : if (errormsg != NULL)
717 alvherre@alvh.no-ip. 1490 [ # # ]:UBC 0 : ereport(WARNING,
1491 : : errcode(ERRCODE_CONNECTION_FAILURE),
1492 : : errmsg("could not send cancel request: %s", errormsg));
1493 : :
717 alvherre@alvh.no-ip. 1494 :CBC 2 : return errormsg == NULL;
1495 : : }
1496 : :
1497 : : static bool
447 tgl@sss.pgh.pa.us 1498 : 2 : pgfdw_cancel_query_end(PGconn *conn, TimestampTz endtime,
1499 : : TimestampTz retrycanceltime, bool consume_input)
1500 : : {
1501 : : PGresult *result;
1502 : : bool timed_out;
1503 : :
1504 : : /*
1505 : : * If requested, consume whatever data is available from the socket. (Note
1506 : : * that if all data is available, this allows pgfdw_get_cleanup_result to
1507 : : * call PQgetResult without forcing the overhead of WaitLatchOrSocket,
1508 : : * which would be large compared to the overhead of PQconsumeInput.)
1509 : : */
1074 efujita@postgresql.o 1510 [ - + - - ]: 2 : if (consume_input && !PQconsumeInput(conn))
1511 : : {
1074 efujita@postgresql.o 1512 [ # # ]:UBC 0 : ereport(WARNING,
1513 : : (errcode(ERRCODE_CONNECTION_FAILURE),
1514 : : errmsg("could not get result of cancel request: %s",
1515 : : pchomp(PQerrorMessage(conn)))));
1516 : 0 : return false;
1517 : : }
1518 : :
1519 : : /* Get and discard the result of the query. */
447 tgl@sss.pgh.pa.us 1520 [ - + ]:CBC 2 : if (pgfdw_get_cleanup_result(conn, endtime, retrycanceltime,
1521 : : &result, &timed_out))
1522 : : {
1558 fujii@postgresql.org 1523 [ # # ]:UBC 0 : if (timed_out)
1524 [ # # ]: 0 : ereport(WARNING,
1525 : : (errmsg("could not get result of cancel request due to timeout")));
1526 : : else
1527 [ # # ]: 0 : ereport(WARNING,
1528 : : (errcode(ERRCODE_CONNECTION_FAILURE),
1529 : : errmsg("could not get result of cancel request: %s",
1530 : : pchomp(PQerrorMessage(conn)))));
1531 : :
3203 rhaas@postgresql.org 1532 : 0 : return false;
1533 : : }
3203 rhaas@postgresql.org 1534 :CBC 2 : PQclear(result);
1535 : :
1536 : 2 : return true;
1537 : : }
1538 : :
1539 : : /*
1540 : : * Submit a query during (sub)abort cleanup and wait up to 30 seconds for the
1541 : : * result. If the query is executed without error, the return value is true.
1542 : : * If the query is executed successfully but returns an error, the return
1543 : : * value is true if and only if ignore_errors is set. If the query can't be
1544 : : * sent or times out, the return value is false.
1545 : : *
1546 : : * It's not a huge problem if we throw an ERROR here, but if we get into error
1547 : : * recursion trouble, we'll end up slamming the connection shut, which will
1548 : : * necessitate failing the entire toplevel transaction even if subtransactions
1549 : : * were used. Try to use WARNING where we can.
1550 : : */
1551 : : static bool
1552 : 75 : pgfdw_exec_cleanup_query(PGconn *conn, const char *query, bool ignore_errors)
1553 : : {
1554 : : TimestampTz endtime;
1555 : :
1556 : : /*
1557 : : * If it takes too long to execute a cleanup query, assume the connection
1558 : : * is dead. It's fairly likely that this is why we aborted in the first
1559 : : * place (e.g. statement timeout, user cancel), so the timeout shouldn't
1560 : : * be too long.
1561 : : */
1074 efujita@postgresql.o 1562 : 75 : endtime = TimestampTzPlusMilliseconds(GetCurrentTimestamp(),
1563 : : CONNECTION_CLEANUP_TIMEOUT);
1564 : :
1565 [ - + ]: 75 : if (!pgfdw_exec_cleanup_query_begin(conn, query))
1074 efujita@postgresql.o 1566 :UBC 0 : return false;
1074 efujita@postgresql.o 1567 :CBC 75 : return pgfdw_exec_cleanup_query_end(conn, query, endtime,
1568 : : false, ignore_errors);
1569 : : }
1570 : :
1571 : : static bool
1572 : 87 : pgfdw_exec_cleanup_query_begin(PGconn *conn, const char *query)
1573 : : {
710 1574 [ - + ]: 87 : Assert(query != NULL);
1575 : :
1576 : : /*
1577 : : * Submit a query. Since we don't use non-blocking mode, this also can
1578 : : * block. But its risk is relatively small, so we ignore that for now.
1579 : : */
3203 rhaas@postgresql.org 1580 [ - + ]: 87 : if (!PQsendQuery(conn, query))
1581 : : {
229 tgl@sss.pgh.pa.us 1582 :UNC 0 : pgfdw_report(WARNING, NULL, conn, query);
3203 rhaas@postgresql.org 1583 :UBC 0 : return false;
1584 : : }
1585 : :
1074 efujita@postgresql.o 1586 :CBC 87 : return true;
1587 : : }
1588 : :
1589 : : static bool
1590 : 87 : pgfdw_exec_cleanup_query_end(PGconn *conn, const char *query,
1591 : : TimestampTz endtime, bool consume_input,
1592 : : bool ignore_errors)
1593 : : {
1594 : : PGresult *result;
1595 : : bool timed_out;
1596 : :
710 1597 [ - + ]: 87 : Assert(query != NULL);
1598 : :
1599 : : /*
1600 : : * If requested, consume whatever data is available from the socket. (Note
1601 : : * that if all data is available, this allows pgfdw_get_cleanup_result to
1602 : : * call PQgetResult without forcing the overhead of WaitLatchOrSocket,
1603 : : * which would be large compared to the overhead of PQconsumeInput.)
1604 : : */
1074 1605 [ + + - + ]: 87 : if (consume_input && !PQconsumeInput(conn))
1606 : : {
229 tgl@sss.pgh.pa.us 1607 :UNC 0 : pgfdw_report(WARNING, NULL, conn, query);
1074 efujita@postgresql.o 1608 :UBC 0 : return false;
1609 : : }
1610 : :
1611 : : /* Get the result of the query. */
447 tgl@sss.pgh.pa.us 1612 [ - + ]:CBC 87 : if (pgfdw_get_cleanup_result(conn, endtime, endtime, &result, &timed_out))
1613 : : {
1558 fujii@postgresql.org 1614 [ # # ]:UBC 0 : if (timed_out)
1615 [ # # ]: 0 : ereport(WARNING,
1616 : : (errmsg("could not get query result due to timeout"),
1617 : : errcontext("remote SQL command: %s", query)));
1618 : : else
229 tgl@sss.pgh.pa.us 1619 :UNC 0 : pgfdw_report(WARNING, NULL, conn, query);
1620 : :
3203 rhaas@postgresql.org 1621 :UBC 0 : return false;
1622 : : }
1623 : :
1624 : : /* Issue a warning if not successful. */
3203 rhaas@postgresql.org 1625 [ - + ]:CBC 87 : if (PQresultStatus(result) != PGRES_COMMAND_OK)
1626 : : {
229 tgl@sss.pgh.pa.us 1627 :UNC 0 : pgfdw_report(WARNING, result, conn, query);
3203 rhaas@postgresql.org 1628 :UBC 0 : return ignore_errors;
1629 : : }
3195 tgl@sss.pgh.pa.us 1630 :CBC 87 : PQclear(result);
1631 : :
3203 rhaas@postgresql.org 1632 : 87 : return true;
1633 : : }
1634 : :
1635 : : /*
1636 : : * Get, during abort cleanup, the result of a query that is in progress.
1637 : : * This might be a query that is being interrupted by a cancel request or by
1638 : : * transaction abort, or it might be a query that was initiated as part of
1639 : : * transaction abort to get the remote side back to the appropriate state.
1640 : : *
1641 : : * endtime is the time at which we should give up and assume the remote side
1642 : : * is dead. retrycanceltime is the time at which we should issue a fresh
1643 : : * cancel request (pass the same value as endtime if this is not wanted).
1644 : : *
1645 : : * Returns true if the timeout expired or connection trouble occurred,
1646 : : * false otherwise. Sets *result except in case of a true result.
1647 : : * Sets *timed_out to true only when the timeout expired.
1648 : : */
1649 : : static bool
447 tgl@sss.pgh.pa.us 1650 : 89 : pgfdw_get_cleanup_result(PGconn *conn, TimestampTz endtime,
1651 : : TimestampTz retrycanceltime,
1652 : : PGresult **result,
1653 : : bool *timed_out)
1654 : : {
233 tgl@sss.pgh.pa.us 1655 :GNC 89 : bool failed = false;
1656 : 89 : PGresult *last_res = NULL;
1657 : 89 : int canceldelta = RETRY_CANCEL_TIMEOUT * 2;
1658 : :
447 tgl@sss.pgh.pa.us 1659 :CBC 89 : *result = NULL;
1558 fujii@postgresql.org 1660 : 89 : *timed_out = false;
1661 : : for (;;)
233 tgl@sss.pgh.pa.us 1662 :GIC 96 : {
1663 : : PGresult *res;
1664 : :
233 tgl@sss.pgh.pa.us 1665 [ + + ]:GNC 269 : while (PQisBusy(conn))
3203 rhaas@postgresql.org 1666 :ECB (96) : {
1667 : : int wc;
233 tgl@sss.pgh.pa.us 1668 :GNC 84 : TimestampTz now = GetCurrentTimestamp();
1669 : : long cur_timeout;
1670 : :
1671 : : /* If timeout has expired, give up. */
1672 [ - + ]: 84 : if (now >= endtime)
1673 : : {
233 tgl@sss.pgh.pa.us 1674 :UNC 0 : *timed_out = true;
1675 : 0 : failed = true;
1676 : 0 : goto exit;
1677 : : }
1678 : :
1679 : : /* If we need to re-issue the cancel request, do that. */
233 tgl@sss.pgh.pa.us 1680 [ - + ]:GNC 84 : if (now >= retrycanceltime)
1681 : : {
1682 : : /* We ignore failure to issue the repeated request. */
233 tgl@sss.pgh.pa.us 1683 :UNC 0 : (void) libpqsrv_cancel(conn, endtime);
1684 : :
1685 : : /* Recompute "now" in case that took measurable time. */
1686 : 0 : now = GetCurrentTimestamp();
1687 : :
1688 : : /* Adjust re-cancel timeout in increasing steps. */
1689 : 0 : retrycanceltime = TimestampTzPlusMilliseconds(now,
1690 : : canceldelta);
1691 : 0 : canceldelta += canceldelta;
1692 : : }
1693 : :
1694 : : /* If timeout has expired, give up, else get sleep time. */
233 tgl@sss.pgh.pa.us 1695 :GNC 84 : cur_timeout = TimestampDifferenceMilliseconds(now,
1696 : : Min(endtime,
1697 : : retrycanceltime));
1698 [ - + ]: 84 : if (cur_timeout <= 0)
1699 : : {
233 tgl@sss.pgh.pa.us 1700 :UNC 0 : *timed_out = true;
1701 : 0 : failed = true;
1702 : 0 : goto exit;
1703 : : }
1704 : :
1705 : : /* first time, allocate or get the custom wait event */
233 tgl@sss.pgh.pa.us 1706 [ + + ]:GNC 84 : if (pgfdw_we_cleanup_result == 0)
1707 : 2 : pgfdw_we_cleanup_result = WaitEventExtensionNew("PostgresFdwCleanupResult");
1708 : :
1709 : : /* Sleep until there's something to do */
1710 : 84 : wc = WaitLatchOrSocket(MyLatch,
1711 : : WL_LATCH_SET | WL_SOCKET_READABLE |
1712 : : WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
1713 : : PQsocket(conn),
1714 : : cur_timeout, pgfdw_we_cleanup_result);
1715 : 84 : ResetLatch(MyLatch);
1716 : :
1717 [ - + ]: 84 : CHECK_FOR_INTERRUPTS();
1718 : :
1719 : : /* Data available in socket? */
1720 [ + - ]: 84 : if (wc & WL_SOCKET_READABLE)
1721 : : {
1722 [ - + ]: 84 : if (!PQconsumeInput(conn))
1723 : : {
1724 : : /* connection trouble */
233 tgl@sss.pgh.pa.us 1725 :UNC 0 : failed = true;
1726 : 0 : goto exit;
1727 : : }
1728 : : }
1729 : : }
1730 : :
233 tgl@sss.pgh.pa.us 1731 :GNC 185 : res = PQgetResult(conn);
1732 [ + + ]: 185 : if (res == NULL)
1733 : 89 : break; /* query is complete */
1734 : :
233 tgl@sss.pgh.pa.us 1735 :GBC 96 : PQclear(last_res);
233 tgl@sss.pgh.pa.us 1736 :GNC 96 : last_res = res;
1737 : : }
1738 : 89 : exit:
1558 fujii@postgresql.org 1739 [ - + ]:CBC 89 : if (failed)
3195 tgl@sss.pgh.pa.us 1740 :UBC 0 : PQclear(last_res);
1741 : : else
3195 tgl@sss.pgh.pa.us 1742 :CBC 89 : *result = last_res;
1558 fujii@postgresql.org 1743 : 89 : return failed;
1744 : : }
1745 : :
1746 : : /*
1747 : : * Abort remote transaction or subtransaction.
1748 : : *
1749 : : * "toplevel" should be set to true if toplevel (main) transaction is
1750 : : * rollbacked, false otherwise.
1751 : : *
1752 : : * Set entry->changing_xact_state to false on success, true on failure.
1753 : : */
1754 : : static void
1451 efujita@postgresql.o 1755 : 51 : pgfdw_abort_cleanup(ConnCacheEntry *entry, bool toplevel)
1756 : : {
1757 : : char sql[100];
1758 : :
1759 : : /*
1760 : : * Don't try to clean up the connection if we're already in error
1761 : : * recursion trouble.
1762 : : */
1635 fujii@postgresql.org 1763 [ - + ]: 51 : if (in_error_recursion_trouble())
1635 fujii@postgresql.org 1764 :UBC 0 : entry->changing_xact_state = true;
1765 : :
1766 : : /*
1767 : : * If connection is already unsalvageable, don't touch it further.
1768 : : */
1635 fujii@postgresql.org 1769 [ + + ]:CBC 51 : if (entry->changing_xact_state)
1770 : 1 : return;
1771 : :
1772 : : /*
1773 : : * Mark this connection as in the process of changing transaction state.
1774 : : */
1775 : 50 : entry->changing_xact_state = true;
1776 : :
1777 : : /* Assume we might have lost track of prepared statements */
1778 : 50 : entry->have_error = true;
1779 : :
1780 : : /*
1781 : : * If a command has been submitted to the remote server by using an
1782 : : * asynchronous execution function, the command might not have yet
1783 : : * completed. Check to see if a command is still being processed by the
1784 : : * remote server, and if so, request cancellation of the command.
1785 : : */
1786 [ + + ]: 50 : if (PQtransactionStatus(entry->conn) == PQTRANS_ACTIVE &&
1787 [ - + ]: 2 : !pgfdw_cancel_query(entry->conn))
1635 fujii@postgresql.org 1788 :UBC 0 : return; /* Unable to cancel running query */
1789 : :
1074 efujita@postgresql.o 1790 [ + + ]:CBC 50 : CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
1635 fujii@postgresql.org 1791 [ - + ]: 50 : if (!pgfdw_exec_cleanup_query(entry->conn, sql, false))
1451 efujita@postgresql.o 1792 :UBC 0 : return; /* Unable to abort remote (sub)transaction */
1793 : :
1635 fujii@postgresql.org 1794 [ + + ]:CBC 50 : if (toplevel)
1795 : : {
1796 [ + + + - ]: 47 : if (entry->have_prep_stmt && entry->have_error &&
1797 [ - + ]: 25 : !pgfdw_exec_cleanup_query(entry->conn,
1798 : : "DEALLOCATE ALL",
1799 : : true))
1635 fujii@postgresql.org 1800 :UBC 0 : return; /* Trouble clearing prepared statements */
1801 : :
1635 fujii@postgresql.org 1802 :CBC 47 : entry->have_prep_stmt = false;
1803 : 47 : entry->have_error = false;
1804 : : }
1805 : :
1806 : : /*
1807 : : * If pendingAreq of the per-connection state is not NULL, it means that
1808 : : * an asynchronous fetch begun by fetch_more_data_begin() was not done
1809 : : * successfully and thus the per-connection state was not reset in
1810 : : * fetch_more_data(); in that case reset the per-connection state here.
1811 : : */
1514 efujita@postgresql.o 1812 [ + + ]: 50 : if (entry->state.pendingAreq)
1813 : 1 : memset(&entry->state, 0, sizeof(entry->state));
1814 : :
1815 : : /* Disarm changing_xact_state if it all worked */
1635 fujii@postgresql.org 1816 : 50 : entry->changing_xact_state = false;
1817 : : }
1818 : :
1819 : : /*
1820 : : * Like pgfdw_abort_cleanup, submit an abort command or cancel request, but
1821 : : * don't wait for the result.
1822 : : *
1823 : : * Returns true if the abort command or cancel request is successfully issued,
1824 : : * false otherwise. If the abort command is successfully issued, the given
1825 : : * connection cache entry is appended to *pending_entries. Otherwise, if the
1826 : : * cancel request is successfully issued, it is appended to *cancel_requested.
1827 : : */
1828 : : static bool
1074 efujita@postgresql.o 1829 : 8 : pgfdw_abort_cleanup_begin(ConnCacheEntry *entry, bool toplevel,
1830 : : List **pending_entries, List **cancel_requested)
1831 : : {
1832 : : /*
1833 : : * Don't try to clean up the connection if we're already in error
1834 : : * recursion trouble.
1835 : : */
1836 [ - + ]: 8 : if (in_error_recursion_trouble())
1074 efujita@postgresql.o 1837 :UBC 0 : entry->changing_xact_state = true;
1838 : :
1839 : : /*
1840 : : * If connection is already unsalvageable, don't touch it further.
1841 : : */
1074 efujita@postgresql.o 1842 [ - + ]:CBC 8 : if (entry->changing_xact_state)
1074 efujita@postgresql.o 1843 :UBC 0 : return false;
1844 : :
1845 : : /*
1846 : : * Mark this connection as in the process of changing transaction state.
1847 : : */
1074 efujita@postgresql.o 1848 :CBC 8 : entry->changing_xact_state = true;
1849 : :
1850 : : /* Assume we might have lost track of prepared statements */
1851 : 8 : entry->have_error = true;
1852 : :
1853 : : /*
1854 : : * If a command has been submitted to the remote server by using an
1855 : : * asynchronous execution function, the command might not have yet
1856 : : * completed. Check to see if a command is still being processed by the
1857 : : * remote server, and if so, request cancellation of the command.
1858 : : */
1859 [ - + ]: 8 : if (PQtransactionStatus(entry->conn) == PQTRANS_ACTIVE)
1860 : : {
1861 : : TimestampTz endtime;
1862 : :
717 alvherre@alvh.no-ip. 1863 :UBC 0 : endtime = TimestampTzPlusMilliseconds(GetCurrentTimestamp(),
1864 : : CONNECTION_CLEANUP_TIMEOUT);
1865 [ # # ]: 0 : if (!pgfdw_cancel_query_begin(entry->conn, endtime))
1074 efujita@postgresql.o 1866 : 0 : return false; /* Unable to cancel running query */
1867 : 0 : *cancel_requested = lappend(*cancel_requested, entry);
1868 : : }
1869 : : else
1870 : : {
1871 : : char sql[100];
1872 : :
1074 efujita@postgresql.o 1873 [ + + ]:CBC 8 : CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
1874 [ - + ]: 8 : if (!pgfdw_exec_cleanup_query_begin(entry->conn, sql))
1074 efujita@postgresql.o 1875 :UBC 0 : return false; /* Unable to abort remote transaction */
1074 efujita@postgresql.o 1876 :CBC 8 : *pending_entries = lappend(*pending_entries, entry);
1877 : : }
1878 : :
1879 : 8 : return true;
1880 : : }
1881 : :
1882 : : /*
1883 : : * Finish pre-commit cleanup of connections on each of which we've sent a
1884 : : * COMMIT command to the remote server.
1885 : : */
1886 : : static void
1480 1887 : 13 : pgfdw_finish_pre_commit_cleanup(List *pending_entries)
1888 : : {
1889 : : ConnCacheEntry *entry;
1890 : 13 : List *pending_deallocs = NIL;
1891 : : ListCell *lc;
1892 : :
1893 [ - + ]: 13 : Assert(pending_entries);
1894 : :
1895 : : /*
1896 : : * Get the result of the COMMIT command for each of the pending entries
1897 : : */
1898 [ + - + + : 29 : foreach(lc, pending_entries)
+ + ]
1899 : : {
1900 : 16 : entry = (ConnCacheEntry *) lfirst(lc);
1901 : :
1902 [ - + ]: 16 : Assert(entry->changing_xact_state);
1903 : :
1904 : : /*
1905 : : * We might already have received the result on the socket, so pass
1906 : : * consume_input=true to try to consume it first
1907 : : */
1908 : 16 : do_sql_command_end(entry->conn, "COMMIT TRANSACTION", true);
1909 : 16 : entry->changing_xact_state = false;
1910 : :
1911 : : /* Do a DEALLOCATE ALL in parallel if needed */
1912 [ + + + + ]: 16 : if (entry->have_prep_stmt && entry->have_error)
1913 : : {
1914 : : /* Ignore errors (see notes in pgfdw_xact_callback) */
1915 [ + - ]: 2 : if (PQsendQuery(entry->conn, "DEALLOCATE ALL"))
1916 : : {
1917 : 2 : pending_deallocs = lappend(pending_deallocs, entry);
1918 : 2 : continue;
1919 : : }
1920 : : }
1921 : 14 : entry->have_prep_stmt = false;
1922 : 14 : entry->have_error = false;
1923 : :
1924 : 14 : pgfdw_reset_xact_state(entry, true);
1925 : : }
1926 : :
1927 : : /* No further work if no pending entries */
1928 [ + + ]: 13 : if (!pending_deallocs)
1929 : 12 : return;
1930 : :
1931 : : /*
1932 : : * Get the result of the DEALLOCATE command for each of the pending
1933 : : * entries
1934 : : */
1935 [ + - + + : 3 : foreach(lc, pending_deallocs)
+ + ]
1936 : : {
1937 : : PGresult *res;
1938 : :
1939 : 2 : entry = (ConnCacheEntry *) lfirst(lc);
1940 : :
1941 : : /* Ignore errors (see notes in pgfdw_xact_callback) */
1942 [ + + ]: 4 : while ((res = PQgetResult(entry->conn)) != NULL)
1943 : : {
1944 : 2 : PQclear(res);
1945 : : /* Stop if the connection is lost (else we'll loop infinitely) */
1946 [ - + ]: 2 : if (PQstatus(entry->conn) == CONNECTION_BAD)
1480 efujita@postgresql.o 1947 :UBC 0 : break;
1948 : : }
1480 efujita@postgresql.o 1949 :CBC 2 : entry->have_prep_stmt = false;
1950 : 2 : entry->have_error = false;
1951 : :
1952 : 2 : pgfdw_reset_xact_state(entry, true);
1953 : : }
1954 : : }
1955 : :
1956 : : /*
1957 : : * Finish pre-subcommit cleanup of connections on each of which we've sent a
1958 : : * RELEASE command to the remote server.
1959 : : */
1960 : : static void
1961 : 1 : pgfdw_finish_pre_subcommit_cleanup(List *pending_entries, int curlevel)
1962 : : {
1963 : : ConnCacheEntry *entry;
1964 : : char sql[100];
1965 : : ListCell *lc;
1966 : :
1967 [ - + ]: 1 : Assert(pending_entries);
1968 : :
1969 : : /*
1970 : : * Get the result of the RELEASE command for each of the pending entries
1971 : : */
1972 : 1 : snprintf(sql, sizeof(sql), "RELEASE SAVEPOINT s%d", curlevel);
1973 [ + - + + : 3 : foreach(lc, pending_entries)
+ + ]
1974 : : {
1975 : 2 : entry = (ConnCacheEntry *) lfirst(lc);
1976 : :
1977 [ - + ]: 2 : Assert(entry->changing_xact_state);
1978 : :
1979 : : /*
1980 : : * We might already have received the result on the socket, so pass
1981 : : * consume_input=true to try to consume it first
1982 : : */
1983 : 2 : do_sql_command_end(entry->conn, sql, true);
1984 : 2 : entry->changing_xact_state = false;
1985 : :
1986 : 2 : pgfdw_reset_xact_state(entry, false);
1987 : : }
1988 : 1 : }
1989 : :
1990 : : /*
1991 : : * Finish abort cleanup of connections on each of which we've sent an abort
1992 : : * command or cancel request to the remote server.
1993 : : */
1994 : : static void
1074 1995 : 4 : pgfdw_finish_abort_cleanup(List *pending_entries, List *cancel_requested,
1996 : : bool toplevel)
1997 : : {
1998 : 4 : List *pending_deallocs = NIL;
1999 : : ListCell *lc;
2000 : :
2001 : : /*
2002 : : * For each of the pending cancel requests (if any), get and discard the
2003 : : * result of the query, and submit an abort command to the remote server.
2004 : : */
2005 [ - + ]: 4 : if (cancel_requested)
2006 : : {
1074 efujita@postgresql.o 2007 [ # # # # :UBC 0 : foreach(lc, cancel_requested)
# # ]
2008 : : {
2009 : 0 : ConnCacheEntry *entry = (ConnCacheEntry *) lfirst(lc);
447 tgl@sss.pgh.pa.us 2010 : 0 : TimestampTz now = GetCurrentTimestamp();
2011 : : TimestampTz endtime;
2012 : : TimestampTz retrycanceltime;
2013 : : char sql[100];
2014 : :
1074 efujita@postgresql.o 2015 [ # # ]: 0 : Assert(entry->changing_xact_state);
2016 : :
2017 : : /*
2018 : : * Set end time. You might think we should do this before issuing
2019 : : * cancel request like in normal mode, but that is problematic,
2020 : : * because if, for example, it took longer than 30 seconds to
2021 : : * process the first few entries in the cancel_requested list, it
2022 : : * would cause a timeout error when processing each of the
2023 : : * remaining entries in the list, leading to slamming that entry's
2024 : : * connection shut.
2025 : : */
447 tgl@sss.pgh.pa.us 2026 : 0 : endtime = TimestampTzPlusMilliseconds(now,
2027 : : CONNECTION_CLEANUP_TIMEOUT);
2028 : 0 : retrycanceltime = TimestampTzPlusMilliseconds(now,
2029 : : RETRY_CANCEL_TIMEOUT);
2030 : :
2031 [ # # ]: 0 : if (!pgfdw_cancel_query_end(entry->conn, endtime,
2032 : : retrycanceltime, true))
2033 : : {
2034 : : /* Unable to cancel running query */
1074 efujita@postgresql.o 2035 : 0 : pgfdw_reset_xact_state(entry, toplevel);
2036 : 0 : continue;
2037 : : }
2038 : :
2039 : : /* Send an abort command in parallel if needed */
2040 [ # # ]: 0 : CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
2041 [ # # ]: 0 : if (!pgfdw_exec_cleanup_query_begin(entry->conn, sql))
2042 : : {
2043 : : /* Unable to abort remote (sub)transaction */
2044 : 0 : pgfdw_reset_xact_state(entry, toplevel);
2045 : : }
2046 : : else
2047 : 0 : pending_entries = lappend(pending_entries, entry);
2048 : : }
2049 : : }
2050 : :
2051 : : /* No further work if no pending entries */
1074 efujita@postgresql.o 2052 [ - + ]:CBC 4 : if (!pending_entries)
1074 efujita@postgresql.o 2053 :UBC 0 : return;
2054 : :
2055 : : /*
2056 : : * Get the result of the abort command for each of the pending entries
2057 : : */
1074 efujita@postgresql.o 2058 [ + - + + :CBC 12 : foreach(lc, pending_entries)
+ + ]
2059 : : {
2060 : 8 : ConnCacheEntry *entry = (ConnCacheEntry *) lfirst(lc);
2061 : : TimestampTz endtime;
2062 : : char sql[100];
2063 : :
2064 [ - + ]: 8 : Assert(entry->changing_xact_state);
2065 : :
2066 : : /*
2067 : : * Set end time. We do this now, not before issuing the command like
2068 : : * in normal mode, for the same reason as for the cancel_requested
2069 : : * entries.
2070 : : */
2071 : 8 : endtime = TimestampTzPlusMilliseconds(GetCurrentTimestamp(),
2072 : : CONNECTION_CLEANUP_TIMEOUT);
2073 : :
2074 [ + + ]: 8 : CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
2075 [ - + ]: 8 : if (!pgfdw_exec_cleanup_query_end(entry->conn, sql, endtime,
2076 : : true, false))
2077 : : {
2078 : : /* Unable to abort remote (sub)transaction */
1074 efujita@postgresql.o 2079 :UBC 0 : pgfdw_reset_xact_state(entry, toplevel);
1074 efujita@postgresql.o 2080 :CBC 4 : continue;
2081 : : }
2082 : :
2083 [ + + ]: 8 : if (toplevel)
2084 : : {
2085 : : /* Do a DEALLOCATE ALL in parallel if needed */
2086 [ + - + - ]: 4 : if (entry->have_prep_stmt && entry->have_error)
2087 : : {
2088 [ - + ]: 4 : if (!pgfdw_exec_cleanup_query_begin(entry->conn,
2089 : : "DEALLOCATE ALL"))
2090 : : {
2091 : : /* Trouble clearing prepared statements */
1074 efujita@postgresql.o 2092 :UBC 0 : pgfdw_reset_xact_state(entry, toplevel);
2093 : : }
2094 : : else
1074 efujita@postgresql.o 2095 :CBC 4 : pending_deallocs = lappend(pending_deallocs, entry);
2096 : 4 : continue;
2097 : : }
1074 efujita@postgresql.o 2098 :UBC 0 : entry->have_prep_stmt = false;
2099 : 0 : entry->have_error = false;
2100 : : }
2101 : :
2102 : : /* Reset the per-connection state if needed */
1074 efujita@postgresql.o 2103 [ - + ]:CBC 4 : if (entry->state.pendingAreq)
1074 efujita@postgresql.o 2104 :UBC 0 : memset(&entry->state, 0, sizeof(entry->state));
2105 : :
2106 : : /* We're done with this entry; unset the changing_xact_state flag */
1074 efujita@postgresql.o 2107 :CBC 4 : entry->changing_xact_state = false;
2108 : 4 : pgfdw_reset_xact_state(entry, toplevel);
2109 : : }
2110 : :
2111 : : /* No further work if no pending entries */
2112 [ + + ]: 4 : if (!pending_deallocs)
2113 : 2 : return;
2114 [ - + ]: 2 : Assert(toplevel);
2115 : :
2116 : : /*
2117 : : * Get the result of the DEALLOCATE command for each of the pending
2118 : : * entries
2119 : : */
2120 [ + - + + : 6 : foreach(lc, pending_deallocs)
+ + ]
2121 : : {
2122 : 4 : ConnCacheEntry *entry = (ConnCacheEntry *) lfirst(lc);
2123 : : TimestampTz endtime;
2124 : :
2125 [ - + ]: 4 : Assert(entry->changing_xact_state);
2126 [ - + ]: 4 : Assert(entry->have_prep_stmt);
2127 [ - + ]: 4 : Assert(entry->have_error);
2128 : :
2129 : : /*
2130 : : * Set end time. We do this now, not before issuing the command like
2131 : : * in normal mode, for the same reason as for the cancel_requested
2132 : : * entries.
2133 : : */
2134 : 4 : endtime = TimestampTzPlusMilliseconds(GetCurrentTimestamp(),
2135 : : CONNECTION_CLEANUP_TIMEOUT);
2136 : :
2137 [ - + ]: 4 : if (!pgfdw_exec_cleanup_query_end(entry->conn, "DEALLOCATE ALL",
2138 : : endtime, true, true))
2139 : : {
2140 : : /* Trouble clearing prepared statements */
1074 efujita@postgresql.o 2141 :UBC 0 : pgfdw_reset_xact_state(entry, toplevel);
2142 : 0 : continue;
2143 : : }
1074 efujita@postgresql.o 2144 :CBC 4 : entry->have_prep_stmt = false;
2145 : 4 : entry->have_error = false;
2146 : :
2147 : : /* Reset the per-connection state if needed */
2148 [ - + ]: 4 : if (entry->state.pendingAreq)
1074 efujita@postgresql.o 2149 :UBC 0 : memset(&entry->state, 0, sizeof(entry->state));
2150 : :
2151 : : /* We're done with this entry; unset the changing_xact_state flag */
1074 efujita@postgresql.o 2152 :CBC 4 : entry->changing_xact_state = false;
2153 : 4 : pgfdw_reset_xact_state(entry, toplevel);
2154 : : }
2155 : : }
2156 : :
2157 : : /* Number of output arguments (columns) for various API versions */
2158 : : #define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_1 2
2159 : : #define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_2 6
2160 : : #define POSTGRES_FDW_GET_CONNECTIONS_COLS 6 /* maximum of above */
2161 : :
2162 : : /*
2163 : : * Internal function used by postgres_fdw_get_connections variants.
2164 : : *
2165 : : * For API version 1.1, this function takes no input parameter and
2166 : : * returns a set of records with the following values:
2167 : : *
2168 : : * - server_name - server name of active connection. In case the foreign server
2169 : : * is dropped but still the connection is active, then the server name will
2170 : : * be NULL in output.
2171 : : * - valid - true/false representing whether the connection is valid or not.
2172 : : * Note that connections can become invalid in pgfdw_inval_callback.
2173 : : *
2174 : : * For API version 1.2 and later, this function takes an input parameter
2175 : : * to check a connection status and returns the following
2176 : : * additional values along with the four values from version 1.1:
2177 : : *
2178 : : * - user_name - the local user name of the active connection. In case the
2179 : : * user mapping is dropped but the connection is still active, then the
2180 : : * user name will be NULL in the output.
2181 : : * - used_in_xact - true if the connection is used in the current transaction.
2182 : : * - closed - true if the connection is closed.
2183 : : * - remote_backend_pid - process ID of the remote backend, on the foreign
2184 : : * server, handling the connection.
2185 : : *
2186 : : * No records are returned when there are no cached connections at all.
2187 : : */
2188 : : static void
597 fujii@postgresql.org 2189 : 13 : postgres_fdw_get_connections_internal(FunctionCallInfo fcinfo,
2190 : : enum pgfdwVersion api_version)
2191 : : {
1882 2192 : 13 : ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
2193 : : HASH_SEQ_STATUS scan;
2194 : : ConnCacheEntry *entry;
2195 : :
1244 michael@paquier.xyz 2196 : 13 : InitMaterializedSRF(fcinfo, 0);
2197 : :
2198 : : /* If cache doesn't exist, we return no records */
1882 fujii@postgresql.org 2199 [ - + ]: 13 : if (!ConnectionHash)
597 fujii@postgresql.org 2200 :UBC 0 : return;
2201 : :
2202 : : /* Check we have the expected number of output arguments */
597 fujii@postgresql.org 2203 [ - + - ]:CBC 13 : switch (rsinfo->setDesc->natts)
2204 : : {
597 fujii@postgresql.org 2205 :UBC 0 : case POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_1:
2206 [ # # ]: 0 : if (api_version != PGFDW_V1_1)
2207 [ # # ]: 0 : elog(ERROR, "incorrect number of output arguments");
2208 : 0 : break;
597 fujii@postgresql.org 2209 :CBC 13 : case POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_2:
2210 [ - + ]: 13 : if (api_version != PGFDW_V1_2)
597 fujii@postgresql.org 2211 [ # # ]:UBC 0 : elog(ERROR, "incorrect number of output arguments");
597 fujii@postgresql.org 2212 :CBC 13 : break;
597 fujii@postgresql.org 2213 :UBC 0 : default:
2214 [ # # ]: 0 : elog(ERROR, "incorrect number of output arguments");
2215 : : }
2216 : :
1882 fujii@postgresql.org 2217 :CBC 13 : hash_seq_init(&scan, ConnectionHash);
2218 [ + + ]: 113 : while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
2219 : : {
2220 : : ForeignServer *server;
1338 peter@eisentraut.org 2221 : 100 : Datum values[POSTGRES_FDW_GET_CONNECTIONS_COLS] = {0};
2222 : 100 : bool nulls[POSTGRES_FDW_GET_CONNECTIONS_COLS] = {0};
543 fujii@postgresql.org 2223 : 100 : int i = 0;
2224 : :
2225 : : /* We only look for open remote connections */
1882 2226 [ + + ]: 100 : if (!entry->conn)
2227 : 87 : continue;
2228 : :
2229 : 13 : server = GetForeignServerExtended(entry->serverid, FSV_MISSING_OK);
2230 : :
2231 : : /*
2232 : : * The foreign server may have been dropped in current explicit
2233 : : * transaction. It is not possible to drop the server from another
2234 : : * session when the connection associated with it is in use in the
2235 : : * current transaction, if tried so, the drop query in another session
2236 : : * blocks until the current transaction finishes.
2237 : : *
2238 : : * Even though the server is dropped in the current transaction, the
2239 : : * cache can still have associated active connection entry, say we
2240 : : * call such connections dangling. Since we can not fetch the server
2241 : : * name from system catalogs for dangling connections, instead we show
2242 : : * NULL value for server name in output.
2243 : : *
2244 : : * We could have done better by storing the server name in the cache
2245 : : * entry instead of server oid so that it could be used in the output.
2246 : : * But the server name in each cache entry requires 64 bytes of
2247 : : * memory, which is huge, when there are many cached connections and
2248 : : * the use case i.e. dropping the foreign server within the explicit
2249 : : * current transaction seems rare. So, we chose to show NULL value for
2250 : : * server name in output.
2251 : : *
2252 : : * Such dangling connections get closed either in next use or at the
2253 : : * end of current explicit transaction in pgfdw_xact_callback.
2254 : : */
2255 [ + + ]: 13 : if (!server)
2256 : : {
2257 : : /*
2258 : : * If the server has been dropped in the current explicit
2259 : : * transaction, then this entry would have been invalidated in
2260 : : * pgfdw_inval_callback at the end of drop server command. Note
2261 : : * that this connection would not have been closed in
2262 : : * pgfdw_inval_callback because it is still being used in the
2263 : : * current explicit transaction. So, assert that here.
2264 : : */
2265 [ + - + - : 1 : Assert(entry->conn && entry->xact_depth > 0 && entry->invalidated);
- + ]
2266 : :
2267 : : /* Show null, if no server name was found */
543 2268 : 1 : nulls[i++] = true;
2269 : : }
2270 : : else
2271 : 12 : values[i++] = CStringGetTextDatum(server->servername);
2272 : :
2273 [ + - ]: 13 : if (api_version >= PGFDW_V1_2)
2274 : : {
2275 : : HeapTuple tp;
2276 : :
2277 : : /* Use the system cache to obtain the user mapping */
2278 : 13 : tp = SearchSysCache1(USERMAPPINGOID, ObjectIdGetDatum(entry->key));
2279 : :
2280 : : /*
2281 : : * Just like in the foreign server case, user mappings can also be
2282 : : * dropped in the current explicit transaction. Therefore, the
2283 : : * similar check as in the server case is required.
2284 : : */
2285 [ + + ]: 13 : if (!HeapTupleIsValid(tp))
2286 : : {
2287 : : /*
2288 : : * If we reach here, this entry must have been invalidated in
2289 : : * pgfdw_inval_callback, same as in the server case.
2290 : : */
2291 [ + - + - : 1 : Assert(entry->conn && entry->xact_depth > 0 &&
- + ]
2292 : : entry->invalidated);
2293 : :
2294 : 1 : nulls[i++] = true;
2295 : : }
2296 : : else
2297 : : {
2298 : : Oid userid;
2299 : :
2300 : 12 : userid = ((Form_pg_user_mapping) GETSTRUCT(tp))->umuser;
2301 [ + + ]: 12 : values[i++] = CStringGetTextDatum(MappingUserName(userid));
2302 : 12 : ReleaseSysCache(tp);
2303 : : }
2304 : : }
2305 : :
2306 : 13 : values[i++] = BoolGetDatum(!entry->invalidated);
2307 : :
597 2308 [ + - ]: 13 : if (api_version >= PGFDW_V1_2)
2309 : : {
2310 : 13 : bool check_conn = PG_GETARG_BOOL(0);
2311 : :
2312 : : /* Is this connection used in the current transaction? */
543 2313 : 13 : values[i++] = BoolGetDatum(entry->xact_depth > 0);
2314 : :
2315 : : /*
2316 : : * If a connection status check is requested and supported, return
2317 : : * whether the connection is closed. Otherwise, return NULL.
2318 : : */
597 2319 [ + + + - ]: 13 : if (check_conn && pgfdw_conn_checkable())
543 2320 : 2 : values[i++] = BoolGetDatum(pgfdw_conn_check(entry->conn) != 0);
2321 : : else
2322 : 11 : nulls[i++] = true;
2323 : :
2324 : : /* Return process ID of remote backend */
377 2325 : 13 : values[i++] = Int32GetDatum(PQbackendPID(entry->conn));
2326 : : }
2327 : :
1468 michael@paquier.xyz 2328 : 13 : tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
2329 : : }
2330 : : }
2331 : :
2332 : : /*
2333 : : * Values in connection strings must be enclosed in single quotes. Single
2334 : : * quotes and backslashes must be escaped with backslash. NB: these rules are
2335 : : * different from the rules for escaping a SQL literal.
2336 : : */
2337 : : static void
9 jdavis@postgresql.or 2338 :GNC 70 : appendEscapedValue(StringInfo str, const char *val)
2339 : : {
2340 : 70 : appendStringInfoChar(str, '\'');
2341 [ + + ]: 508 : for (int i = 0; val[i] != '\0'; i++)
2342 : : {
2343 [ + - - + ]: 438 : if (val[i] == '\\' || val[i] == '\'')
9 jdavis@postgresql.or 2344 :UNC 0 : appendStringInfoChar(str, '\\');
9 jdavis@postgresql.or 2345 :GNC 438 : appendStringInfoChar(str, val[i]);
2346 : : }
2347 : 70 : appendStringInfoChar(str, '\'');
2348 : 70 : }
2349 : :
2350 : : Datum
2351 : 6 : postgres_fdw_connection(PG_FUNCTION_ARGS)
2352 : : {
2353 : 6 : Oid userid = PG_GETARG_OID(0);
2354 : 6 : Oid serverid = PG_GETARG_OID(1);
2355 : 6 : ForeignServer *server = GetForeignServer(serverid);
2356 : 6 : UserMapping *user = GetUserMapping(userid, serverid);
2357 : : StringInfoData str;
2358 : : const char **keywords;
2359 : : const char **values;
2360 : : char *appname;
2361 : 6 : char *sep = "";
2362 : :
2363 : 6 : construct_connection_params(server, user, &keywords, &values, &appname);
2364 : :
2365 : 6 : initStringInfo(&str);
2366 [ + + ]: 76 : for (int i = 0; keywords[i] != NULL; i++)
2367 : : {
2368 [ - + ]: 70 : if (values[i] == NULL)
9 jdavis@postgresql.or 2369 :UNC 0 : continue;
9 jdavis@postgresql.or 2370 :GNC 70 : appendStringInfo(&str, "%s%s = ", sep, keywords[i]);
2371 : 70 : appendEscapedValue(&str, values[i]);
2372 : 70 : sep = " ";
2373 : : }
2374 : :
2375 [ + + ]: 6 : if (appname != NULL)
2376 : 2 : pfree(appname);
2377 : 6 : pfree(keywords);
2378 : 6 : pfree(values);
2379 : 6 : PG_RETURN_TEXT_P(cstring_to_text(str.data));
2380 : : }
2381 : :
2382 : : /*
2383 : : * List active foreign server connections.
2384 : : *
2385 : : * The SQL API of this function has changed multiple times, and will likely
2386 : : * do so again in future. To support the case where a newer version of this
2387 : : * loadable module is being used with an old SQL declaration of the function,
2388 : : * we continue to support the older API versions.
2389 : : */
2390 : : Datum
597 fujii@postgresql.org 2391 :CBC 13 : postgres_fdw_get_connections_1_2(PG_FUNCTION_ARGS)
2392 : : {
2393 : 13 : postgres_fdw_get_connections_internal(fcinfo, PGFDW_V1_2);
2394 : :
2395 : 13 : PG_RETURN_VOID();
2396 : : }
2397 : :
2398 : : Datum
597 fujii@postgresql.org 2399 :UBC 0 : postgres_fdw_get_connections(PG_FUNCTION_ARGS)
2400 : : {
2401 : 0 : postgres_fdw_get_connections_internal(fcinfo, PGFDW_V1_1);
2402 : :
1882 2403 : 0 : PG_RETURN_VOID();
2404 : : }
2405 : :
2406 : : /*
2407 : : * Disconnect the specified cached connections.
2408 : : *
2409 : : * This function discards the open connections that are established by
2410 : : * postgres_fdw from the local session to the foreign server with
2411 : : * the given name. Note that there can be multiple connections to
2412 : : * the given server using different user mappings. If the connections
2413 : : * are used in the current local transaction, they are not disconnected
2414 : : * and warning messages are reported. This function returns true
2415 : : * if it disconnects at least one connection, otherwise false. If no
2416 : : * foreign server with the given name is found, an error is reported.
2417 : : */
2418 : : Datum
1874 fujii@postgresql.org 2419 :CBC 4 : postgres_fdw_disconnect(PG_FUNCTION_ARGS)
2420 : : {
2421 : : ForeignServer *server;
2422 : : char *servername;
2423 : :
2424 : 4 : servername = text_to_cstring(PG_GETARG_TEXT_PP(0));
2425 : 4 : server = GetForeignServerByName(servername, false);
2426 : :
2427 : 3 : PG_RETURN_BOOL(disconnect_cached_connections(server->serverid));
2428 : : }
2429 : :
2430 : : /*
2431 : : * Disconnect all the cached connections.
2432 : : *
2433 : : * This function discards all the open connections that are established by
2434 : : * postgres_fdw from the local session to the foreign servers.
2435 : : * If the connections are used in the current local transaction, they are
2436 : : * not disconnected and warning messages are reported. This function
2437 : : * returns true if it disconnects at least one connection, otherwise false.
2438 : : */
2439 : : Datum
2440 : 5 : postgres_fdw_disconnect_all(PG_FUNCTION_ARGS)
2441 : : {
2442 : 5 : PG_RETURN_BOOL(disconnect_cached_connections(InvalidOid));
2443 : : }
2444 : :
2445 : : /*
2446 : : * Workhorse to disconnect cached connections.
2447 : : *
2448 : : * This function scans all the connection cache entries and disconnects
2449 : : * the open connections whose foreign server OID matches with
2450 : : * the specified one. If InvalidOid is specified, it disconnects all
2451 : : * the cached connections.
2452 : : *
2453 : : * This function emits a warning for each connection that's used in
2454 : : * the current transaction and doesn't close it. It returns true if
2455 : : * it disconnects at least one connection, otherwise false.
2456 : : *
2457 : : * Note that this function disconnects even the connections that are
2458 : : * established by other users in the same local session using different
2459 : : * user mappings. This leads even non-superuser to be able to close
2460 : : * the connections established by superusers in the same local session.
2461 : : *
2462 : : * XXX As of now we don't see any security risk doing this. But we should
2463 : : * set some restrictions on that, for example, prevent non-superuser
2464 : : * from closing the connections established by superusers even
2465 : : * in the same session?
2466 : : */
2467 : : static bool
2468 : 8 : disconnect_cached_connections(Oid serverid)
2469 : : {
2470 : : HASH_SEQ_STATUS scan;
2471 : : ConnCacheEntry *entry;
2472 : 8 : bool all = !OidIsValid(serverid);
2473 : 8 : bool result = false;
2474 : :
2475 : : /*
2476 : : * Connection cache hashtable has not been initialized yet in this
2477 : : * session, so return false.
2478 : : */
2479 [ - + ]: 8 : if (!ConnectionHash)
1874 fujii@postgresql.org 2480 :UBC 0 : return false;
2481 : :
1874 fujii@postgresql.org 2482 :CBC 8 : hash_seq_init(&scan, ConnectionHash);
2483 [ + + ]: 67 : while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
2484 : : {
2485 : : /* Ignore cache entry if no open connection right now. */
2486 [ + + ]: 59 : if (!entry->conn)
2487 : 47 : continue;
2488 : :
2489 [ + + + + ]: 12 : if (all || entry->serverid == serverid)
2490 : : {
2491 : : /*
2492 : : * Emit a warning because the connection to close is used in the
2493 : : * current transaction and cannot be disconnected right now.
2494 : : */
2495 [ + + ]: 9 : if (entry->xact_depth > 0)
2496 : : {
2497 : : ForeignServer *server;
2498 : :
2499 : 3 : server = GetForeignServerExtended(entry->serverid,
2500 : : FSV_MISSING_OK);
2501 : :
2502 [ - + ]: 3 : if (!server)
2503 : : {
2504 : : /*
2505 : : * If the foreign server was dropped while its connection
2506 : : * was used in the current transaction, the connection
2507 : : * must have been marked as invalid by
2508 : : * pgfdw_inval_callback at the end of DROP SERVER command.
2509 : : */
1874 fujii@postgresql.org 2510 [ # # ]:UBC 0 : Assert(entry->invalidated);
2511 : :
2512 [ # # ]: 0 : ereport(WARNING,
2513 : : (errmsg("cannot close dropped server connection because it is still in use")));
2514 : : }
2515 : : else
1874 fujii@postgresql.org 2516 [ + - ]:CBC 3 : ereport(WARNING,
2517 : : (errmsg("cannot close connection for server \"%s\" because it is still in use",
2518 : : server->servername)));
2519 : : }
2520 : : else
2521 : : {
2522 [ - + ]: 6 : elog(DEBUG3, "discarding connection %p", entry->conn);
2523 : 6 : disconnect_pg_server(entry);
2524 : 6 : result = true;
2525 : : }
2526 : : }
2527 : : }
2528 : :
2529 : 8 : return result;
2530 : : }
2531 : :
2532 : : /*
2533 : : * Check if the remote server closed the connection.
2534 : : *
2535 : : * Returns 1 if the connection is closed, -1 if an error occurred,
2536 : : * and 0 if it's not closed or if the connection check is unavailable
2537 : : * on this platform.
2538 : : */
2539 : : static int
597 2540 : 2 : pgfdw_conn_check(PGconn *conn)
2541 : : {
2542 : 2 : int sock = PQsocket(conn);
2543 : :
2544 [ + - - + ]: 2 : if (PQstatus(conn) != CONNECTION_OK || sock == -1)
597 fujii@postgresql.org 2545 :UBC 0 : return -1;
2546 : :
2547 : : #if (defined(HAVE_POLL) && defined(POLLRDHUP))
2548 : : {
2549 : : struct pollfd input_fd;
2550 : : int result;
2551 : :
597 fujii@postgresql.org 2552 :CBC 2 : input_fd.fd = sock;
2553 : 2 : input_fd.events = POLLRDHUP;
2554 : 2 : input_fd.revents = 0;
2555 : :
2556 : : do
2557 : 2 : result = poll(&input_fd, 1, 0);
2558 [ - + - - ]: 2 : while (result < 0 && errno == EINTR);
2559 : :
2560 [ - + ]: 2 : if (result < 0)
597 fujii@postgresql.org 2561 :UBC 0 : return -1;
2562 : :
596 fujii@postgresql.org 2563 :CBC 2 : return (input_fd.revents &
2564 : 2 : (POLLRDHUP | POLLHUP | POLLERR | POLLNVAL)) ? 1 : 0;
2565 : : }
2566 : : #else
2567 : : return 0;
2568 : : #endif
2569 : : }
2570 : :
2571 : : /*
2572 : : * Check if connection status checking is available on this platform.
2573 : : *
2574 : : * Returns true if available, false otherwise.
2575 : : */
2576 : : static bool
597 2577 : 2 : pgfdw_conn_checkable(void)
2578 : : {
2579 : : #if (defined(HAVE_POLL) && defined(POLLRDHUP))
2580 : 2 : return true;
2581 : : #else
2582 : : return false;
2583 : : #endif
2584 : : }
2585 : :
2586 : : /*
2587 : : * Ensure that require_auth and SCRAM keys are correctly set on values. SCRAM
2588 : : * keys used to pass-through are coming from the initial connection from the
2589 : : * client with the server.
2590 : : *
2591 : : * All required SCRAM options are set by postgres_fdw, so we just need to
2592 : : * ensure that these options are not overwritten by the user.
2593 : : */
2594 : : static bool
356 peter@eisentraut.org 2595 : 8 : pgfdw_has_required_scram_options(const char **keywords, const char **values)
2596 : : {
2597 : 8 : bool has_scram_server_key = false;
2598 : 8 : bool has_scram_client_key = false;
2599 : 8 : bool has_require_auth = false;
2600 : 8 : bool has_scram_keys = false;
2601 : :
2602 : : /*
2603 : : * Continue iterating even if we found the keys that we need to validate
2604 : : * to make sure that there is no other declaration of these keys that can
2605 : : * overwrite the first.
2606 : : */
2607 [ + + ]: 80 : for (int i = 0; keywords[i] != NULL; i++)
2608 : : {
2609 [ + + ]: 72 : if (strcmp(keywords[i], "scram_client_key") == 0)
2610 : : {
2611 [ + - + - ]: 8 : if (values[i] != NULL && values[i][0] != '\0')
2612 : 8 : has_scram_client_key = true;
2613 : : else
356 peter@eisentraut.org 2614 :UBC 0 : has_scram_client_key = false;
2615 : : }
2616 : :
356 peter@eisentraut.org 2617 [ + + ]:CBC 72 : if (strcmp(keywords[i], "scram_server_key") == 0)
2618 : : {
2619 [ + - + - ]: 8 : if (values[i] != NULL && values[i][0] != '\0')
2620 : 8 : has_scram_server_key = true;
2621 : : else
356 peter@eisentraut.org 2622 :UBC 0 : has_scram_server_key = false;
2623 : : }
2624 : :
356 peter@eisentraut.org 2625 [ + + ]:CBC 72 : if (strcmp(keywords[i], "require_auth") == 0)
2626 : : {
2627 [ + - + - ]: 8 : if (values[i] != NULL && strcmp(values[i], "scram-sha-256") == 0)
2628 : 8 : has_require_auth = true;
2629 : : else
356 peter@eisentraut.org 2630 :UBC 0 : has_require_auth = false;
2631 : : }
2632 : : }
2633 : :
219 peter@eisentraut.org 2634 [ + - + - :CBC 8 : has_scram_keys = has_scram_client_key && has_scram_server_key && MyProcPort != NULL && MyProcPort->has_scram_keys;
+ - + - ]
2635 : :
356 2636 [ + - + - ]: 8 : return (has_scram_keys && has_require_auth);
2637 : : }
|