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 "fe_utils/string_utils.h"
#include "parallel.h"
#include "pg_backup_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 223 of file parallel.c.

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

◆ NO_SLOT

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

Definition at line 73 of file parallel.c.

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

◆ pgpipe

#define pgpipe (   a)    pipe(a)

Definition at line 134 of file parallel.c.

Referenced by ParallelBackupStart(), and readMessageFromPipe().

◆ PIPE_READ

#define PIPE_READ   0

Definition at line 70 of file parallel.c.

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

◆ PIPE_WRITE

#define PIPE_WRITE   1

Definition at line 71 of file parallel.c.

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

◆ piperead

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

Definition at line 135 of file parallel.c.

Referenced by readMessageFromPipe().

◆ pipewrite

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

Definition at line 136 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 76 of file parallel.c.

Function Documentation

◆ archive_close_connection()

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

Definition at line 353 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().

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

◆ buildWorkerCommand()

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

Definition at line 1121 of file parallel.c.

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

Referenced by DispatchJobForTocEntry().

1123 {
1124  if (act == ACT_DUMP)
1125  snprintf(buf, buflen, "DUMP %d", te->dumpId);
1126  else if (act == ACT_RESTORE)
1127  snprintf(buf, buflen, "RESTORE %d", te->dumpId);
1128  else
1129  Assert(false);
1130 }
static char * buf
Definition: pg_test_fsync.c:67
#define Assert(condition)
Definition: c.h:739
#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 1169 of file parallel.c.

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

Referenced by WaitForCommands().

1171 {
1172  snprintf(buf, buflen, "OK %d %d %d",
1173  te->dumpId,
1174  status,
1176 }
int n_errors
Definition: pg_backup.h:206
#define WORKER_IGNORED_ERRORS
static char * buf
Definition: pg_test_fsync.c:67
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:226
#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 1218 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().

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

◆ GetIdleWorker()

static int GetIdleWorker ( ParallelState pstate)
static

Definition at line 1249 of file parallel.c.

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

Referenced by DispatchJobForTocEntry(), and WaitForWorkers().

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

◆ getMessageFromMaster()

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

Definition at line 1529 of file parallel.c.

References PIPE_READ, and readMessageFromPipe().

Referenced by WaitForCommands().

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

◆ getMessageFromWorker()

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

Definition at line 1592 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().

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

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

Referenced by archive_close_connection().

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

◆ HasEveryWorkerTerminated()

static bool HasEveryWorkerTerminated ( ParallelState pstate)
static

Definition at line 1265 of file parallel.c.

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

Referenced by WaitForTerminatingWorkers().

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

◆ init_parallel_dump_utils()

void init_parallel_dump_utils ( void  )

Definition at line 246 of file parallel.c.

References exit_nicely, on_exit_nicely(), and pg_log_error.

Referenced by main().

247 {
248 #ifdef WIN32
249  if (!parallel_init_done)
250  {
251  WSADATA wsaData;
252  int err;
253 
254  /* Prepare for threaded operation */
255  tls_index = TlsAlloc();
256  mainThreadId = GetCurrentThreadId();
257 
258  /* Initialize socket access */
259  err = WSAStartup(MAKEWORD(2, 2), &wsaData);
260  if (err != 0)
261  {
262  pg_log_error("WSAStartup failed: %d", err);
263  exit_nicely(1);
264  }
265  /* ... and arrange to shut it down at exit */
266  on_exit_nicely(shutdown_parallel_dump_utils, NULL);
267  parallel_init_done = true;
268  }
269 #endif
270 }
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:95

◆ IsEveryWorkerIdle()

bool IsEveryWorkerIdle ( ParallelState pstate)

Definition at line 1281 of file parallel.c.

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

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

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

◆ ListenToWorkers()

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

Definition at line 1411 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().

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

◆ lockTableForWorker()

static void lockTableForWorker ( ArchiveHandle AH,
TocEntry te 
)
static

Definition at line 1314 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().

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

◆ on_exit_close_archive()

void on_exit_close_archive ( Archive AHX)

Definition at line 342 of file parallel.c.

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

Referenced by main().

343 {
344  shutdown_info.AHX = AHX;
346 }
void on_exit_nicely(on_exit_nicely_callback function, void *arg)
static ShutdownInformation shutdown_info
Definition: parallel.c:149
static void archive_close_connection(int code, void *arg)
Definition: parallel.c:353

◆ ParallelBackupEnd()

void ParallelBackupEnd ( ArchiveHandle AH,
ParallelState pstate 
)

Definition at line 1072 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().

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

◆ ParallelBackupStart()

ParallelState* ParallelBackupStart ( ArchiveHandle AH)

Definition at line 906 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().

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

◆ parseWorkerCommand()

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

Definition at line 1136 of file parallel.c.

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

Referenced by WaitForCommands().

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

◆ parseWorkerResponse()

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

Definition at line 1184 of file parallel.c.

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

Referenced by ListenToWorkers().

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

◆ readMessageFromPipe()

static char * readMessageFromPipe ( int  fd)
static

Definition at line 1673 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().

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

◆ RunWorker()

static void RunWorker ( ArchiveHandle AH,
ParallelSlot slot 
)
static

Definition at line 838 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().

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

◆ select_loop()

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

Definition at line 1553 of file parallel.c.

References EINTR, i, and select.

Referenced by getMessageFromWorker().

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

◆ sendMessageToMaster()

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

Definition at line 1540 of file parallel.c.

References fatal, PIPE_WRITE, and pipewrite.

Referenced by WaitForCommands().

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

◆ sendMessageToWorker()

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

Definition at line 1655 of file parallel.c.

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

Referenced by DispatchJobForTocEntry().

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

◆ set_archive_cancel_info()

void set_archive_cancel_info ( ArchiveHandle AH,
PGconn conn 
)

Definition at line 739 of file parallel.c.

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

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

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

◆ set_cancel_pstate()

static void set_cancel_pstate ( ParallelState pstate)
static

Definition at line 798 of file parallel.c.

References DumpSignalInformation::pstate.

Referenced by ParallelBackupEnd(), and ParallelBackupStart().

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

◆ set_cancel_slot_archive()

static void set_cancel_slot_archive ( ParallelSlot slot,
ArchiveHandle AH 
)
static

Definition at line 818 of file parallel.c.

References ParallelSlot::AH.

Referenced by RunWorker().

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

◆ setup_cancel_handler()

static void setup_cancel_handler ( void  )
static

Definition at line 617 of file parallel.c.

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

Referenced by main(), psql_setup_cancel_handler(), runInitSteps(), and set_archive_cancel_info().

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

◆ ShutdownWorkersHard()

static void ShutdownWorkersHard ( ParallelState pstate)
static

Definition at line 409 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().

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

◆ sigTermHandler()

static void sigTermHandler ( SIGNAL_ARGS  )
static

Definition at line 557 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().

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

◆ WaitForCommands()

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

Definition at line 1349 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().

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

◆ WaitForTerminatingWorkers()

static void WaitForTerminatingWorkers ( ParallelState pstate)
static

Definition at line 458 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().

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

◆ WaitForWorkers()

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

Definition at line 1464 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().

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

Variable Documentation

◆ shutdown_info

ShutdownInformation shutdown_info
static

Definition at line 149 of file parallel.c.

◆ signal_info

volatile DumpSignalInformation signal_info
static

Definition at line 170 of file parallel.c.