PostgreSQL Source Code  git master
parallel.c File Reference
#include "postgres_fe.h"
#include <sys/wait.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include "parallel.h"
#include "pg_backup_utils.h"
#include "fe_utils/string_utils.h"
#include "port/pg_bswap.h"
Include dependency graph for parallel.c:

Go to the source code of this file.

Data Structures

struct  ParallelSlot
 
struct  ShutdownInformation
 
struct  DumpSignalInformation
 

Macros

#define PIPE_READ   0
 
#define PIPE_WRITE   1
 
#define NO_SLOT   (-1) /* Failure result for GetIdleWorker() */
 
#define pgpipe(a)   pipe(a)
 
#define piperead(a, b, c)   read(a,b,c)
 
#define pipewrite(a, b, c)   write(a,b,c)
 
#define write_stderr(str)
 
#define messageStartsWith(msg, prefix)   (strncmp(msg, prefix, strlen(prefix)) == 0)
 

Typedefs

typedef struct ShutdownInformation ShutdownInformation
 
typedef struct DumpSignalInformation DumpSignalInformation
 

Enumerations

enum  T_WorkerStatus { WRKR_IDLE, WRKR_WORKING, WRKR_TERMINATED }
 

Functions

static ParallelSlotGetMyPSlot (ParallelState *pstate)
 
static void archive_close_connection (int code, void *arg)
 
static void ShutdownWorkersHard (ParallelState *pstate)
 
static void WaitForTerminatingWorkers (ParallelState *pstate)
 
static void setup_cancel_handler (void)
 
static void set_cancel_pstate (ParallelState *pstate)
 
static void set_cancel_slot_archive (ParallelSlot *slot, ArchiveHandle *AH)
 
static void RunWorker (ArchiveHandle *AH, ParallelSlot *slot)
 
static int GetIdleWorker (ParallelState *pstate)
 
static bool HasEveryWorkerTerminated (ParallelState *pstate)
 
static void lockTableForWorker (ArchiveHandle *AH, TocEntry *te)
 
static void WaitForCommands (ArchiveHandle *AH, int pipefd[2])
 
static bool ListenToWorkers (ArchiveHandle *AH, ParallelState *pstate, bool do_wait)
 
static char * getMessageFromMaster (int pipefd[2])
 
static void sendMessageToMaster (int pipefd[2], const char *str)
 
static int select_loop (int maxFd, fd_set *workerset)
 
static char * getMessageFromWorker (ParallelState *pstate, bool do_wait, int *worker)
 
static void sendMessageToWorker (ParallelState *pstate, int worker, const char *str)
 
static char * readMessageFromPipe (int fd)
 
void init_parallel_dump_utils (void)
 
void on_exit_close_archive (Archive *AHX)
 
static void sigTermHandler (SIGNAL_ARGS)
 
void set_archive_cancel_info (ArchiveHandle *AH, PGconn *conn)
 
ParallelStateParallelBackupStart (ArchiveHandle *AH)
 
void ParallelBackupEnd (ArchiveHandle *AH, ParallelState *pstate)
 
static void buildWorkerCommand (ArchiveHandle *AH, TocEntry *te, T_Action act, char *buf, int buflen)
 
static void parseWorkerCommand (ArchiveHandle *AH, TocEntry **te, T_Action *act, const char *msg)
 
static void buildWorkerResponse (ArchiveHandle *AH, TocEntry *te, T_Action act, int status, char *buf, int buflen)
 
static int parseWorkerResponse (ArchiveHandle *AH, TocEntry *te, const char *msg)
 
void DispatchJobForTocEntry (ArchiveHandle *AH, ParallelState *pstate, TocEntry *te, T_Action act, ParallelCompletionPtr callback, void *callback_data)
 
bool IsEveryWorkerIdle (ParallelState *pstate)
 
void WaitForWorkers (ArchiveHandle *AH, ParallelState *pstate, WFW_WaitOption mode)
 

Variables

static ShutdownInformation shutdown_info
 
static volatile DumpSignalInformation signal_info
 

Macro Definition Documentation

◆ messageStartsWith

#define messageStartsWith (   msg,
  prefix 
)    (strncmp(msg, prefix, strlen(prefix)) == 0)

Definition at line 224 of file parallel.c.

Referenced by ListenToWorkers(), parseWorkerCommand(), and parseWorkerResponse().

◆ NO_SLOT

#define NO_SLOT   (-1) /* Failure result for GetIdleWorker() */

Definition at line 74 of file parallel.c.

Referenced by DispatchJobForTocEntry(), GetIdleWorker(), and WaitForWorkers().

◆ pgpipe

#define pgpipe (   a)    pipe(a)

Definition at line 135 of file parallel.c.

Referenced by ParallelBackupStart(), and readMessageFromPipe().

◆ PIPE_READ

#define PIPE_READ   0

Definition at line 71 of file parallel.c.

Referenced by getMessageFromMaster(), ParallelBackupStart(), and RunWorker().

◆ PIPE_WRITE

#define PIPE_WRITE   1

Definition at line 72 of file parallel.c.

Referenced by ParallelBackupStart(), RunWorker(), and sendMessageToMaster().

◆ piperead

#define piperead (   a,
  b,
  c 
)    read(a,b,c)

Definition at line 136 of file parallel.c.

Referenced by readMessageFromPipe().

◆ pipewrite

#define pipewrite (   a,
  b,
  c 
)    write(a,b,c)

Definition at line 137 of file parallel.c.

Referenced by sendMessageToMaster(), and sendMessageToWorker().

◆ write_stderr

Typedef Documentation

◆ DumpSignalInformation

◆ ShutdownInformation

Enumeration Type Documentation

◆ T_WorkerStatus

Enumerator
WRKR_IDLE 
WRKR_WORKING 
WRKR_TERMINATED 

Definition at line 77 of file parallel.c.

Function Documentation

◆ archive_close_connection()

static void archive_close_connection ( int  code,
void *  arg 
)
static

Definition at line 354 of file parallel.c.

References ParallelSlot::AH, ShutdownInformation::AHX, closesocket, DisconnectDatabase(), GetMyPSlot(), ParallelSlot::pipeRevRead, ParallelSlot::pipeRevWrite, ShutdownInformation::pstate, _archiveHandle::public, and ShutdownWorkersHard().

Referenced by on_exit_close_archive().

355 {
357 
358  if (si->pstate)
359  {
360  /* In parallel mode, must figure out who we are */
361  ParallelSlot *slot = GetMyPSlot(si->pstate);
362 
363  if (!slot)
364  {
365  /*
366  * We're the master. Forcibly shut down workers, then close our
367  * own database connection, if any.
368  */
370 
371  if (si->AHX)
372  DisconnectDatabase(si->AHX);
373  }
374  else
375  {
376  /*
377  * We're a worker. Shut down our own DB connection if any. On
378  * Windows, we also have to close our communication sockets, to
379  * emulate what will happen on Unix when the worker process exits.
380  * (Without this, if this is a premature exit, the master would
381  * fail to detect it because there would be no EOF condition on
382  * the other end of the pipe.)
383  */
384  if (slot->AH)
385  DisconnectDatabase(&(slot->AH->public));
386 
387 #ifdef WIN32
388  closesocket(slot->pipeRevRead);
389  closesocket(slot->pipeRevWrite);
390 #endif
391  }
392  }
393  else
394  {
395  /* Non-parallel operation: just kill the master DB connection */
396  if (si->AHX)
397  DisconnectDatabase(si->AHX);
398  }
399 }
ArchiveHandle * AH
Definition: parallel.c:99
#define closesocket
Definition: port.h:312
static void ShutdownWorkersHard(ParallelState *pstate)
Definition: parallel.c:410
static ParallelSlot * GetMyPSlot(ParallelState *pstate)
Definition: parallel.c:279
int pipeRevRead
Definition: parallel.c:103
void DisconnectDatabase(Archive *AHX)
Definition: pg_backup_db.c:339
ParallelState * pstate
Definition: parallel.c:146
int pipeRevWrite
Definition: parallel.c:104
void * arg

◆ buildWorkerCommand()

static void buildWorkerCommand ( ArchiveHandle AH,
TocEntry te,
T_Action  act,
char *  buf,
int  buflen 
)
static

Definition at line 1122 of file parallel.c.

References ACT_DUMP, ACT_RESTORE, Assert, _tocEntry::dumpId, and snprintf.

Referenced by DispatchJobForTocEntry().

1124 {
1125  if (act == ACT_DUMP)
1126  snprintf(buf, buflen, "DUMP %d", te->dumpId);
1127  else if (act == ACT_RESTORE)
1128  snprintf(buf, buflen, "RESTORE %d", te->dumpId);
1129  else
1130  Assert(false);
1131 }
static char * buf
Definition: pg_test_fsync.c:68
#define Assert(condition)
Definition: c.h:732
#define snprintf
Definition: port.h:192

◆ buildWorkerResponse()

static void buildWorkerResponse ( ArchiveHandle AH,
TocEntry te,
T_Action  act,
int  status,
char *  buf,
int  buflen 
)
static

Definition at line 1170 of file parallel.c.

References _tocEntry::dumpId, Archive::n_errors, _archiveHandle::public, snprintf, and WORKER_IGNORED_ERRORS.

Referenced by WaitForCommands().

1172 {
1173  snprintf(buf, buflen, "OK %d %d %d",
1174  te->dumpId,
1175  status,
1177 }
int n_errors
Definition: pg_backup.h:206
#define WORKER_IGNORED_ERRORS
static char * buf
Definition: pg_test_fsync.c:68
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
#define snprintf
Definition: port.h:192

◆ DispatchJobForTocEntry()

void DispatchJobForTocEntry ( ArchiveHandle AH,
ParallelState pstate,
TocEntry te,
T_Action  act,
ParallelCompletionPtr  callback,
void *  callback_data 
)

Definition at line 1219 of file parallel.c.

References buf, buildWorkerCommand(), ParallelSlot::callback, ParallelSlot::callback_data, GetIdleWorker(), NO_SLOT, ParallelState::parallelSlot, sendMessageToWorker(), ParallelState::te, WaitForWorkers(), WFW_ONE_IDLE, ParallelSlot::workerStatus, and WRKR_WORKING.

Referenced by restore_toc_entries_parallel(), and WriteDataChunks().

1225 {
1226  int worker;
1227  char buf[256];
1228 
1229  /* Get a worker, waiting if none are idle */
1230  while ((worker = GetIdleWorker(pstate)) == NO_SLOT)
1231  WaitForWorkers(AH, pstate, WFW_ONE_IDLE);
1232 
1233  /* Construct and send command string */
1234  buildWorkerCommand(AH, te, act, buf, sizeof(buf));
1235 
1236  sendMessageToWorker(pstate, worker, buf);
1237 
1238  /* Remember worker is busy, and which TocEntry it's working on */
1239  pstate->parallelSlot[worker].workerStatus = WRKR_WORKING;
1240  pstate->parallelSlot[worker].callback = callback;
1241  pstate->parallelSlot[worker].callback_data = callback_data;
1242  pstate->te[worker] = te;
1243 }
static void buildWorkerCommand(ArchiveHandle *AH, TocEntry *te, T_Action act, char *buf, int buflen)
Definition: parallel.c:1122
void * callback_data
Definition: parallel.c:97
static int GetIdleWorker(ParallelState *pstate)
Definition: parallel.c:1250
#define NO_SLOT
Definition: parallel.c:74
static void callback(struct sockaddr *addr, struct sockaddr *mask, void *unused)
Definition: test_ifaddrs.c:48
static char * buf
Definition: pg_test_fsync.c:68
ParallelSlot * parallelSlot
Definition: parallel.h:45
static void sendMessageToWorker(ParallelState *pstate, int worker, const char *str)
Definition: parallel.c:1656
void WaitForWorkers(ArchiveHandle *AH, ParallelState *pstate, WFW_WaitOption mode)
Definition: parallel.c:1465
TocEntry ** te
Definition: parallel.h:44
ParallelCompletionPtr callback
Definition: parallel.c:96
T_WorkerStatus workerStatus
Definition: parallel.c:93

◆ GetIdleWorker()

static int GetIdleWorker ( ParallelState pstate)
static

Definition at line 1250 of file parallel.c.

References i, NO_SLOT, ParallelState::numWorkers, ParallelState::parallelSlot, ParallelSlot::workerStatus, and WRKR_IDLE.

Referenced by DispatchJobForTocEntry(), and WaitForWorkers().

1251 {
1252  int i;
1253 
1254  for (i = 0; i < pstate->numWorkers; i++)
1255  {
1256  if (pstate->parallelSlot[i].workerStatus == WRKR_IDLE)
1257  return i;
1258  }
1259  return NO_SLOT;
1260 }
#define NO_SLOT
Definition: parallel.c:74
ParallelSlot * parallelSlot
Definition: parallel.h:45
T_WorkerStatus workerStatus
Definition: parallel.c:93
int i
int numWorkers
Definition: parallel.h:42

◆ getMessageFromMaster()

static char * getMessageFromMaster ( int  pipefd[2])
static

Definition at line 1530 of file parallel.c.

References PIPE_READ, and readMessageFromPipe().

Referenced by WaitForCommands().

1531 {
1532  return readMessageFromPipe(pipefd[PIPE_READ]);
1533 }
#define PIPE_READ
Definition: parallel.c:71
static char * readMessageFromPipe(int fd)
Definition: parallel.c:1674

◆ getMessageFromWorker()

static char * getMessageFromWorker ( ParallelState pstate,
bool  do_wait,
int *  worker 
)
static

Definition at line 1593 of file parallel.c.

References Assert, fatal, i, ParallelState::numWorkers, ParallelState::parallelSlot, ParallelSlot::pipeRead, readMessageFromPipe(), select, select_loop(), ParallelSlot::workerStatus, and WRKR_TERMINATED.

Referenced by ListenToWorkers().

1594 {
1595  int i;
1596  fd_set workerset;
1597  int maxFd = -1;
1598  struct timeval nowait = {0, 0};
1599 
1600  /* construct bitmap of socket descriptors for select() */
1601  FD_ZERO(&workerset);
1602  for (i = 0; i < pstate->numWorkers; i++)
1603  {
1604  if (pstate->parallelSlot[i].workerStatus == WRKR_TERMINATED)
1605  continue;
1606  FD_SET(pstate->parallelSlot[i].pipeRead, &workerset);
1607  if (pstate->parallelSlot[i].pipeRead > maxFd)
1608  maxFd = pstate->parallelSlot[i].pipeRead;
1609  }
1610 
1611  if (do_wait)
1612  {
1613  i = select_loop(maxFd, &workerset);
1614  Assert(i != 0);
1615  }
1616  else
1617  {
1618  if ((i = select(maxFd + 1, &workerset, NULL, NULL, &nowait)) == 0)
1619  return NULL;
1620  }
1621 
1622  if (i < 0)
1623  fatal("select() failed: %m");
1624 
1625  for (i = 0; i < pstate->numWorkers; i++)
1626  {
1627  char *msg;
1628 
1629  if (!FD_ISSET(pstate->parallelSlot[i].pipeRead, &workerset))
1630  continue;
1631 
1632  /*
1633  * Read the message if any. If the socket is ready because of EOF,
1634  * we'll return NULL instead (and the socket will stay ready, so the
1635  * condition will persist).
1636  *
1637  * Note: because this is a blocking read, we'll wait if only part of
1638  * the message is available. Waiting a long time would be bad, but
1639  * since worker status messages are short and are always sent in one
1640  * operation, it shouldn't be a problem in practice.
1641  */
1642  msg = readMessageFromPipe(pstate->parallelSlot[i].pipeRead);
1643  *worker = i;
1644  return msg;
1645  }
1646  Assert(false);
1647  return NULL;
1648 }
int pipeRead
Definition: parallel.c:101
static int select_loop(int maxFd, fd_set *workerset)
Definition: parallel.c:1554
static char * readMessageFromPipe(int fd)
Definition: parallel.c:1674
#define select(n, r, w, e, timeout)
Definition: win32_port.h:445
ParallelSlot * parallelSlot
Definition: parallel.h:45
#define Assert(condition)
Definition: c.h:732
#define fatal(...)
T_WorkerStatus workerStatus
Definition: parallel.c:93
static bool do_wait
Definition: pg_ctl.c:79
int i
int numWorkers
Definition: parallel.h:42

◆ GetMyPSlot()

static ParallelSlot * GetMyPSlot ( ParallelState pstate)
static

Definition at line 279 of file parallel.c.

References createPQExpBuffer(), i, ParallelState::numWorkers, ParallelState::parallelSlot, ParallelSlot::pid, and resetPQExpBuffer().

Referenced by archive_close_connection().

280 {
281  int i;
282 
283  for (i = 0; i < pstate->numWorkers; i++)
284  {
285 #ifdef WIN32
286  if (pstate->parallelSlot[i].threadId == GetCurrentThreadId())
287 #else
288  if (pstate->parallelSlot[i].pid == getpid())
289 #endif
290  return &(pstate->parallelSlot[i]);
291  }
292 
293  return NULL;
294 }
pid_t pid
Definition: parallel.c:111
ParallelSlot * parallelSlot
Definition: parallel.h:45
int i
int numWorkers
Definition: parallel.h:42

◆ HasEveryWorkerTerminated()

static bool HasEveryWorkerTerminated ( ParallelState pstate)
static

Definition at line 1266 of file parallel.c.

References i, ParallelState::numWorkers, ParallelState::parallelSlot, ParallelSlot::workerStatus, and WRKR_TERMINATED.

Referenced by WaitForTerminatingWorkers().

1267 {
1268  int i;
1269 
1270  for (i = 0; i < pstate->numWorkers; i++)
1271  {
1272  if (pstate->parallelSlot[i].workerStatus != WRKR_TERMINATED)
1273  return false;
1274  }
1275  return true;
1276 }
ParallelSlot * parallelSlot
Definition: parallel.h:45
T_WorkerStatus workerStatus
Definition: parallel.c:93
int i
int numWorkers
Definition: parallel.h:42

◆ init_parallel_dump_utils()

void init_parallel_dump_utils ( void  )

Definition at line 247 of file parallel.c.

References exit_nicely, on_exit_nicely(), and pg_log_error.

Referenced by main().

248 {
249 #ifdef WIN32
250  if (!parallel_init_done)
251  {
252  WSADATA wsaData;
253  int err;
254 
255  /* Prepare for threaded operation */
256  tls_index = TlsAlloc();
257  mainThreadId = GetCurrentThreadId();
258 
259  /* Initialize socket access */
260  err = WSAStartup(MAKEWORD(2, 2), &wsaData);
261  if (err != 0)
262  {
263  pg_log_error("WSAStartup failed: %d", err);
264  exit_nicely(1);
265  }
266  /* ... and arrange to shut it down at exit */
267  on_exit_nicely(shutdown_parallel_dump_utils, NULL);
268  parallel_init_done = true;
269  }
270 #endif
271 }
void on_exit_nicely(on_exit_nicely_callback function, void *arg)
#define pg_log_error(...)
Definition: logging.h:79
#define exit_nicely(code)
Definition: pg_dumpall.c:96

◆ IsEveryWorkerIdle()

bool IsEveryWorkerIdle ( ParallelState pstate)

Definition at line 1282 of file parallel.c.

References i, ParallelState::numWorkers, ParallelState::parallelSlot, ParallelSlot::workerStatus, and WRKR_IDLE.

Referenced by ParallelBackupEnd(), restore_toc_entries_parallel(), and WaitForWorkers().

1283 {
1284  int i;
1285 
1286  for (i = 0; i < pstate->numWorkers; i++)
1287  {
1288  if (pstate->parallelSlot[i].workerStatus != WRKR_IDLE)
1289  return false;
1290  }
1291  return true;
1292 }
ParallelSlot * parallelSlot
Definition: parallel.h:45
T_WorkerStatus workerStatus
Definition: parallel.c:93
int i
int numWorkers
Definition: parallel.h:42

◆ ListenToWorkers()

static bool ListenToWorkers ( ArchiveHandle AH,
ParallelState pstate,
bool  do_wait 
)
static

Definition at line 1412 of file parallel.c.

References ParallelSlot::callback, ParallelSlot::callback_data, fatal, free, getMessageFromWorker(), messageStartsWith, ParallelState::parallelSlot, parseWorkerResponse(), status(), ParallelState::te, ParallelSlot::workerStatus, and WRKR_IDLE.

Referenced by WaitForWorkers().

1413 {
1414  int worker;
1415  char *msg;
1416 
1417  /* Try to collect a status message */
1418  msg = getMessageFromWorker(pstate, do_wait, &worker);
1419 
1420  if (!msg)
1421  {
1422  /* If do_wait is true, we must have detected EOF on some socket */
1423  if (do_wait)
1424  fatal("a worker process died unexpectedly");
1425  return false;
1426  }
1427 
1428  /* Process it and update our idea of the worker's status */
1429  if (messageStartsWith(msg, "OK "))
1430  {
1431  ParallelSlot *slot = &pstate->parallelSlot[worker];
1432  TocEntry *te = pstate->te[worker];
1433  int status;
1434 
1435  status = parseWorkerResponse(AH, te, msg);
1436  slot->callback(AH, te, status, slot->callback_data);
1437  slot->workerStatus = WRKR_IDLE;
1438  pstate->te[worker] = NULL;
1439  }
1440  else
1441  fatal("invalid message received from worker: \"%s\"",
1442  msg);
1443 
1444  /* Free the string returned from getMessageFromWorker */
1445  free(msg);
1446 
1447  return true;
1448 }
void * callback_data
Definition: parallel.c:97
static char * getMessageFromWorker(ParallelState *pstate, bool do_wait, int *worker)
Definition: parallel.c:1593
ParallelSlot * parallelSlot
Definition: parallel.h:45
#define free(a)
Definition: header.h:65
TocEntry ** te
Definition: parallel.h:44
ParallelCompletionPtr callback
Definition: parallel.c:96
#define fatal(...)
T_WorkerStatus workerStatus
Definition: parallel.c:93
static bool do_wait
Definition: pg_ctl.c:79
static int parseWorkerResponse(ArchiveHandle *AH, TocEntry *te, const char *msg)
Definition: parallel.c:1185
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
#define messageStartsWith(msg, prefix)
Definition: parallel.c:224

◆ lockTableForWorker()

static void lockTableForWorker ( ArchiveHandle AH,
TocEntry te 
)
static

Definition at line 1315 of file parallel.c.

References appendPQExpBuffer(), _archiveHandle::connection, createPQExpBuffer(), PQExpBufferData::data, _tocEntry::desc, destroyPQExpBuffer(), fatal, fmtQualifiedId(), PGRES_COMMAND_OK, PQclear(), PQexec(), PQresultStatus(), and _tocEntry::tag.

Referenced by WaitForCommands().

1316 {
1317  const char *qualId;
1318  PQExpBuffer query;
1319  PGresult *res;
1320 
1321  /* Nothing to do for BLOBS */
1322  if (strcmp(te->desc, "BLOBS") == 0)
1323  return;
1324 
1325  query = createPQExpBuffer();
1326 
1327  qualId = fmtQualifiedId(te->namespace, te->tag);
1328 
1329  appendPQExpBuffer(query, "LOCK TABLE %s IN ACCESS SHARE MODE NOWAIT",
1330  qualId);
1331 
1332  res = PQexec(AH->connection, query->data);
1333 
1334  if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
1335  fatal("could not obtain lock on relation \"%s\"\n"
1336  "This usually means that someone requested an ACCESS EXCLUSIVE lock "
1337  "on the table after the pg_dump parent process had gotten the "
1338  "initial ACCESS SHARE lock on the table.", qualId);
1339 
1340  PQclear(res);
1341  destroyPQExpBuffer(query);
1342 }
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2693
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:116
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:74
void PQclear(PGresult *res)
Definition: fe-exec.c:695
const char * fmtQualifiedId(const char *schema, const char *id)
Definition: string_utils.c:147
#define fatal(...)
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1940

◆ on_exit_close_archive()

void on_exit_close_archive ( Archive AHX)

Definition at line 343 of file parallel.c.

References ShutdownInformation::AHX, archive_close_connection(), and on_exit_nicely().

Referenced by main().

344 {
345  shutdown_info.AHX = AHX;
347 }
void on_exit_nicely(on_exit_nicely_callback function, void *arg)
static ShutdownInformation shutdown_info
Definition: parallel.c:150
static void archive_close_connection(int code, void *arg)
Definition: parallel.c:354

◆ ParallelBackupEnd()

void ParallelBackupEnd ( ArchiveHandle AH,
ParallelState pstate 
)

Definition at line 1073 of file parallel.c.

References Assert, closesocket, free, i, IsEveryWorkerIdle(), ParallelState::numWorkers, ParallelState::parallelSlot, ParallelSlot::pipeRead, ParallelSlot::pipeWrite, ShutdownInformation::pstate, set_cancel_pstate(), ParallelState::te, and WaitForTerminatingWorkers().

Referenced by _CloseArchive(), and RestoreArchive().

1074 {
1075  int i;
1076 
1077  /* No work if non-parallel */
1078  if (pstate->numWorkers == 1)
1079  return;
1080 
1081  /* There should not be any unfinished jobs */
1082  Assert(IsEveryWorkerIdle(pstate));
1083 
1084  /* Close the sockets so that the workers know they can exit */
1085  for (i = 0; i < pstate->numWorkers; i++)
1086  {
1087  closesocket(pstate->parallelSlot[i].pipeRead);
1088  closesocket(pstate->parallelSlot[i].pipeWrite);
1089  }
1090 
1091  /* Wait for them to exit */
1092  WaitForTerminatingWorkers(pstate);
1093 
1094  /*
1095  * Unlink pstate from shutdown_info, so the exit handler will not try to
1096  * use it; and likewise unlink from signal_info.
1097  */
1098  shutdown_info.pstate = NULL;
1099  set_cancel_pstate(NULL);
1100 
1101  /* Release state (mere neatnik-ism, since we're about to terminate) */
1102  free(pstate->te);
1103  free(pstate->parallelSlot);
1104  free(pstate);
1105 }
int pipeRead
Definition: parallel.c:101
static void set_cancel_pstate(ParallelState *pstate)
Definition: parallel.c:799
bool IsEveryWorkerIdle(ParallelState *pstate)
Definition: parallel.c:1282
#define closesocket
Definition: port.h:312
ParallelSlot * parallelSlot
Definition: parallel.h:45
ParallelState * pstate
Definition: parallel.c:146
#define free(a)
Definition: header.h:65
static ShutdownInformation shutdown_info
Definition: parallel.c:150
#define Assert(condition)
Definition: c.h:732
TocEntry ** te
Definition: parallel.h:44
int pipeWrite
Definition: parallel.c:102
int i
static void WaitForTerminatingWorkers(ParallelState *pstate)
Definition: parallel.c:459
int numWorkers
Definition: parallel.h:42

◆ ParallelBackupStart()

ParallelState* ParallelBackupStart ( ArchiveHandle AH)

Definition at line 907 of file parallel.c.

References ParallelSlot::AH, DumpSignalInformation::am_worker, Assert, ParallelSlot::callback, ParallelSlot::callback_data, closesocket, _archiveHandle::connection, fatal, getLocalPQExpBuffer, i, ParallelState::numWorkers, Archive::numWorkers, ParallelState::parallelSlot, pg_malloc(), pg_malloc0(), pgpipe, ParallelSlot::pid, PIPE_READ, PIPE_WRITE, ParallelSlot::pipeRead, ParallelSlot::pipeRevRead, ParallelSlot::pipeRevWrite, ParallelSlot::pipeWrite, pqsignal(), ShutdownInformation::pstate, _archiveHandle::public, RunWorker(), set_archive_cancel_info(), set_cancel_pstate(), SIG_IGN, SIGPIPE, ParallelState::te, ParallelSlot::workerStatus, and WRKR_IDLE.

Referenced by _CloseArchive(), and RestoreArchive().

908 {
909  ParallelState *pstate;
910  int i;
911 
912  Assert(AH->public.numWorkers > 0);
913 
914  pstate = (ParallelState *) pg_malloc(sizeof(ParallelState));
915 
916  pstate->numWorkers = AH->public.numWorkers;
917  pstate->te = NULL;
918  pstate->parallelSlot = NULL;
919 
920  if (AH->public.numWorkers == 1)
921  return pstate;
922 
923  pstate->te = (TocEntry **)
924  pg_malloc0(pstate->numWorkers * sizeof(TocEntry *));
925  pstate->parallelSlot = (ParallelSlot *)
926  pg_malloc0(pstate->numWorkers * sizeof(ParallelSlot));
927 
928 #ifdef WIN32
929  /* Make fmtId() and fmtQualifiedId() use thread-local storage */
930  getLocalPQExpBuffer = getThreadLocalPQExpBuffer;
931 #endif
932 
933  /*
934  * Set the pstate in shutdown_info, to tell the exit handler that it must
935  * clean up workers as well as the main database connection. But we don't
936  * set this in signal_info yet, because we don't want child processes to
937  * inherit non-NULL signal_info.pstate.
938  */
939  shutdown_info.pstate = pstate;
940 
941  /*
942  * Temporarily disable query cancellation on the master connection. This
943  * ensures that child processes won't inherit valid AH->connCancel
944  * settings and thus won't try to issue cancels against the master's
945  * connection. No harm is done if we fail while it's disabled, because
946  * the master connection is idle at this point anyway.
947  */
948  set_archive_cancel_info(AH, NULL);
949 
950  /* Ensure stdio state is quiesced before forking */
951  fflush(NULL);
952 
953  /* Create desired number of workers */
954  for (i = 0; i < pstate->numWorkers; i++)
955  {
956 #ifdef WIN32
957  WorkerInfo *wi;
958  uintptr_t handle;
959 #else
960  pid_t pid;
961 #endif
962  ParallelSlot *slot = &(pstate->parallelSlot[i]);
963  int pipeMW[2],
964  pipeWM[2];
965 
966  /* Create communication pipes for this worker */
967  if (pgpipe(pipeMW) < 0 || pgpipe(pipeWM) < 0)
968  fatal("could not create communication channels: %m");
969 
970  pstate->te[i] = NULL; /* just for safety */
971 
972  slot->workerStatus = WRKR_IDLE;
973  slot->AH = NULL;
974  slot->callback = NULL;
975  slot->callback_data = NULL;
976 
977  /* master's ends of the pipes */
978  slot->pipeRead = pipeWM[PIPE_READ];
979  slot->pipeWrite = pipeMW[PIPE_WRITE];
980  /* child's ends of the pipes */
981  slot->pipeRevRead = pipeMW[PIPE_READ];
982  slot->pipeRevWrite = pipeWM[PIPE_WRITE];
983 
984 #ifdef WIN32
985  /* Create transient structure to pass args to worker function */
986  wi = (WorkerInfo *) pg_malloc(sizeof(WorkerInfo));
987 
988  wi->AH = AH;
989  wi->slot = slot;
990 
991  handle = _beginthreadex(NULL, 0, (void *) &init_spawned_worker_win32,
992  wi, 0, &(slot->threadId));
993  slot->hThread = handle;
994 #else /* !WIN32 */
995  pid = fork();
996  if (pid == 0)
997  {
998  /* we are the worker */
999  int j;
1000 
1001  /* this is needed for GetMyPSlot() */
1002  slot->pid = getpid();
1003 
1004  /* instruct signal handler that we're in a worker now */
1005  signal_info.am_worker = true;
1006 
1007  /* close read end of Worker -> Master */
1008  closesocket(pipeWM[PIPE_READ]);
1009  /* close write end of Master -> Worker */
1010  closesocket(pipeMW[PIPE_WRITE]);
1011 
1012  /*
1013  * Close all inherited fds for communication of the master with
1014  * previously-forked workers.
1015  */
1016  for (j = 0; j < i; j++)
1017  {
1018  closesocket(pstate->parallelSlot[j].pipeRead);
1019  closesocket(pstate->parallelSlot[j].pipeWrite);
1020  }
1021 
1022  /* Run the worker ... */
1023  RunWorker(AH, slot);
1024 
1025  /* We can just exit(0) when done */
1026  exit(0);
1027  }
1028  else if (pid < 0)
1029  {
1030  /* fork failed */
1031  fatal("could not create worker process: %m");
1032  }
1033 
1034  /* In Master after successful fork */
1035  slot->pid = pid;
1036 
1037  /* close read end of Master -> Worker */
1038  closesocket(pipeMW[PIPE_READ]);
1039  /* close write end of Worker -> Master */
1040  closesocket(pipeWM[PIPE_WRITE]);
1041 #endif /* WIN32 */
1042  }
1043 
1044  /*
1045  * Having forked off the workers, disable SIGPIPE so that master isn't
1046  * killed if it tries to send a command to a dead worker. We don't want
1047  * the workers to inherit this setting, though.
1048  */
1049 #ifndef WIN32
1051 #endif
1052 
1053  /*
1054  * Re-establish query cancellation on the master connection.
1055  */
1057 
1058  /*
1059  * Tell the cancel signal handler to forward signals to worker processes,
1060  * too. (As with query cancel, we did not need this earlier because the
1061  * workers have not yet been given anything to do; if we die before this
1062  * point, any already-started workers will see EOF and quit promptly.)
1063  */
1064  set_cancel_pstate(pstate);
1065 
1066  return pstate;
1067 }
int pipeRead
Definition: parallel.c:101
static void set_cancel_pstate(ParallelState *pstate)
Definition: parallel.c:799
ArchiveHandle * AH
Definition: parallel.c:99
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
void * callback_data
Definition: parallel.c:97
#define closesocket
Definition: port.h:312
#define PIPE_READ
Definition: parallel.c:71
#define SIGPIPE
Definition: win32_port.h:168
void * pg_malloc0(size_t size)
Definition: fe_memutils.c:53
pid_t pid
Definition: parallel.c:111
static void RunWorker(ArchiveHandle *AH, ParallelSlot *slot)
Definition: parallel.c:839
int pipeRevRead
Definition: parallel.c:103
#define pgpipe(a)
Definition: parallel.c:135
#define SIG_IGN
Definition: win32_port.h:160
ParallelSlot * parallelSlot
Definition: parallel.h:45
ParallelState * pstate
Definition: parallel.c:146
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
static ShutdownInformation shutdown_info
Definition: parallel.c:150
#define Assert(condition)
Definition: c.h:732
TocEntry ** te
Definition: parallel.h:44
ParallelCompletionPtr callback
Definition: parallel.c:96
int pipeRevWrite
Definition: parallel.c:104
PQExpBuffer(* getLocalPQExpBuffer)(void)
Definition: string_utils.c:29
#define fatal(...)
int numWorkers
Definition: pg_backup.h:193
static volatile DumpSignalInformation signal_info
Definition: parallel.c:171
T_WorkerStatus workerStatus
Definition: parallel.c:93
void set_archive_cancel_info(ArchiveHandle *AH, PGconn *conn)
Definition: parallel.c:740
int pipeWrite
Definition: parallel.c:102
int i
#define PIPE_WRITE
Definition: parallel.c:72
int numWorkers
Definition: parallel.h:42

◆ parseWorkerCommand()

static void parseWorkerCommand ( ArchiveHandle AH,
TocEntry **  te,
T_Action act,
const char *  msg 
)
static

Definition at line 1137 of file parallel.c.

References ACT_DUMP, ACT_RESTORE, Assert, fatal, getTocEntryByDumpId(), and messageStartsWith.

Referenced by WaitForCommands().

1139 {
1140  DumpId dumpId;
1141  int nBytes;
1142 
1143  if (messageStartsWith(msg, "DUMP "))
1144  {
1145  *act = ACT_DUMP;
1146  sscanf(msg, "DUMP %d%n", &dumpId, &nBytes);
1147  Assert(nBytes == strlen(msg));
1148  *te = getTocEntryByDumpId(AH, dumpId);
1149  Assert(*te != NULL);
1150  }
1151  else if (messageStartsWith(msg, "RESTORE "))
1152  {
1153  *act = ACT_RESTORE;
1154  sscanf(msg, "RESTORE %d%n", &dumpId, &nBytes);
1155  Assert(nBytes == strlen(msg));
1156  *te = getTocEntryByDumpId(AH, dumpId);
1157  Assert(*te != NULL);
1158  }
1159  else
1160  fatal("unrecognized command received from master: \"%s\"",
1161  msg);
1162 }
int DumpId
Definition: pg_backup.h:234
TocEntry * getTocEntryByDumpId(ArchiveHandle *AH, DumpId id)
#define Assert(condition)
Definition: c.h:732
#define fatal(...)
#define messageStartsWith(msg, prefix)
Definition: parallel.c:224

◆ parseWorkerResponse()

static int parseWorkerResponse ( ArchiveHandle AH,
TocEntry te,
const char *  msg 
)
static

Definition at line 1185 of file parallel.c.

References Assert, _tocEntry::dumpId, fatal, messageStartsWith, Archive::n_errors, _archiveHandle::public, and status().

Referenced by ListenToWorkers().

1187 {
1188  DumpId dumpId;
1189  int nBytes,
1190  n_errors;
1191  int status = 0;
1192 
1193  if (messageStartsWith(msg, "OK "))
1194  {
1195  sscanf(msg, "OK %d %d %d%n", &dumpId, &status, &n_errors, &nBytes);
1196 
1197  Assert(dumpId == te->dumpId);
1198  Assert(nBytes == strlen(msg));
1199 
1200  AH->public.n_errors += n_errors;
1201  }
1202  else
1203  fatal("invalid message received from worker: \"%s\"",
1204  msg);
1205 
1206  return status;
1207 }
int DumpId
Definition: pg_backup.h:234
int n_errors
Definition: pg_backup.h:206
#define Assert(condition)
Definition: c.h:732
#define fatal(...)
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
#define messageStartsWith(msg, prefix)
Definition: parallel.c:224

◆ readMessageFromPipe()

static char * readMessageFromPipe ( int  fd)
static

Definition at line 1674 of file parallel.c.

References accept, Assert, bind, buf, closesocket, connect, listen, pg_free(), pg_hton16, pg_hton32, pg_log_error, pg_malloc(), pg_realloc(), PGINVALID_SOCKET, pgpipe, piperead, recv, and socket.

Referenced by getMessageFromMaster(), and getMessageFromWorker().

1675 {
1676  char *msg;
1677  int msgsize,
1678  bufsize;
1679  int ret;
1680 
1681  /*
1682  * In theory, if we let piperead() read multiple bytes, it might give us
1683  * back fragments of multiple messages. (That can't actually occur, since
1684  * neither master nor workers send more than one message without waiting
1685  * for a reply, but we don't wish to assume that here.) For simplicity,
1686  * read a byte at a time until we get the terminating '\0'. This method
1687  * is a bit inefficient, but since this is only used for relatively short
1688  * command and status strings, it shouldn't matter.
1689  */
1690  bufsize = 64; /* could be any number */
1691  msg = (char *) pg_malloc(bufsize);
1692  msgsize = 0;
1693  for (;;)
1694  {
1695  Assert(msgsize < bufsize);
1696  ret = piperead(fd, msg + msgsize, 1);
1697  if (ret <= 0)
1698  break; /* error or connection closure */
1699 
1700  Assert(ret == 1);
1701 
1702  if (msg[msgsize] == '\0')
1703  return msg; /* collected whole message */
1704 
1705  msgsize++;
1706  if (msgsize == bufsize) /* enlarge buffer if needed */
1707  {
1708  bufsize += 16; /* could be any number */
1709  msg = (char *) pg_realloc(msg, bufsize);
1710  }
1711  }
1712 
1713  /* Other end has closed the connection */
1714  pg_free(msg);
1715  return NULL;
1716 }
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
static int fd(const char *x, int i)
Definition: preproc-init.c:105
void * pg_realloc(void *ptr, size_t size)
Definition: fe_memutils.c:65
#define Assert(condition)
Definition: c.h:732
void pg_free(void *ptr)
Definition: fe_memutils.c:105
#define piperead(a, b, c)
Definition: parallel.c:136

◆ RunWorker()

static void RunWorker ( ArchiveHandle AH,
ParallelSlot slot 
)
static

Definition at line 839 of file parallel.c.

References ParallelSlot::AH, CloneArchive(), DeCloneArchive(), DisconnectDatabase(), free, PIPE_READ, PIPE_WRITE, ParallelSlot::pipeRevRead, ParallelSlot::pipeRevWrite, _archiveHandle::public, set_cancel_slot_archive(), _archiveHandle::SetupWorkerPtr, and WaitForCommands().

Referenced by ParallelBackupStart().

840 {
841  int pipefd[2];
842 
843  /* fetch child ends of pipes */
844  pipefd[PIPE_READ] = slot->pipeRevRead;
845  pipefd[PIPE_WRITE] = slot->pipeRevWrite;
846 
847  /*
848  * Clone the archive so that we have our own state to work with, and in
849  * particular our own database connection.
850  *
851  * We clone on Unix as well as Windows, even though technically we don't
852  * need to because fork() gives us a copy in our own address space
853  * already. But CloneArchive resets the state information and also clones
854  * the database connection which both seem kinda helpful.
855  */
856  AH = CloneArchive(AH);
857 
858  /* Remember cloned archive where signal handler can find it */
859  set_cancel_slot_archive(slot, AH);
860 
861  /*
862  * Call the setup worker function that's defined in the ArchiveHandle.
863  */
864  (AH->SetupWorkerPtr) ((Archive *) AH);
865 
866  /*
867  * Execute commands until done.
868  */
869  WaitForCommands(AH, pipefd);
870 
871  /*
872  * Disconnect from database and clean up.
873  */
874  set_cancel_slot_archive(slot, NULL);
875  DisconnectDatabase(&(AH->public));
876  DeCloneArchive(AH);
877 }
#define PIPE_READ
Definition: parallel.c:71
SetupWorkerPtrType SetupWorkerPtr
void DeCloneArchive(ArchiveHandle *AH)
int pipeRevRead
Definition: parallel.c:103
ArchiveHandle * CloneArchive(ArchiveHandle *AH)
void DisconnectDatabase(Archive *AHX)
Definition: pg_backup_db.c:339
int pipeRevWrite
Definition: parallel.c:104
static void set_cancel_slot_archive(ParallelSlot *slot, ArchiveHandle *AH)
Definition: parallel.c:819
#define PIPE_WRITE
Definition: parallel.c:72
static void WaitForCommands(ArchiveHandle *AH, int pipefd[2])
Definition: parallel.c:1350

◆ select_loop()

static int select_loop ( int  maxFd,
fd_set *  workerset 
)
static

Definition at line 1554 of file parallel.c.

References EINTR, i, and select.

Referenced by getMessageFromWorker().

1555 {
1556  int i;
1557  fd_set saveSet = *workerset;
1558 
1559  for (;;)
1560  {
1561  *workerset = saveSet;
1562  i = select(maxFd + 1, workerset, NULL, NULL, NULL);
1563 
1564 #ifndef WIN32
1565  if (i < 0 && errno == EINTR)
1566  continue;
1567 #else
1568  if (i == SOCKET_ERROR && WSAGetLastError() == WSAEINTR)
1569  continue;
1570 #endif
1571  break;
1572  }
1573 
1574  return i;
1575 }
#define select(n, r, w, e, timeout)
Definition: win32_port.h:445
int i
#define EINTR
Definition: win32_port.h:332

◆ sendMessageToMaster()

static void sendMessageToMaster ( int  pipefd[2],
const char *  str 
)
static

Definition at line 1541 of file parallel.c.

References fatal, PIPE_WRITE, and pipewrite.

Referenced by WaitForCommands().

1542 {
1543  int len = strlen(str) + 1;
1544 
1545  if (pipewrite(pipefd[PIPE_WRITE], str, len) != len)
1546  fatal("could not write to the communication channel: %m");
1547 }
#define fatal(...)
#define pipewrite(a, b, c)
Definition: parallel.c:137
#define PIPE_WRITE
Definition: parallel.c:72

◆ sendMessageToWorker()

static void sendMessageToWorker ( ParallelState pstate,
int  worker,
const char *  str 
)
static

Definition at line 1656 of file parallel.c.

References fatal, ParallelState::parallelSlot, ParallelSlot::pipeWrite, and pipewrite.

Referenced by DispatchJobForTocEntry().

1657 {
1658  int len = strlen(str) + 1;
1659 
1660  if (pipewrite(pstate->parallelSlot[worker].pipeWrite, str, len) != len)
1661  {
1662  fatal("could not write to the communication channel: %m");
1663  }
1664 }
ParallelSlot * parallelSlot
Definition: parallel.h:45
#define fatal(...)
int pipeWrite
Definition: parallel.c:102
#define pipewrite(a, b, c)
Definition: parallel.c:137

◆ set_archive_cancel_info()

void set_archive_cancel_info ( ArchiveHandle AH,
PGconn conn 
)

Definition at line 740 of file parallel.c.

References ParallelSlot::AH, _archiveHandle::connCancel, DumpSignalInformation::myAH, PQfreeCancel(), PQgetCancel(), and setup_cancel_handler().

Referenced by ConnectDatabase(), DisconnectDatabase(), ParallelBackupStart(), and ReconnectToServer().

741 {
742  PGcancel *oldConnCancel;
743 
744  /*
745  * Activate the interrupt handler if we didn't yet in this process. On
746  * Windows, this also initializes signal_info_lock; therefore it's
747  * important that this happen at least once before we fork off any
748  * threads.
749  */
751 
752  /*
753  * On Unix, we assume that storing a pointer value is atomic with respect
754  * to any possible signal interrupt. On Windows, use a critical section.
755  */
756 
757 #ifdef WIN32
758  EnterCriticalSection(&signal_info_lock);
759 #endif
760 
761  /* Free the old one if we have one */
762  oldConnCancel = AH->connCancel;
763  /* be sure interrupt handler doesn't use pointer while freeing */
764  AH->connCancel = NULL;
765 
766  if (oldConnCancel != NULL)
767  PQfreeCancel(oldConnCancel);
768 
769  /* Set the new one if specified */
770  if (conn)
771  AH->connCancel = PQgetCancel(conn);
772 
773  /*
774  * On Unix, there's only ever one active ArchiveHandle per process, so we
775  * can just set signal_info.myAH unconditionally. On Windows, do that
776  * only in the main thread; worker threads have to make sure their
777  * ArchiveHandle appears in the pstate data, which is dealt with in
778  * RunWorker().
779  */
780 #ifndef WIN32
781  signal_info.myAH = AH;
782 #else
783  if (mainThreadId == GetCurrentThreadId())
784  signal_info.myAH = AH;
785 #endif
786 
787 #ifdef WIN32
788  LeaveCriticalSection(&signal_info_lock);
789 #endif
790 }
void PQfreeCancel(PGcancel *cancel)
Definition: fe-connect.c:4224
ArchiveHandle * myAH
Definition: parallel.c:163
static void setup_cancel_handler(void)
Definition: parallel.c:618
PGcancel *volatile connCancel
PGcancel * PQgetCancel(PGconn *conn)
Definition: fe-connect.c:4201
static volatile DumpSignalInformation signal_info
Definition: parallel.c:171

◆ set_cancel_pstate()

static void set_cancel_pstate ( ParallelState pstate)
static

Definition at line 799 of file parallel.c.

References DumpSignalInformation::pstate.

Referenced by ParallelBackupEnd(), and ParallelBackupStart().

800 {
801 #ifdef WIN32
802  EnterCriticalSection(&signal_info_lock);
803 #endif
804 
805  signal_info.pstate = pstate;
806 
807 #ifdef WIN32
808  LeaveCriticalSection(&signal_info_lock);
809 #endif
810 }
ParallelState * pstate
Definition: parallel.c:164
static volatile DumpSignalInformation signal_info
Definition: parallel.c:171

◆ set_cancel_slot_archive()

static void set_cancel_slot_archive ( ParallelSlot slot,
ArchiveHandle AH 
)
static

Definition at line 819 of file parallel.c.

References ParallelSlot::AH.

Referenced by RunWorker().

820 {
821 #ifdef WIN32
822  EnterCriticalSection(&signal_info_lock);
823 #endif
824 
825  slot->AH = AH;
826 
827 #ifdef WIN32
828  LeaveCriticalSection(&signal_info_lock);
829 #endif
830 }
ArchiveHandle * AH
Definition: parallel.c:99

◆ setup_cancel_handler()

static void setup_cancel_handler ( void  )
static

Definition at line 618 of file parallel.c.

References ParallelSlot::AH, _archiveHandle::connCancel, FALSE, DumpSignalInformation::handler_set, i, DumpSignalInformation::myAH, ParallelState::numWorkers, ParallelState::parallelSlot, PQcancel(), pqsignal(), progname, DumpSignalInformation::pstate, SIGQUIT, sigTermHandler(), TRUE, and write_stderr.

Referenced by main(), and set_archive_cancel_info().

619 {
620  /*
621  * When forking, signal_info.handler_set will propagate into the new
622  * process, but that's fine because the signal handler state does too.
623  */
625  {
626  signal_info.handler_set = true;
627 
628  pqsignal(SIGINT, sigTermHandler);
629  pqsignal(SIGTERM, sigTermHandler);
631  }
632 }
#define SIGQUIT
Definition: win32_port.h:164
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
static volatile DumpSignalInformation signal_info
Definition: parallel.c:171
static void sigTermHandler(SIGNAL_ARGS)
Definition: parallel.c:558

◆ ShutdownWorkersHard()

static void ShutdownWorkersHard ( ParallelState pstate)
static

Definition at line 410 of file parallel.c.

References ParallelSlot::AH, closesocket, _archiveHandle::connCancel, i, kill, ParallelState::numWorkers, ParallelState::parallelSlot, ParallelSlot::pid, ParallelSlot::pipeWrite, PQcancel(), and WaitForTerminatingWorkers().

Referenced by archive_close_connection().

411 {
412  int i;
413 
414  /*
415  * Close our write end of the sockets so that any workers waiting for
416  * commands know they can exit.
417  */
418  for (i = 0; i < pstate->numWorkers; i++)
419  closesocket(pstate->parallelSlot[i].pipeWrite);
420 
421  /*
422  * Force early termination of any commands currently in progress.
423  */
424 #ifndef WIN32
425  /* On non-Windows, send SIGTERM to each worker process. */
426  for (i = 0; i < pstate->numWorkers; i++)
427  {
428  pid_t pid = pstate->parallelSlot[i].pid;
429 
430  if (pid != 0)
431  kill(pid, SIGTERM);
432  }
433 #else
434 
435  /*
436  * On Windows, send query cancels directly to the workers' backends. Use
437  * a critical section to ensure worker threads don't change state.
438  */
439  EnterCriticalSection(&signal_info_lock);
440  for (i = 0; i < pstate->numWorkers; i++)
441  {
442  ArchiveHandle *AH = pstate->parallelSlot[i].AH;
443  char errbuf[1];
444 
445  if (AH != NULL && AH->connCancel != NULL)
446  (void) PQcancel(AH->connCancel, errbuf, sizeof(errbuf));
447  }
448  LeaveCriticalSection(&signal_info_lock);
449 #endif
450 
451  /* Now wait for them to terminate. */
453 }
ArchiveHandle * AH
Definition: parallel.c:99
#define closesocket
Definition: port.h:312
#define kill(pid, sig)
Definition: win32_port.h:435
PGcancel *volatile connCancel
pid_t pid
Definition: parallel.c:111
ParallelSlot * parallelSlot
Definition: parallel.h:45
int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
Definition: fe-connect.c:4356
int pipeWrite
Definition: parallel.c:102
int i
static void WaitForTerminatingWorkers(ParallelState *pstate)
Definition: parallel.c:459
int numWorkers
Definition: parallel.h:42

◆ sigTermHandler()

static void sigTermHandler ( SIGNAL_ARGS  )
static

Definition at line 558 of file parallel.c.

References DumpSignalInformation::am_worker, _archiveHandle::connCancel, i, kill, DumpSignalInformation::myAH, ParallelState::numWorkers, ParallelState::parallelSlot, ParallelSlot::pid, PQcancel(), pqsignal(), progname, DumpSignalInformation::pstate, SIG_IGN, SIGQUIT, and write_stderr.

Referenced by setup_cancel_handler().

559 {
560  int i;
561  char errbuf[1];
562 
563  /*
564  * Some platforms allow delivery of new signals to interrupt an active
565  * signal handler. That could muck up our attempt to send PQcancel, so
566  * disable the signals that setup_cancel_handler enabled.
567  */
568  pqsignal(SIGINT, SIG_IGN);
569  pqsignal(SIGTERM, SIG_IGN);
571 
572  /*
573  * If we're in the master, forward signal to all workers. (It seems best
574  * to do this before PQcancel; killing the master transaction will result
575  * in invalid-snapshot errors from active workers, which maybe we can
576  * quiet by killing workers first.) Ignore any errors.
577  */
578  if (signal_info.pstate != NULL)
579  {
580  for (i = 0; i < signal_info.pstate->numWorkers; i++)
581  {
582  pid_t pid = signal_info.pstate->parallelSlot[i].pid;
583 
584  if (pid != 0)
585  kill(pid, SIGTERM);
586  }
587  }
588 
589  /*
590  * Send QueryCancel if we have a connection to send to. Ignore errors,
591  * there's not much we can do about them anyway.
592  */
593  if (signal_info.myAH != NULL && signal_info.myAH->connCancel != NULL)
594  (void) PQcancel(signal_info.myAH->connCancel, errbuf, sizeof(errbuf));
595 
596  /*
597  * Report we're quitting, using nothing more complicated than write(2).
598  * When in parallel operation, only the master process should do this.
599  */
600  if (!signal_info.am_worker)
601  {
602  if (progname)
603  {
605  write_stderr(": ");
606  }
607  write_stderr("terminated by user\n");
608  }
609 
610  /* And die. */
611  exit(1);
612 }
#define SIGQUIT
Definition: win32_port.h:164
ArchiveHandle * myAH
Definition: parallel.c:163
#define write_stderr(str)
Definition: parallel.c:182
#define kill(pid, sig)
Definition: win32_port.h:435
PGcancel *volatile connCancel
const char * progname
Definition: pg_standby.c:37
ParallelState * pstate
Definition: parallel.c:164
pid_t pid
Definition: parallel.c:111
#define SIG_IGN
Definition: win32_port.h:160
ParallelSlot * parallelSlot
Definition: parallel.h:45
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
static volatile DumpSignalInformation signal_info
Definition: parallel.c:171
int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
Definition: fe-connect.c:4356
int i
int numWorkers
Definition: parallel.h:42

◆ WaitForCommands()

static void WaitForCommands ( ArchiveHandle AH,
int  pipefd[2] 
)
static

Definition at line 1350 of file parallel.c.

References ACT_DUMP, ACT_RESTORE, Assert, buf, buildWorkerResponse(), free, getMessageFromMaster(), lockTableForWorker(), parseWorkerCommand(), sendMessageToMaster(), status(), _archiveHandle::WorkerJobDumpPtr, and _archiveHandle::WorkerJobRestorePtr.

Referenced by RunWorker().

1351 {
1352  char *command;
1353  TocEntry *te;
1354  T_Action act;
1355  int status = 0;
1356  char buf[256];
1357 
1358  for (;;)
1359  {
1360  if (!(command = getMessageFromMaster(pipefd)))
1361  {
1362  /* EOF, so done */
1363  return;
1364  }
1365 
1366  /* Decode the command */
1367  parseWorkerCommand(AH, &te, &act, command);
1368 
1369  if (act == ACT_DUMP)
1370  {
1371  /* Acquire lock on this table within the worker's session */
1372  lockTableForWorker(AH, te);
1373 
1374  /* Perform the dump command */
1375  status = (AH->WorkerJobDumpPtr) (AH, te);
1376  }
1377  else if (act == ACT_RESTORE)
1378  {
1379  /* Perform the restore command */
1380  status = (AH->WorkerJobRestorePtr) (AH, te);
1381  }
1382  else
1383  Assert(false);
1384 
1385  /* Return status to master */
1386  buildWorkerResponse(AH, te, act, status, buf, sizeof(buf));
1387 
1388  sendMessageToMaster(pipefd, buf);
1389 
1390  /* command was pg_malloc'd and we are responsible for free()ing it. */
1391  free(command);
1392  }
1393 }
static void buildWorkerResponse(ArchiveHandle *AH, TocEntry *te, T_Action act, int status, char *buf, int buflen)
Definition: parallel.c:1170
static char * getMessageFromMaster(int pipefd[2])
Definition: parallel.c:1530
static char * buf
Definition: pg_test_fsync.c:68
static void lockTableForWorker(ArchiveHandle *AH, TocEntry *te)
Definition: parallel.c:1315
#define free(a)
Definition: header.h:65
static void parseWorkerCommand(ArchiveHandle *AH, TocEntry **te, T_Action *act, const char *msg)
Definition: parallel.c:1137
#define Assert(condition)
Definition: c.h:732
WorkerJobRestorePtrType WorkerJobRestorePtr
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
WorkerJobDumpPtrType WorkerJobDumpPtr
static void sendMessageToMaster(int pipefd[2], const char *str)
Definition: parallel.c:1541

◆ WaitForTerminatingWorkers()

static void WaitForTerminatingWorkers ( ParallelState pstate)
static

Definition at line 459 of file parallel.c.

References Assert, free, HasEveryWorkerTerminated(), ParallelState::numWorkers, ParallelState::parallelSlot, pg_malloc(), ParallelSlot::pid, status(), ParallelState::te, ParallelSlot::workerStatus, and WRKR_TERMINATED.

Referenced by ParallelBackupEnd(), and ShutdownWorkersHard().

460 {
461  while (!HasEveryWorkerTerminated(pstate))
462  {
463  ParallelSlot *slot = NULL;
464  int j;
465 
466 #ifndef WIN32
467  /* On non-Windows, use wait() to wait for next worker to end */
468  int status;
469  pid_t pid = wait(&status);
470 
471  /* Find dead worker's slot, and clear the PID field */
472  for (j = 0; j < pstate->numWorkers; j++)
473  {
474  slot = &(pstate->parallelSlot[j]);
475  if (slot->pid == pid)
476  {
477  slot->pid = 0;
478  break;
479  }
480  }
481 #else /* WIN32 */
482  /* On Windows, we must use WaitForMultipleObjects() */
483  HANDLE *lpHandles = pg_malloc(sizeof(HANDLE) * pstate->numWorkers);
484  int nrun = 0;
485  DWORD ret;
486  uintptr_t hThread;
487 
488  for (j = 0; j < pstate->numWorkers; j++)
489  {
490  if (pstate->parallelSlot[j].workerStatus != WRKR_TERMINATED)
491  {
492  lpHandles[nrun] = (HANDLE) pstate->parallelSlot[j].hThread;
493  nrun++;
494  }
495  }
496  ret = WaitForMultipleObjects(nrun, lpHandles, false, INFINITE);
497  Assert(ret != WAIT_FAILED);
498  hThread = (uintptr_t) lpHandles[ret - WAIT_OBJECT_0];
499  free(lpHandles);
500 
501  /* Find dead worker's slot, and clear the hThread field */
502  for (j = 0; j < pstate->numWorkers; j++)
503  {
504  slot = &(pstate->parallelSlot[j]);
505  if (slot->hThread == hThread)
506  {
507  /* For cleanliness, close handles for dead threads */
508  CloseHandle((HANDLE) slot->hThread);
509  slot->hThread = (uintptr_t) INVALID_HANDLE_VALUE;
510  break;
511  }
512  }
513 #endif /* WIN32 */
514 
515  /* On all platforms, update workerStatus and te[] as well */
516  Assert(j < pstate->numWorkers);
518  pstate->te[j] = NULL;
519  }
520 }
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
static bool HasEveryWorkerTerminated(ParallelState *pstate)
Definition: parallel.c:1266
pid_t pid
Definition: parallel.c:111
ParallelSlot * parallelSlot
Definition: parallel.h:45
#define free(a)
Definition: header.h:65
#define Assert(condition)
Definition: c.h:732
TocEntry ** te
Definition: parallel.h:44
T_WorkerStatus workerStatus
Definition: parallel.c:93
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
int numWorkers
Definition: parallel.h:42

◆ WaitForWorkers()

void WaitForWorkers ( ArchiveHandle AH,
ParallelState pstate,
WFW_WaitOption  mode 
)

Definition at line 1465 of file parallel.c.

References Assert, do_wait, GetIdleWorker(), IsEveryWorkerIdle(), ListenToWorkers(), NO_SLOT, WFW_ALL_IDLE, WFW_GOT_STATUS, WFW_NO_WAIT, and WFW_ONE_IDLE.

Referenced by DispatchJobForTocEntry(), restore_toc_entries_parallel(), and WriteDataChunks().

1466 {
1467  bool do_wait = false;
1468 
1469  /*
1470  * In GOT_STATUS mode, always block waiting for a message, since we can't
1471  * return till we get something. In other modes, we don't block the first
1472  * time through the loop.
1473  */
1474  if (mode == WFW_GOT_STATUS)
1475  {
1476  /* Assert that caller knows what it's doing */
1477  Assert(!IsEveryWorkerIdle(pstate));
1478  do_wait = true;
1479  }
1480 
1481  for (;;)
1482  {
1483  /*
1484  * Check for status messages, even if we don't need to block. We do
1485  * not try very hard to reap all available messages, though, since
1486  * there's unlikely to be more than one.
1487  */
1488  if (ListenToWorkers(AH, pstate, do_wait))
1489  {
1490  /*
1491  * If we got a message, we are done by definition for GOT_STATUS
1492  * mode, and we can also be certain that there's at least one idle
1493  * worker. So we're done in all but ALL_IDLE mode.
1494  */
1495  if (mode != WFW_ALL_IDLE)
1496  return;
1497  }
1498 
1499  /* Check whether we must wait for new status messages */
1500  switch (mode)
1501  {
1502  case WFW_NO_WAIT:
1503  return; /* never wait */
1504  case WFW_GOT_STATUS:
1505  Assert(false); /* can't get here, because we waited */
1506  break;
1507  case WFW_ONE_IDLE:
1508  if (GetIdleWorker(pstate) != NO_SLOT)
1509  return;
1510  break;
1511  case WFW_ALL_IDLE:
1512  if (IsEveryWorkerIdle(pstate))
1513  return;
1514  break;
1515  }
1516 
1517  /* Loop back, and this time wait for something to happen */
1518  do_wait = true;
1519  }
1520 }
static PgChecksumMode mode
Definition: pg_checksums.c:61
bool IsEveryWorkerIdle(ParallelState *pstate)
Definition: parallel.c:1282
static int GetIdleWorker(ParallelState *pstate)
Definition: parallel.c:1250
#define NO_SLOT
Definition: parallel.c:74
static bool ListenToWorkers(ArchiveHandle *AH, ParallelState *pstate, bool do_wait)
Definition: parallel.c:1412
#define Assert(condition)
Definition: c.h:732
static bool do_wait
Definition: pg_ctl.c:79

Variable Documentation

◆ shutdown_info

ShutdownInformation shutdown_info
static

Definition at line 150 of file parallel.c.

◆ signal_info

volatile DumpSignalInformation signal_info
static

Definition at line 171 of file parallel.c.