On Thu Nov 26, 2026 at 9:44 AM CET, Peter Eisentraut wrote:
Feedback on patch [PATCH v13 3/5] fe_utils: Simplify cancel logic in wait_on_slots:
Addressed all of this in the attached v14.
2) The new code loses the message "Cancel request sent" under some circumstances.
I fixed this by not calling SetCancelConn at all anymore for parallel slots. Instead it now relies on the cancel being sent by disconnectDatabase, and prints a user message in ParallelSlotsTerminate.
But actually shouldn't the header file be in src/include/port/ (or maybe src/include/port/win32/)?
That's totally correct and indeed simplifies the final patch. I moved it to src/include/port now. Moving it to src/include/port/win32/pthread.h might change MinGW behaviour in ways that I'm not sure are better since it has its own pthread (similarly for src/include/port/win32_msvc). Since hopefully we'll get rid of this thing once we get Thomas's pg_threads.h, I don't feel like spending too much time on this.
From 643b19bce2b96190709be45c8e102ccdf14f0bff Mon Sep 17 00:00:00 2001 From: Jelte Fennema-Nio <[email protected]> Date: Tue, 7 Apr 2026 19:54:13 +0200 Subject: [PATCH v14 1/3] fe_utils: Stop using SetCancelConn for parallel slots When waiting on parallel slots, only a single connection was registered using SetCancelConn. So on Ctrl-C only the query of that one slot was cancelled right away, while the others kept running until the slots were terminated. Instead select_loop now checks CancelRequested itself, which makes wait_on_slots fail right away. We then rely on the caller calling ParallelSlotsTerminate, which already cancels the queries that are still running on any of the slots. It now also reports "Cancel request sent" when it does that because of a Ctrl-C. ParallelSlotsWaitCompletion now waits using wait_on_slots too, so that it behaves the same. To not miss a SIGINT that arrives right before the wait starts, select_loop now uses pselect() with SIGINT blocked outside of the wait. This is the first use of pselect() in the tree, but it does not need a configure check because it has been part of POSIX since POSIX.1-2001. A user-visible effect is that we no longer wait for the server to respond to the cancel request. So only "Cancel request sent" is reported and not the resulting "canceling statement due to user request" error. In passing, specify the Windows select() timeout as {1, 0} instead of the invalid {0, 1000000}. --- src/fe_utils/parallel_slot.c | 136 +++++++++++++++++++++-------------- 1 file changed, 83 insertions(+), 53 deletions(-) diff --git a/src/fe_utils/parallel_slot.c b/src/fe_utils/parallel_slot.c index fb9e6cc4ec1..2f825d4d63e 100644 --- a/src/fe_utils/parallel_slot.c +++ b/src/fe_utils/parallel_slot.c @@ -19,6 +19,10 @@ #include "postgres_fe.h" #include <sys/select.h> +#ifndef WIN32 +#include <pthread.h> +#include <signal.h> +#endif #include "common/logging.h" #include "fe_utils/cancel.h" @@ -49,27 +53,6 @@ processQueryResult(ParallelSlot *slot, PGresult *result) return true; } -/* - * Consume all the results generated for the given connection until - * nothing remains. If at least one error is encountered, return false. - * Note that this will block if the connection is busy. - */ -static bool -consumeQueryResult(ParallelSlot *slot) -{ - bool ok = true; - PGresult *result; - - SetCancelConn(slot->connection); - while ((result = PQgetResult(slot->connection)) != NULL) - { - if (!processQueryResult(slot, result)) - ok = false; - } - ResetCancelConn(); - return ok; -} - /* * Wait until a file descriptor from the given set becomes readable. * @@ -82,26 +65,44 @@ select_loop(int maxFd, fd_set *workerset) int i; fd_set saveSet = *workerset; - if (CancelRequested) - return -1; +#ifndef WIN32 + + /* + * Keep SIGINT blocked except while waiting in pselect(). Otherwise a + * SIGINT arriving between the CancelRequested check and the start of the + * wait would go unnoticed until a socket becomes readable, which for a + * stuck server might be never. + */ + sigset_t origmask; + sigset_t blockmask; + + sigemptyset(&blockmask); + sigaddset(&blockmask, SIGINT); + pthread_sigmask(SIG_BLOCK, &blockmask, &origmask); +#endif for (;;) { /* * On Windows, we need to check once in a while for cancel requests; - * on other platforms we rely on select() returning when interrupted. + * on other platforms we rely on pselect() returning when interrupted. */ - struct timeval *tvp; #ifdef WIN32 - struct timeval tv = {0, 1000000}; - - tvp = &tv; -#else - tvp = NULL; + struct timeval tv = {1, 0}; #endif + if (CancelRequested) + { + i = -1; + break; + } + *workerset = saveSet; - i = select(maxFd + 1, workerset, NULL, NULL, tvp); +#ifdef WIN32 + i = select(maxFd + 1, workerset, NULL, NULL, &tv); +#else + i = pselect(maxFd + 1, workerset, NULL, NULL, NULL, &origmask); +#endif #ifdef WIN32 if (i == SOCKET_ERROR) @@ -115,13 +116,15 @@ select_loop(int maxFd, fd_set *workerset) if (i < 0 && errno == EINTR) continue; /* ignore this */ - if (i < 0 || CancelRequested) - return -1; /* but not this */ if (i == 0) continue; /* timeout (Win32 only) */ break; } +#ifndef WIN32 + pthread_sigmask(SIG_SETMASK, &origmask, NULL); +#endif + return i; } @@ -190,15 +193,15 @@ find_any_idle_slot(const ParallelSlotArray *sa) /* * Wait for any slot's connection to have query results, consume the results, * and update the slot's status as appropriate. Returns true on success, - * false on cancellation, on error, or if no slots are connected. + * false on cancellation, on error, or if no slots are connected. Slots + * without a connection are ignored. */ static bool wait_on_slots(ParallelSlotArray *sa) { int i; fd_set slotset; - int maxFd = 0; - PGconn *cancelconn = NULL; + int maxFd = -1; /* We must reconstruct the fd_set for each call to select_loop */ FD_ZERO(&slotset); @@ -207,8 +210,8 @@ wait_on_slots(ParallelSlotArray *sa) { int sock; - /* We shouldn't get here if we still have slots without connections */ - Assert(sa->slots[i].connection != NULL); + if (sa->slots[i].connection == NULL) + continue; sock = PQsocket(sa->slots[i].connection); @@ -219,10 +222,6 @@ wait_on_slots(ParallelSlotArray *sa) if (sock < 0) continue; - /* Keep track of the first valid connection we see. */ - if (cancelconn == NULL) - cancelconn = sa->slots[i].connection; - FD_SET(sock, &slotset); if (sock > maxFd) maxFd = sock; @@ -232,12 +231,10 @@ wait_on_slots(ParallelSlotArray *sa) * If we get this far with no valid connections, processing cannot * continue. */ - if (cancelconn == NULL) + if (maxFd < 0) return false; - SetCancelConn(cancelconn); i = select_loop(maxFd, &slotset); - ResetCancelConn(); /* failure? */ if (i < 0) @@ -247,6 +244,9 @@ wait_on_slots(ParallelSlotArray *sa) { int sock; + if (sa->slots[i].connection == NULL) + continue; + sock = PQsocket(sa->slots[i].connection); if (sock >= 0 && FD_ISSET(sock, &slotset)) @@ -478,6 +478,7 @@ void ParallelSlotsTerminate(ParallelSlotArray *sa) { int i; + int ncanceled = 0; for (i = 0; i < sa->numslots; i++) { @@ -486,8 +487,35 @@ ParallelSlotsTerminate(ParallelSlotArray *sa) if (conn == NULL) continue; + if (PQtransactionStatus(conn) == PQTRANS_ACTIVE) + ncanceled++; + disconnectDatabase(conn); } + + /* + * Only report this if the user asked for the cancel, not when we cancel + * the remaining queries because one of them failed. + */ + if (ncanceled > 0 && CancelRequested) + fprintf(stderr, ngettext("Cancel request sent\n", + "Cancel requests sent\n", + ncanceled)); +} + +/* + * Return whether any slot is still running a query. + */ +static bool +any_slot_busy(const ParallelSlotArray *sa) +{ + for (int i = 0; i < sa->numslots; i++) + { + if (PQtransactionStatus(sa->slots[i].connection) == PQTRANS_ACTIVE) + return true; + } + + return false; } /* @@ -499,18 +527,20 @@ ParallelSlotsTerminate(ParallelSlotArray *sa) bool ParallelSlotsWaitCompletion(ParallelSlotArray *sa) { - int i; - - for (i = 0; i < sa->numslots; i++) + while (any_slot_busy(sa)) { - if (sa->slots[i].connection == NULL) - continue; - if (!consumeQueryResult(&sa->slots[i])) + if (!wait_on_slots(sa)) return false; - /* Mark connection as idle */ - ParallelSlotSetIdle(&sa->slots[i]); } + /* + * wait_on_slots only marks a slot as idle once its query has finished. + * That never happens for a slot that was handed out but on which sending + * the query failed, so mark all of them as idle here. + */ + for (int i = 0; i < sa->numslots; i++) + ParallelSlotSetIdle(&sa->slots[i]); + return true; } -- 2.56.1
From f9eeb629073ce19ce464db4bde656c4dde96a4f8 Mon Sep 17 00:00:00 2001 From: Jelte Fennema-Nio <[email protected]> Date: Sat, 13 Dec 2025 18:18:13 +0100 Subject: [PATCH v14 2/3] Move Windows pthread compatibility functions to src/port This is in preparation of a follow-up commit which will start to use these functions in more places than just libpq. The accompanying header, pthread-win32.h, was already in src/port. That is not a standard location for headers though, so libpq and libpq-oauth had to add that directory to their include path to find it. Move the header to src/include/port, so that it can be included without any such build system changes. --- configure.ac | 1 + src/{ => include}/port/pthread-win32.h | 2 +- src/interfaces/libpq-oauth/meson.build | 3 +-- src/interfaces/libpq/Makefile | 3 +-- src/interfaces/libpq/fe-connect.c | 2 +- src/interfaces/libpq/fe-secure-openssl.c | 2 +- src/interfaces/libpq/fe-secure.c | 2 +- src/interfaces/libpq/libpq-int.h | 2 +- src/interfaces/libpq/meson.build | 5 ++--- src/port/meson.build | 1 + src/{interfaces/libpq => port}/pthread-win32.c | 6 +++--- src/tools/pginclude/headerscheck | 2 +- 12 files changed, 15 insertions(+), 16 deletions(-) rename src/{ => include}/port/pthread-win32.h (94%) rename src/{interfaces/libpq => port}/pthread-win32.c (92%) diff --git a/configure.ac b/configure.ac index 18bbe596612..9b57de6550c 100644 --- a/configure.ac +++ b/configure.ac @@ -1975,6 +1975,7 @@ if test "$PORTNAME" = "win32"; then AC_LIBOBJ(dirmod) AC_LIBOBJ(kill) AC_LIBOBJ(open) + AC_LIBOBJ(pthread-win32) AC_LIBOBJ(system) AC_LIBOBJ(win32common) AC_LIBOBJ(win32dlopen) diff --git a/src/port/pthread-win32.h b/src/include/port/pthread-win32.h similarity index 94% rename from src/port/pthread-win32.h rename to src/include/port/pthread-win32.h index 5f33269057c..29bdfbaf5f5 100644 --- a/src/port/pthread-win32.h +++ b/src/include/port/pthread-win32.h @@ -1,5 +1,5 @@ /* - * src/port/pthread-win32.h + * src/include/port/pthread-win32.h */ #ifndef __PTHREAD_H #define __PTHREAD_H diff --git a/src/interfaces/libpq-oauth/meson.build b/src/interfaces/libpq-oauth/meson.build index ea3a900f4f1..9ff9beb1309 100644 --- a/src/interfaces/libpq-oauth/meson.build +++ b/src/interfaces/libpq-oauth/meson.build @@ -26,8 +26,7 @@ export_file = custom_target('libpq-oauth.exports', kwargs: gen_export_kwargs, ) -# port needs to be in include path due to pthread-win32.h -libpq_oauth_inc = include_directories('.', '../libpq', '../../port') +libpq_oauth_inc = include_directories('.', '../libpq') if build_static_lib libpq_oauth_st = static_library('libpq-oauth', diff --git a/src/interfaces/libpq/Makefile b/src/interfaces/libpq/Makefile index 0963995eed4..dec29a93bf9 100644 --- a/src/interfaces/libpq/Makefile +++ b/src/interfaces/libpq/Makefile @@ -24,7 +24,7 @@ NAME= pq SO_MAJOR_VERSION= 5 SO_MINOR_VERSION= $(MAJORVERSION) -override CPPFLAGS := -I$(srcdir) -I$(top_builddir)/src/port -I$(top_srcdir)/src/port $(CPPFLAGS) +override CPPFLAGS := -I$(srcdir) -I$(top_builddir)/src/port $(CPPFLAGS) ifneq ($(PORTNAME), win32) override CFLAGS += $(PTHREAD_CFLAGS) endif @@ -75,7 +75,6 @@ endif ifeq ($(PORTNAME), win32) OBJS += \ - pthread-win32.o \ win32.o endif diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index b30585c74c8..ec8e56d5cf3 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -57,7 +57,7 @@ #endif #ifdef WIN32 -#include "pthread-win32.h" +#include "port/pthread-win32.h" #else #include <pthread.h> #endif diff --git a/src/interfaces/libpq/fe-secure-openssl.c b/src/interfaces/libpq/fe-secure-openssl.c index 243ed240087..a213f675321 100644 --- a/src/interfaces/libpq/fe-secure-openssl.c +++ b/src/interfaces/libpq/fe-secure-openssl.c @@ -46,7 +46,7 @@ #include <sys/stat.h> #ifdef WIN32 -#include "pthread-win32.h" +#include "port/pthread-win32.h" #else #include <pthread.h> #endif diff --git a/src/interfaces/libpq/fe-secure.c b/src/interfaces/libpq/fe-secure.c index 1a8e2e6746e..d6a90cca3a6 100644 --- a/src/interfaces/libpq/fe-secure.c +++ b/src/interfaces/libpq/fe-secure.c @@ -36,7 +36,7 @@ #include <sys/stat.h> #ifdef WIN32 -#include "pthread-win32.h" +#include "port/pthread-win32.h" #else #include <pthread.h> #endif diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index 9261fe0d309..0cc0af7c4a5 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -32,7 +32,7 @@ #endif #ifdef WIN32 -#include "pthread-win32.h" +#include "port/pthread-win32.h" #else #include <pthread.h> #endif diff --git a/src/interfaces/libpq/meson.build b/src/interfaces/libpq/meson.build index b0ae72167a1..78d2f9d1f85 100644 --- a/src/interfaces/libpq/meson.build +++ b/src/interfaces/libpq/meson.build @@ -20,7 +20,7 @@ libpq_sources = files( libpq_so_sources = [] # for shared lib, in addition to the above if host_system == 'windows' - libpq_sources += files('pthread-win32.c', 'win32.c') + libpq_sources += files('win32.c') libpq_so_sources += rc_lib_gen.process(win32ver_rc, extra_args: [ '--NAME', 'libpq', '--FILEDESC', 'PostgreSQL Access Library',]) @@ -42,8 +42,7 @@ export_file = custom_target('libpq.exports', kwargs: gen_export_kwargs, ) -# port needs to be in include path due to pthread-win32.h -libpq_inc = include_directories('.', '../../port') +libpq_inc = include_directories('.') libpq_c_args = ['-DSO_MAJOR_VERSION=5'] # The OAuth implementation differs depending on the type of library being built. diff --git a/src/port/meson.build b/src/port/meson.build index 922b3f64676..10833b13842 100644 --- a/src/port/meson.build +++ b/src/port/meson.build @@ -33,6 +33,7 @@ if host_system == 'windows' 'dirmod.c', 'kill.c', 'open.c', + 'pthread-win32.c', 'system.c', 'win32common.c', 'win32dlopen.c', diff --git a/src/interfaces/libpq/pthread-win32.c b/src/port/pthread-win32.c similarity index 92% rename from src/interfaces/libpq/pthread-win32.c rename to src/port/pthread-win32.c index cf66284f007..04594abcc44 100644 --- a/src/interfaces/libpq/pthread-win32.c +++ b/src/port/pthread-win32.c @@ -5,14 +5,14 @@ * * Copyright (c) 2004-2026, PostgreSQL Global Development Group * IDENTIFICATION -* src/interfaces/libpq/pthread-win32.c +* src/port/pthread-win32.c * *------------------------------------------------------------------------- */ -#include "postgres_fe.h" +#include "c.h" -#include "pthread-win32.h" +#include "port/pthread-win32.h" DWORD pthread_self(void) diff --git a/src/tools/pginclude/headerscheck b/src/tools/pginclude/headerscheck index 785d6f867ad..69d9af4ad6f 100755 --- a/src/tools/pginclude/headerscheck +++ b/src/tools/pginclude/headerscheck @@ -105,7 +105,7 @@ do test "$f" = src/include/port/win32_msvc/dirent.h && continue test "$f" = src/include/port/win32_msvc/utime.h && continue test "$f" = src/include/port/win32ntdll.h && continue - test "$f" = src/port/pthread-win32.h && continue + test "$f" = src/include/port/pthread-win32.h && continue # Likewise, these files are platform-specific, and the one # relevant to our platform will be included by atomics.h. -- 2.56.1
From 9d676e300c90184656ebaf8856591b144abcfac9 Mon Sep 17 00:00:00 2001 From: Jelte Fennema-Nio <[email protected]> Date: Sat, 13 Dec 2025 13:05:50 +0100 Subject: [PATCH v14 3/3] Don't use deprecated and insecure PQcancel psql and other tools anymore All of our frontend tools that used our fe_utils to cancel queries, including psql, still used PQcancel to send cancel requests to the server. That function is insecure, because it does not use encryption to send the cancel request. This starts using the new cancellation APIs (introduced in 61461a300) for all these frontend tools. These APIs use the same encryption settings as the connection that's being cancelled. Since these APIs are not signal-safe this required a refactor to not send the cancel request in a signal handler anymore, but instead using a dedicated thread. Similar logic was already used for Windows anyway, so this has the benefit that it makes the cancel logic more uniform across our supported platforms. In the pg_dump code there's still quite a bit of behavioural difference though, because pg_dump is using threads for parallelism on Windows, but processes on Unixes. --- meson.build | 2 +- src/bin/pg_amcheck/pg_amcheck.c | 2 +- src/bin/pg_dump/parallel.c | 335 ++++++++------------ src/bin/pg_dump/pg_backup_archiver.c | 2 +- src/bin/pg_dump/pg_backup_archiver.h | 8 +- src/bin/pg_dump/pg_backup_db.c | 7 +- src/bin/pgbench/pgbench.c | 2 +- src/bin/psql/common.c | 10 +- src/bin/scripts/clusterdb.c | 2 +- src/bin/scripts/reindexdb.c | 2 +- src/bin/scripts/vacuuming.c | 2 +- src/fe_utils/cancel.c | 440 +++++++++++++++++++-------- src/include/fe_utils/cancel.h | 15 +- 13 files changed, 476 insertions(+), 353 deletions(-) diff --git a/meson.build b/meson.build index 3238c849e1b..fcbf738f068 100644 --- a/meson.build +++ b/meson.build @@ -3650,7 +3650,7 @@ frontend_code = declare_dependency( include_directories: [postgres_inc], link_with: [fe_utils, common_static, pgport_static], sources: generated_headers_stamp, - dependencies: [os_deps, libintl], + dependencies: [os_deps, libintl, thread_dep], ) backend_both_deps += [ diff --git a/src/bin/pg_amcheck/pg_amcheck.c b/src/bin/pg_amcheck/pg_amcheck.c index cced5181cce..ef06e83626f 100644 --- a/src/bin/pg_amcheck/pg_amcheck.c +++ b/src/bin/pg_amcheck/pg_amcheck.c @@ -477,7 +477,7 @@ main(int argc, char *argv[]) cparams.dbname = NULL; cparams.override_dbname = NULL; - setup_cancel_handler(NULL); + setup_cancel_handler(NULL, NULL); /* choose the database for our initial connection */ if (opts.alldb) diff --git a/src/bin/pg_dump/parallel.c b/src/bin/pg_dump/parallel.c index d6bdb60977c..c10bf2f98db 100644 --- a/src/bin/pg_dump/parallel.c +++ b/src/bin/pg_dump/parallel.c @@ -60,6 +60,8 @@ #include <fcntl.h> #endif +#include "common/logging.h" +#include "fe_utils/cancel.h" #include "fe_utils/string_utils.h" #include "parallel.h" #include "pg_backup_utils.h" @@ -174,10 +176,6 @@ typedef struct DumpSignalInformation static volatile DumpSignalInformation signal_info; -#ifdef WIN32 -static CRITICAL_SECTION signal_info_lock; -#endif - /* * Write a simple string to stderr --- must be safe in a signal handler. * We ignore the write() result since there's not much we could do about it. @@ -209,6 +207,7 @@ static void WaitForTerminatingWorkers(ParallelState *pstate); static void set_cancel_handler(void); static void set_cancel_pstate(ParallelState *pstate); static void set_cancel_slot_archive(ParallelSlot *slot, ArchiveHandle *AH); +static void StopWorkers(void); static void RunWorker(ArchiveHandle *AH, ParallelSlot *slot); static int GetIdleWorker(ParallelState *pstate); static bool HasEveryWorkerTerminated(ParallelState *pstate); @@ -410,32 +409,9 @@ ShutdownWorkersHard(ParallelState *pstate) /* * Force early termination of any commands currently in progress. */ -#ifndef WIN32 - /* On non-Windows, send SIGTERM to each worker process. */ - for (i = 0; i < pstate->numWorkers; i++) - { - pid_t pid = pstate->parallelSlot[i].pid; - - if (pid != 0) - kill(pid, SIGTERM); - } -#else - - /* - * On Windows, send query cancels directly to the workers' backends. Use - * a critical section to ensure worker threads don't change state. - */ - EnterCriticalSection(&signal_info_lock); - for (i = 0; i < pstate->numWorkers; i++) - { - ArchiveHandle *AH = pstate->parallelSlot[i].AH; - char errbuf[1]; - - if (AH != NULL && AH->connCancel != NULL) - (void) PQcancel(AH->connCancel, errbuf, sizeof(errbuf)); - } - LeaveCriticalSection(&signal_info_lock); -#endif + LockCancelThread(); + StopWorkers(); + UnlockCancelThread(); /* Now wait for them to terminate. */ WaitForTerminatingWorkers(pstate); @@ -519,75 +495,68 @@ WaitForTerminatingWorkers(ParallelState *pstate) * could leave a SQL command (e.g., CREATE INDEX on a large table) running * for a long time. Instead, we try to send a cancel request and then die. * pg_dump probably doesn't really need this, but we might as well use it - * there too. Note that sending the cancel directly from the signal handler - * is safe because PQcancel() is written to make it so. + * there too. * - * In parallel operation on Unix, each process is responsible for canceling - * its own connection (this must be so because nobody else has access to it). - * Furthermore, the leader process should attempt to forward its signal to - * each child. In simple manual use of pg_dump/pg_restore, forwarding isn't - * needed because typing control-C at the console would deliver SIGINT to - * every member of the terminal process group --- but in other scenarios it - * might be that only the leader gets signaled. + * On Unix, the signal handler wakes up a dedicated cancel thread via a + * self-pipe, which then sends the cancel and calls _exit(). This thread also + * forwards the signal to each child so they can also cancel their queries. In + * simple manual use of pg_dump/pg_restore, forwarding isn't needed because + * typing control-C at the console would deliver SIGINT to every member of the + * terminal process group --- but in other scenarios it might be that only the + * leader gets signaled. * * On Windows, the cancel handler runs in a separate thread, because that's * how SetConsoleCtrlHandler works. Because the workers are threads in this * same process, we set a flag (is_cancel_in_progress()) so they stay quiet * about the query cancellations instead of cluttering the screen, then send - * cancels on all active connections and return FALSE, which will allow the - * process to die. For safety's sake, we use a critical section to protect - * the PGcancel structures against being changed while the signal thread runs. + * cancels on all active connections and call _exit() to terminate the + * process. Access to the shared PGcancelConn structures is serialized against + * the main thread by the cancel thread lock held around the callback. */ -#ifndef WIN32 - /* - * Signal handler (Unix only) + * Cancel all active queries, print a termination message, and exit. + * + * Invoked from the cancel thread (Unix) or the Windows console handler thread. + * It never returns: after sending the cancels it calls _exit() so that the + * process terminates on cancel. We use _exit() rather than exit() because the + * latter would invoke atexit handlers that can fail if we interrupted related + * code. */ -static void -sigTermHandler(SIGNAL_ARGS) +pg_noreturn static void +CancelBackendsAndExit(void) { - int i; - char errbuf[1]; +#ifdef WIN32 /* - * Some platforms allow delivery of new signals to interrupt an active - * signal handler. That could muck up our attempt to send PQcancel, so - * disable the signals that set_cancel_handler enabled. + * On Windows the workers are threads within this same process. Once we + * cancel their queries below they would receive the cancellation as an + * error and report it, cluttering the user's screen in the brief window + * before the process exits. Tell them to stay quiet about it by setting + * a flag. This must be set before we send any cancel, so that a worker is + * guaranteed to see it by the time its query fails as a result. */ - pqsignal(SIGINT, PG_SIG_IGN); - pqsignal(SIGTERM, PG_SIG_IGN); - pqsignal(SIGQUIT, PG_SIG_IGN); + set_cancel_in_progress(); +#endif /* - * If we're in the leader, forward signal to all workers. (It seems best - * to do this before PQcancel; killing the leader transaction will result - * in invalid-snapshot errors from active workers, which maybe we can - * quiet by killing workers first.) Ignore any errors. + * Stop workers first to avoid invalid-snapshot errors if the leader + * cancels before workers. */ - if (signal_info.pstate != NULL) - { - for (i = 0; i < signal_info.pstate->numWorkers; i++) - { - pid_t pid = signal_info.pstate->parallelSlot[i].pid; + StopWorkers(); - if (pid != 0) - kill(pid, SIGTERM); - } - } + if (signal_info.myAH != NULL && signal_info.myAH->cancelConn != NULL) + (void) PQcancelBlocking(signal_info.myAH->cancelConn); /* - * Send QueryCancel if we have a connection to send to. Ignore errors, - * there's not much we can do about them anyway. - */ - if (signal_info.myAH != NULL && signal_info.myAH->connCancel != NULL) - (void) PQcancel(signal_info.myAH->connCancel, errbuf, sizeof(errbuf)); - - /* - * Report we're quitting, using nothing more complicated than write(2). - * When in parallel operation, only the leader process should do this. + * Print termination message. In parallel operation, only the leader + * should print this. On Windows, workers are threads in the same process + * and the console handler only runs in the leader context, so we can + * always print it. */ +#ifndef WIN32 if (!signal_info.am_worker) +#endif { if (progname) { @@ -597,106 +566,42 @@ sigTermHandler(SIGNAL_ARGS) write_stderr("terminated by user\n"); } - /* - * And die, using _exit() not exit() because the latter will invoke atexit - * handlers that can fail if we interrupted related code. - */ _exit(1); } /* - * Enable cancel interrupt handler, if not already done. - */ -static void -set_cancel_handler(void) -{ - /* - * When forking, signal_info.handler_set will propagate into the new - * process, but that's fine because the signal handler state does too. - */ - if (!signal_info.handler_set) - { - signal_info.handler_set = true; - - pqsignal(SIGINT, sigTermHandler); - pqsignal(SIGTERM, sigTermHandler); - pqsignal(SIGQUIT, sigTermHandler); - } -} - -#else /* WIN32 */ - -/* - * Console interrupt handler --- runs in a newly-started thread. + * Stop all worker processes/threads. * - * After stopping other threads and sending cancel requests on all open - * connections, we return FALSE which will allow the default ExitProcess() - * action to be taken. + * On Unix, send SIGTERM to each worker process; their signal handlers will + * send cancel requests to their backends. + * + * On Windows, workers are threads in the same process, so we send cancel + * requests directly to their backends. + * + * Caller must hold the cancel thread lock (via LockCancelThread). */ -static BOOL WINAPI -consoleHandler(DWORD dwCtrlType) +static void +StopWorkers(void) { int i; - char errbuf[1]; - - if (dwCtrlType == CTRL_C_EVENT || - dwCtrlType == CTRL_BREAK_EVENT) - { - /* - * Tell worker threads to stay quiet about the query cancellations - * we're about to send them; otherwise they'd report them as errors - * and clutter the user's screen. This must be set before we send any - * cancel, so that a worker is guaranteed to see it by the time its - * query fails as a result. - */ - set_cancel_in_progress(); - /* Critical section prevents changing data we look at here */ - EnterCriticalSection(&signal_info_lock); - - /* - * If in parallel mode, send QueryCancel to each worker's connected - * backend. Do this before canceling the main transaction, else we - * might get invalid-snapshot errors reported before we can stop the - * workers. Ignore errors, there's not much we can do about them - * anyway. - */ - if (signal_info.pstate != NULL) - { - for (i = 0; i < signal_info.pstate->numWorkers; i++) - { - ArchiveHandle *AH = signal_info.pstate->parallelSlot[i].AH; - - if (AH != NULL && AH->connCancel != NULL) - (void) PQcancel(AH->connCancel, errbuf, sizeof(errbuf)); - } - } + if (signal_info.pstate == NULL) + return; - /* - * Send QueryCancel to leader connection, if enabled. Ignore errors, - * there's not much we can do about them anyway. - */ - if (signal_info.myAH != NULL && signal_info.myAH->connCancel != NULL) - (void) PQcancel(signal_info.myAH->connCancel, - errbuf, sizeof(errbuf)); + for (i = 0; i < signal_info.pstate->numWorkers; i++) + { +#ifndef WIN32 + pid_t pid = signal_info.pstate->parallelSlot[i].pid; - LeaveCriticalSection(&signal_info_lock); + if (pid != 0) + kill(pid, SIGTERM); +#else + ArchiveHandle *AH = signal_info.pstate->parallelSlot[i].AH; - /* - * Report we're quitting, using nothing more complicated than - * write(2). We should be able to use pg_log_*() here, but for now we - * stay aligned with the sigTermHandler behavior. - */ - if (progname) - { - write_stderr(progname); - write_stderr(": "); - } - write_stderr("terminated by user\n"); + if (AH != NULL && AH->cancelConn != NULL) + (void) PQcancelBlocking(AH->cancelConn); +#endif } - - /* Always return FALSE to allow signal handling to continue */ - return FALSE; } /* @@ -705,58 +610,55 @@ consoleHandler(DWORD dwCtrlType) static void set_cancel_handler(void) { - if (!signal_info.handler_set) - { - signal_info.handler_set = true; + if (signal_info.handler_set) + return; - InitializeCriticalSection(&signal_info_lock); + signal_info.handler_set = true; - SetConsoleCtrlHandler(consoleHandler, TRUE); - } -} + setup_cancel_handler(NULL, CancelBackendsAndExit); -#endif /* WIN32 */ +#ifndef WIN32 + pqsignal(SIGTERM, CancelSignalHandler); + pqsignal(SIGQUIT, CancelSignalHandler); +#endif +} /* * set_archive_cancel_info * - * Fill AH->connCancel with cancellation info for the specified database + * Fill AH->cancelConn with cancellation info for the specified database * connection; or clear it if conn is NULL. */ void set_archive_cancel_info(ArchiveHandle *AH, PGconn *conn) { - PGcancel *oldConnCancel; + PGcancelConn *oldCancelConn; /* - * Activate the interrupt handler if we didn't yet in this process. On - * Windows, this also initializes signal_info_lock; therefore it's + * Activate the interrupt handler if we didn't yet in this process. It's * important that this happen at least once before we fork off any * threads. */ set_cancel_handler(); /* - * On Unix, we assume that storing a pointer value is atomic with respect - * to any possible signal interrupt. On Windows, use a critical section. + * Use mutex to prevent the cancel handler from using the pointer while + * we're changing it. */ - -#ifdef WIN32 - EnterCriticalSection(&signal_info_lock); -#endif + LockCancelThread(); /* Free the old one if we have one */ - oldConnCancel = AH->connCancel; + oldCancelConn = AH->cancelConn; /* be sure interrupt handler doesn't use pointer while freeing */ - AH->connCancel = NULL; + AH->cancelConn = NULL; - if (oldConnCancel != NULL) - PQfreeCancel(oldConnCancel); + if (oldCancelConn != NULL) + PQcancelFinish(oldCancelConn); /* Set the new one if specified */ if (conn) - AH->connCancel = PQgetCancel(conn); + AH->cancelConn = PQcancelCreate(conn); /* * On Unix, there's only ever one active ArchiveHandle per process, so we @@ -772,49 +674,35 @@ set_archive_cancel_info(ArchiveHandle *AH, PGconn *conn) signal_info.myAH = AH; #endif -#ifdef WIN32 - LeaveCriticalSection(&signal_info_lock); -#endif + UnlockCancelThread(); } /* * set_cancel_pstate * * Set signal_info.pstate to point to the specified ParallelState, if any. - * We need this mainly to have an interlock against Windows signal thread. + * We need this mainly to have an interlock against the cancel handler thread. */ static void set_cancel_pstate(ParallelState *pstate) { -#ifdef WIN32 - EnterCriticalSection(&signal_info_lock); -#endif - + LockCancelThread(); signal_info.pstate = pstate; - -#ifdef WIN32 - LeaveCriticalSection(&signal_info_lock); -#endif + UnlockCancelThread(); } /* * set_cancel_slot_archive * * Set ParallelSlot's AH field to point to the specified archive, if any. - * We need this mainly to have an interlock against Windows signal thread. + * We need this mainly to have an interlock against the cancel handler thread. */ static void set_cancel_slot_archive(ParallelSlot *slot, ArchiveHandle *AH) { -#ifdef WIN32 - EnterCriticalSection(&signal_info_lock); -#endif - + LockCancelThread(); slot->AH = AH; - -#ifdef WIN32 - LeaveCriticalSection(&signal_info_lock); -#endif + UnlockCancelThread(); } @@ -929,7 +817,7 @@ ParallelBackupStart(ArchiveHandle *AH) /* * Temporarily disable query cancellation on the leader connection. This - * ensures that child processes won't inherit valid AH->connCancel + * ensures that child processes won't inherit valid AH->cancelConn * settings and thus won't try to issue cancels against the leader's * connection. No harm is done if we fail while it's disabled, because * the leader connection is idle at this point anyway. @@ -947,6 +835,7 @@ ParallelBackupStart(ArchiveHandle *AH) uintptr_t handle; #else pid_t pid; + sigset_t cancel_set; #endif ParallelSlot *slot = &(pstate->parallelSlot[i]); int pipeMW[2], @@ -977,6 +866,18 @@ ParallelBackupStart(ArchiveHandle *AH) slot->hThread = handle; slot->workerStatus = WRKR_IDLE; #else /* !WIN32 */ + + /* + * Block signals before fork so that no signal can arrive in the child + * before ResetCancelAfterFork() has cleaned up the inherited cancel + * state (pipe fds, signal handlers, mutex). + */ + sigemptyset(&cancel_set); + sigaddset(&cancel_set, SIGINT); + sigaddset(&cancel_set, SIGTERM); + sigaddset(&cancel_set, SIGQUIT); + sigprocmask(SIG_BLOCK, &cancel_set, NULL); + pid = fork(); if (pid == 0) { @@ -989,6 +890,12 @@ ParallelBackupStart(ArchiveHandle *AH) /* instruct signal handler that we're in a worker now */ signal_info.am_worker = true; + signal_info.handler_set = false; + ResetCancelAfterFork(); + pqsignal(SIGTERM, PG_SIG_DFL); + pqsignal(SIGQUIT, PG_SIG_DFL); + sigprocmask(SIG_UNBLOCK, &cancel_set, NULL); + /* close read end of Worker -> Leader */ closesocket(pipeWM[PIPE_READ]); /* close write end of Leader -> Worker */ @@ -1017,6 +924,8 @@ ParallelBackupStart(ArchiveHandle *AH) } /* In Leader after successful fork */ + sigprocmask(SIG_UNBLOCK, &cancel_set, NULL); + slot->pid = pid; slot->workerStatus = WRKR_IDLE; @@ -1405,8 +1314,12 @@ ListenToWorkers(ArchiveHandle *AH, ParallelState *pstate, bool do_wait) if (!msg) { - /* If do_wait is true, we must have detected EOF on some socket */ - if (do_wait) + /* + * If do_wait is true, we must have detected EOF on some socket. If + * it's due to a cancel request, that's expected, otherwise it's a + * problem. + */ + if (do_wait && !CancelRequested) pg_fatal("a worker process died unexpectedly"); return false; } diff --git a/src/bin/pg_dump/pg_backup_archiver.c b/src/bin/pg_dump/pg_backup_archiver.c index d3e0006fa07..0ca06a7b6a0 100644 --- a/src/bin/pg_dump/pg_backup_archiver.c +++ b/src/bin/pg_dump/pg_backup_archiver.c @@ -5218,7 +5218,7 @@ CloneArchive(ArchiveHandle *AH) /* The clone will have its own connection, so disregard connection state */ clone->connection = NULL; - clone->connCancel = NULL; + clone->cancelConn = NULL; clone->currUser = NULL; clone->currSchema = NULL; clone->currTableAm = NULL; diff --git a/src/bin/pg_dump/pg_backup_archiver.h b/src/bin/pg_dump/pg_backup_archiver.h index c1528d78853..28febac0c43 100644 --- a/src/bin/pg_dump/pg_backup_archiver.h +++ b/src/bin/pg_dump/pg_backup_archiver.h @@ -288,8 +288,12 @@ struct _archiveHandle char *savedPassword; /* password for ropt->username, if known */ char *use_role; PGconn *connection; - /* If connCancel isn't NULL, SIGINT handler will send a cancel */ - PGcancel *volatile connCancel; + + /* + * If cancelConn isn't NULL, SIGINT handler will trigger the cancel thread + * to send a cancel. + */ + PGcancelConn *cancelConn; int connectToDB; /* Flag to indicate if direct DB connection is * required */ diff --git a/src/bin/pg_dump/pg_backup_db.c b/src/bin/pg_dump/pg_backup_db.c index c226d2470ed..1bc0aa24530 100644 --- a/src/bin/pg_dump/pg_backup_db.c +++ b/src/bin/pg_dump/pg_backup_db.c @@ -84,7 +84,7 @@ ReconnectToServer(ArchiveHandle *AH, const char *dbname) /* * Note: we want to establish the new connection, and in particular update - * ArchiveHandle's connCancel, before closing old connection. Otherwise + * ArchiveHandle's cancelConn, before closing old connection. Otherwise * an ill-timed SIGINT could try to access a dead connection. */ AH->connection = NULL; /* dodge error check in ConnectDatabaseAhx */ @@ -164,12 +164,11 @@ void DisconnectDatabase(Archive *AHX) { ArchiveHandle *AH = (ArchiveHandle *) AHX; - char errbuf[1]; if (!AH->connection) return; - if (AH->connCancel) + if (AH->cancelConn) { /* * If we have an active query, send a cancel before closing, ignoring @@ -177,7 +176,7 @@ DisconnectDatabase(Archive *AHX) * helpful during pg_fatal(). */ if (PQtransactionStatus(AH->connection) == PQTRANS_ACTIVE) - (void) PQcancel(AH->connCancel, errbuf, sizeof(errbuf)); + (void) PQcancelBlocking(AH->cancelConn); /* * Prevent signal handler from sending a cancel after this. diff --git a/src/bin/pgbench/pgbench.c b/src/bin/pgbench/pgbench.c index 06c43fd6942..cd6e640e874 100644 --- a/src/bin/pgbench/pgbench.c +++ b/src/bin/pgbench/pgbench.c @@ -5346,7 +5346,7 @@ runInitSteps(const char *initialize_steps) if ((con = doConnect()) == NULL) pg_fatal("could not create connection for initialization"); - setup_cancel_handler(NULL); + setup_cancel_handler(NULL, NULL); SetCancelConn(con); for (step = initialize_steps; *step != '\0'; step++) diff --git a/src/bin/psql/common.c b/src/bin/psql/common.c index becb22ea7e2..6351384bdf8 100644 --- a/src/bin/psql/common.c +++ b/src/bin/psql/common.c @@ -308,23 +308,27 @@ volatile sig_atomic_t sigint_interrupt_enabled = false; sigjmp_buf sigint_interrupt_jmp; +#ifndef WIN32 static void psql_cancel_callback(void) { -#ifndef WIN32 /* if we are waiting for input, longjmp out of it */ if (sigint_interrupt_enabled) { sigint_interrupt_enabled = false; siglongjmp(sigint_interrupt_jmp, 1); } -#endif } +#endif void psql_setup_cancel_handler(void) { - setup_cancel_handler(psql_cancel_callback); +#ifndef WIN32 + setup_cancel_handler(psql_cancel_callback, NULL); +#else + setup_cancel_handler(NULL, NULL); +#endif } diff --git a/src/bin/scripts/clusterdb.c b/src/bin/scripts/clusterdb.c index 53bbb42c883..f282a88c76d 100644 --- a/src/bin/scripts/clusterdb.c +++ b/src/bin/scripts/clusterdb.c @@ -140,7 +140,7 @@ main(int argc, char *argv[]) cparams.prompt_password = prompt_password; cparams.override_dbname = NULL; - setup_cancel_handler(NULL); + setup_cancel_handler(NULL, NULL); if (alldb) { diff --git a/src/bin/scripts/reindexdb.c b/src/bin/scripts/reindexdb.c index f955a6f0547..af0e75c483d 100644 --- a/src/bin/scripts/reindexdb.c +++ b/src/bin/scripts/reindexdb.c @@ -211,7 +211,7 @@ main(int argc, char *argv[]) cparams.prompt_password = prompt_password; cparams.override_dbname = NULL; - setup_cancel_handler(NULL); + setup_cancel_handler(NULL, NULL); if (concurrentCons > 1 && syscatalog) pg_fatal("cannot use multiple jobs to reindex system catalogs"); diff --git a/src/bin/scripts/vacuuming.c b/src/bin/scripts/vacuuming.c index e38c8d401ac..834e6e33efb 100644 --- a/src/bin/scripts/vacuuming.c +++ b/src/bin/scripts/vacuuming.c @@ -70,7 +70,7 @@ vacuuming_main(ConnParams *cparams, const char *dbname, unsigned int tbl_count, int concurrentCons, const char *progname) { - setup_cancel_handler(NULL); + setup_cancel_handler(NULL, NULL); /* Avoid opening extra connections. */ if (tbl_count > 0 && (concurrentCons > tbl_count)) diff --git a/src/fe_utils/cancel.c b/src/fe_utils/cancel.c index 0de2ccf684c..be8ce65f039 100644 --- a/src/fe_utils/cancel.c +++ b/src/fe_utils/cancel.c @@ -3,7 +3,7 @@ * Query cancellation support for frontend code * * This module provides SIGINT/Ctrl-C handling for frontend tools that need to - * cancel queries or interrupt other operations. It provides three + * cancel queries or interrupt other operations. It provides four * independent mechanisms, any combination of which can be used by an * application: * @@ -13,9 +13,9 @@ * calling SetCancelConn() to register the connection that is (or will be) * running the query, prior to waiting for the result. When SIGINT/Ctrl-C * is received, a cancel request for this connection will then be sent from - * the signal handler (on Windows, from a separate thread). That in turn - * will then (assuming a co-operating server) cause the server to cancel - * the query and send an error to the waiting client on the main thread. + * a separate thread. That in turn will then (assuming a co-operating + * server) cause the server to cancel the query and send an error to the + * waiting client on the main thread. * The cancel connection is a process-wide global, so only one connection * can be the cancel target at a time. ResetCancelConn() should be called * to disarm the mechanism again after the blocking wait has completed. @@ -26,11 +26,21 @@ * not blocked (indefinitely), but needs to take an action when Ctrl-C is * pressed, such as break out of a long running loop. * - * 3. Signal handler callback -- A callback function can be registered with + * 3. Thread handler callback -- A callback function can be registered with + * setup_cancel_handler(), which will then be called whenever SIGINT is + * received. Unlike the signal handler callback below, it does not run in + * the signal handler but in the same separate thread that sends the cancel + * request (the dedicated cancel thread on Unix, the console handler thread + * on Windows), so it need not be async-signal-safe. That thread holds + * cancel_thread_lock while the callback runs, so code sharing data with the + * callback should take the same lock via + * LockCancelThread()/UnlockCancelThread(). + * + * 4. Signal handler callback -- A callback function can be registered with * setup_cancel_handler(), which will then be called directly from the * signal handler whenever SIGINT is received. Because it is called from a * signal handler, the callback function must be async-signal-safe. On - * Windows, it is called from a separate signal-handling thread. NOTE: The + * Windows, this callback is never called. NOTE: The * callback is called AFTER setting CancelRequested but BEFORE sending the * cancel request to the server (if armed by SetCancelConn). This means * that if the callback exits or longjmps, no cancel request will be sent @@ -46,9 +56,21 @@ #include "postgres_fe.h" +#include <signal.h> #include <unistd.h> +#ifndef WIN32 +#include <fcntl.h> +#endif + +#ifdef WIN32 +#include "port/pthread-win32.h" +#else +#include <pthread.h> +#endif + #include "common/connect.h" +#include "common/logging.h" #include "fe_utils/cancel.h" #include "fe_utils/string_utils.h" @@ -66,11 +88,19 @@ (void) rc_; \ } while (0) + +/* + * Cancel connection that should be used to send cancel requests. + */ +static PGcancelConn *cancelConn = NULL; + /* - * Contains all the information needed to cancel a query issued from - * a database connection to the backend. + * Mutex held by the cancel thread for the duration of the cancel callback. + * SetCancelConn()/ResetCancelConn() on the main thread take this lock too, + * so they will wait for any in-flight cancel to finish before replacing or + * freeing cancelConn. */ -static PGcancel *volatile cancelConn = NULL; +static pthread_mutex_t cancel_thread_lock = PTHREAD_MUTEX_INITIALIZER; /* * Predetermined localized error strings --- needed to avoid trying @@ -88,168 +118,183 @@ static const char *cancel_not_sent_msg = NULL; */ volatile sig_atomic_t CancelRequested = false; -#ifdef WIN32 -static CRITICAL_SECTION cancelConnLock; -#endif +/* + * Signal handler callback, called directly from signal handler context. + * Must be async-signal-safe. + */ +static void (*signal_callback_fn) (void) = NULL; /* - * Additional callback for cancellations. + * Cancel thread callback, called from the cancel thread (Unix) or console + * handler (Windows) when a cancel signal is received. */ -static void (*cancel_callback) (void) = NULL; +static void (*thread_callback_fn) (void) = NULL; + +#ifndef WIN32 +/* + * On Unix, the SIGINT signal handler cannot call PQcancelBlocking() directly + * because it is not async-signal-safe. Instead, we use a pipe to wake a + * dedicated cancel thread: the signal handler writes a byte to the pipe, and + * the cancel thread's blocking read() returns, triggering the actual cancel + * request. + */ +static int cancel_pipe[2] = {-1, -1}; +#endif /* - * SetCancelConn + * Send a cancel request to the connection, if one is set. * - * Set cancelConn to point to the current database connection. + * Called from the cancel thread (Unix) or the console handler thread + * (Windows), never from the signal handler itself. The caller is + * responsible for holding cancel_thread_lock. */ -void -SetCancelConn(PGconn *conn) +static void +SendCancelRequest(void) { - PGcancel *oldCancelConn; - -#ifdef WIN32 - EnterCriticalSection(&cancelConnLock); -#endif + PGcancelConn *cc; - /* Free the old one if we have one */ - oldCancelConn = cancelConn; - - /* be sure handle_sigint doesn't use pointer while freeing */ - cancelConn = NULL; + cc = cancelConn; + if (cc == NULL) + return; - if (oldCancelConn != NULL) - PQfreeCancel(oldCancelConn); + if (PQcancelBlocking(cc)) + { + write_stderr(cancel_sent_msg); + } + else + { + char *errmsg = PQcancelErrorMessage(cc); - cancelConn = PQgetCancel(conn); + write_stderr(cancel_not_sent_msg); + if (errmsg) + write_stderr(errmsg); + } -#ifdef WIN32 - LeaveCriticalSection(&cancelConnLock); -#endif + /* Reset for possible reuse */ + PQcancelReset(cc); } + /* - * ResetCancelConn + * Helper to replace cancelConn with a new value. * - * Free the current cancel connection, if any, and set to NULL. + * Takes cancel_thread_lock, which also waits for any in-flight cancel + * callback to finish, since the cancel thread holds the same lock. */ -void -ResetCancelConn(void) +static void +SetCancelConnInternal(PGcancelConn *newCancelConn) { - PGcancel *oldCancelConn; - -#ifdef WIN32 - EnterCriticalSection(&cancelConnLock); -#endif + PGcancelConn *oldCancelConn; + LockCancelThread(); oldCancelConn = cancelConn; - - /* be sure handle_sigint doesn't use pointer while freeing */ - cancelConn = NULL; + cancelConn = newCancelConn; + UnlockCancelThread(); if (oldCancelConn != NULL) - PQfreeCancel(oldCancelConn); - -#ifdef WIN32 - LeaveCriticalSection(&cancelConnLock); -#endif + PQcancelFinish(oldCancelConn); } - /* - * Code to support query cancellation - * - * Note that sending the cancel directly from the signal handler is safe - * because PQcancel() is written to make it so. We use write() to report - * to stderr because it's better to use simple facilities in a signal - * handler. + * SetCancelConn * - * On Windows, the signal canceling happens on a separate thread, because - * that's how SetConsoleCtrlHandler works. The PQcancel function is safe - * for this (unlike PQrequestCancel). However, a CRITICAL_SECTION is required - * to protect the PGcancel structure against being changed while the signal - * thread is using it. + * Set cancelConn to point to a cancel connection for the given database + * connection. This creates a new PGcancelConn that can be used to send + * cancel requests. */ - -#ifndef WIN32 +void +SetCancelConn(PGconn *conn) +{ + SetCancelConnInternal(PQcancelCreate(conn)); +} /* - * handle_sigint + * ResetCancelConn * - * Handle interrupt signals by canceling the current command, if cancelConn - * is set. + * Clear cancelConn, preventing any pending cancel from being sent. + * Waits for any in-flight cancel request to complete first. */ -static void -handle_sigint(SIGNAL_ARGS) +void +ResetCancelConn(void) { - char errbuf[256]; + SetCancelConnInternal(NULL); +} - CancelRequested = true; - if (cancel_callback != NULL) - cancel_callback(); +/* + * LockCancelThread / UnlockCancelThread + * + * Acquire or release cancel_thread_lock. External callers (e.g. pg_dump) + * use these to protect shared data that the cancel-thread callback also + * accesses, without exposing the mutex directly. + */ +void +LockCancelThread(void) +{ + pthread_mutex_lock(&cancel_thread_lock); +} - /* Send QueryCancel if we are processing a database query */ - if (cancelConn != NULL) - { - if (PQcancel(cancelConn, errbuf, sizeof(errbuf))) - { - write_stderr(cancel_sent_msg); - } - else - { - write_stderr(cancel_not_sent_msg); - write_stderr(errbuf); - } - } +void +UnlockCancelThread(void) +{ + pthread_mutex_unlock(&cancel_thread_lock); } +#ifndef WIN32 /* - * setup_cancel_handler + * ResetCancelAfterFork + * + * Reset cancel module state after fork(). Threads don't survive fork(), so the + * cancel thread and its pipe are gone. The mutex may have been held by the + * cancel thread at fork time, so we must reinitialize it rather than trying to + * unlock it. cancelConn is NULLed without freeing because the parent process + * owns the underlying object. The SIGINT handler is reset to SIG_DFL so that + * a signal arriving before setup_cancel_handler() is called again doesn't try + * to write to the closed pipe. * - * Register query cancellation callback for SIGINT. + * The child will set up a fresh cancel thread when it later calls + * setup_cancel_handler(). */ void -setup_cancel_handler(void (*query_cancel_callback) (void)) +ResetCancelAfterFork(void) { - cancel_callback = query_cancel_callback; - cancel_sent_msg = _("Cancel request sent\n"); - cancel_not_sent_msg = _("Could not send cancel request: "); + close(cancel_pipe[0]); + close(cancel_pipe[1]); + cancel_pipe[0] = cancel_pipe[1] = -1; - pqsignal(SIGINT, handle_sigint); -} + pthread_mutex_init(&cancel_thread_lock, NULL); + + cancelConn = NULL; + CancelRequested = false; -#else /* WIN32 */ + pqsignal(SIGINT, PG_SIG_DFL); +} +#endif +#ifdef WIN32 +/* + * Console control handler for Windows. + * + * This runs in a separate thread created by the OS, so we can safely call + * the blocking cancel API directly. + */ static BOOL WINAPI consoleHandler(DWORD dwCtrlType) { - char errbuf[256]; - if (dwCtrlType == CTRL_C_EVENT || dwCtrlType == CTRL_BREAK_EVENT) { CancelRequested = true; - if (cancel_callback != NULL) - cancel_callback(); + LockCancelThread(); - /* Send QueryCancel if we are processing a database query */ - EnterCriticalSection(&cancelConnLock); - if (cancelConn != NULL) - { - if (PQcancel(cancelConn, errbuf, sizeof(errbuf))) - { - write_stderr(cancel_sent_msg); - } - else - { - write_stderr(cancel_not_sent_msg); - write_stderr(errbuf); - } - } + SendCancelRequest(); + + if (thread_callback_fn != NULL) + thread_callback_fn(); - LeaveCriticalSection(&cancelConnLock); + UnlockCancelThread(); return TRUE; } @@ -258,16 +303,169 @@ consoleHandler(DWORD dwCtrlType) return FALSE; } +#else /* !WIN32 */ + +/* + * Signal handler that setup_cancel_handler configures for SIGINT. Exposed so + * other signals than SIGINT can use it if desired. + */ void -setup_cancel_handler(void (*callback) (void)) +CancelSignalHandler(SIGNAL_ARGS) +{ + int save_errno = errno; + + CancelRequested = true; + + if (signal_callback_fn != NULL) + signal_callback_fn(); + + /* Wake up the cancel thread */ + if (cancel_pipe[1] >= 0) + { + char c = 1; + int rc = write(cancel_pipe[1], &c, 1); + + (void) rc; + } + + errno = save_errno; +} + +/* + * Thread main function for create_cancel_thread. Waits for the signal + * handler to write a byte to the pipe, then calls the cancel callback. + */ +static void * +cancel_thread_loop(void *arg) { - cancel_callback = callback; + for (;;) + { + char buf[16]; + ssize_t rc; + + rc = read(cancel_pipe[0], buf, sizeof(buf)); + if (rc <= 0) + { + if (errno == EINTR) + continue; + /* Pipe closed or error - exit thread */ + break; + } + + LockCancelThread(); + + SendCancelRequest(); + + if (thread_callback_fn != NULL) + thread_callback_fn(); + + /* + * Drain any pending bytes from the cancel pipe, so that signals + * received while we were already handling a cancel don't cause us to + * wake up again and cancel a subsequent query. + */ + fcntl(cancel_pipe[0], F_SETFL, O_NONBLOCK); + while (read(cancel_pipe[0], buf, sizeof(buf)) > 0) + ; /* loop until pipe is fully drained */ + fcntl(cancel_pipe[0], F_SETFL, 0); + + UnlockCancelThread(); + } + + return NULL; +} + +/* + * create_cancel_thread + * + * Create a dedicated thread and associated pipe for async-signal-safe cancel + * handling. The pipe allows signal handlers (which cannot safely call complex + * functions) to wake up the thread by writing a byte. + * + * The write end of the pipe is set non-blocking so signal handlers never + * block. The thread is created with all signals blocked so that signals are + * always delivered to the main thread. The thread runs until process exit. + * No handle is returned because currently no callers need to join it. + */ +static void +create_cancel_thread(void) +{ + sigset_t save_set; + sigset_t block_set; + pthread_t thread; + int rc; + + if (pipe(cancel_pipe) < 0) + { + pg_log_error("could not create pipe for cancel: %m"); + exit(1); + } + + /* + * Make the write end non-blocking, so that the signal handler won't block + * if the pipe buffer is full (which is very unlikely in practice but + * possible in theory). + */ + fcntl(cancel_pipe[1], F_SETFL, O_NONBLOCK); + + /* + * Block all signals before creating the cancel thread, so that it + * inherits a signal mask with all signals blocked. This ensures signals + * are always delivered to the main thread, which matters because some + * signal_callback functions call siglongjmp() back to a sigsetjmp() on + * the main thread's stack, specifically the psql_cancel_callback + * function. + */ + sigfillset(&block_set); + pthread_sigmask(SIG_BLOCK, &block_set, &save_set); + + rc = pthread_create(&thread, NULL, cancel_thread_loop, NULL); + + pthread_sigmask(SIG_SETMASK, &save_set, NULL); + + if (rc != 0) + { + pg_log_error("could not create cancel thread: %s", strerror(rc)); + exit(1); + } + + pthread_detach(thread); +} + +#endif /* !WIN32 */ + + +/* + * setup_cancel_handler + * + * Set up signal handling for SIGINT (Unix) or console events (Windows) to + * perform cancel actions. + * + * signal_callback is invoked directly from the signal handler context on + * every SIGINT (on Unix), so it must be async-signal-safe. Can be NULL. + * On Windows, signal handlers don't exist (the console handler runs in a + * separate thread), so signal_callback must be NULL. + * + * thread_callback is invoked from a dedicated cancel thread (Unix) or the + * console handler thread (Windows) when a signal is received. Can be NULL. + */ +void +setup_cancel_handler(void (*signal_callback) (void), + void (*thread_callback) (void)) +{ +#ifdef WIN32 + Assert(signal_callback == NULL); +#endif + + signal_callback_fn = signal_callback; + thread_callback_fn = thread_callback; cancel_sent_msg = _("Cancel request sent\n"); cancel_not_sent_msg = _("Could not send cancel request: "); - InitializeCriticalSection(&cancelConnLock); - +#ifdef WIN32 SetConsoleCtrlHandler(consoleHandler, TRUE); +#else + create_cancel_thread(); + pqsignal(SIGINT, CancelSignalHandler); +#endif } - -#endif /* WIN32 */ diff --git a/src/include/fe_utils/cancel.h b/src/include/fe_utils/cancel.h index e174fb83b92..feb1970d372 100644 --- a/src/include/fe_utils/cancel.h +++ b/src/include/fe_utils/cancel.h @@ -23,10 +23,15 @@ extern PGDLLIMPORT volatile sig_atomic_t CancelRequested; extern void SetCancelConn(PGconn *conn); extern void ResetCancelConn(void); -/* - * A callback can be optionally set up to be called at cancellation - * time. - */ -extern void setup_cancel_handler(void (*query_cancel_callback) (void)); +extern void setup_cancel_handler(void (*signal_callback) (void), + void (*thread_callback) (void)); + +extern void LockCancelThread(void); +extern void UnlockCancelThread(void); + +#ifndef WIN32 +extern void ResetCancelAfterFork(void); +extern void CancelSignalHandler(SIGNAL_ARGS); +#endif #endif /* CANCEL_H */ -- 2.56.1
