PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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 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)
 
#define messageEquals(msg, pattern)   (strcmp(msg, pattern) == 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
 
static const char * modulename = gettext_noop("parallel archiver")
 

Macro Definition Documentation

#define messageEquals (   msg,
  pattern 
)    (strcmp(msg, pattern) == 0)

Definition at line 226 of file parallel.c.

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

Definition at line 224 of file parallel.c.

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

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

Definition at line 72 of file parallel.c.

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

#define pgpipe (   a)    pipe(a)

Definition at line 133 of file parallel.c.

Referenced by ParallelBackupStart().

#define PIPE_READ   0

Definition at line 69 of file parallel.c.

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

#define PIPE_WRITE   1

Definition at line 70 of file parallel.c.

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

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

Definition at line 134 of file parallel.c.

Referenced by readMessageFromPipe().

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

Definition at line 135 of file parallel.c.

Referenced by sendMessageToMaster(), and sendMessageToWorker().

#define write_stderr (   str)
Value:
do { \
const char *str_ = (str); \
int rc_; \
rc_ = write(fileno(stderr), str_, strlen(str_)); \
(void) rc_; \
} while (0)
#define write(a, b, c)
Definition: win32.h:14

Definition at line 180 of file parallel.c.

Referenced by AuxiliaryProcessMain(), check_root(), checkDataDir(), crashDumpHandler(), ExceptionalCondition(), pg_attribute_printf(), pg_signal_thread(), PostmasterMain(), printMixedStruct(), save_ps_display_args(), SelectConfigFiles(), sigTermHandler(), startup_hacks(), and write_syslogger_file().

Typedef Documentation

Enumeration Type Documentation

Enumerator
WRKR_IDLE 
WRKR_WORKING 
WRKR_TERMINATED 

Definition at line 75 of file parallel.c.

Function Documentation

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

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

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

Definition at line 1128 of file parallel.c.

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

Referenced by DispatchJobForTocEntry().

1130 {
1131  if (act == ACT_DUMP)
1132  snprintf(buf, buflen, "DUMP %d", te->dumpId);
1133  else if (act == ACT_RESTORE)
1134  snprintf(buf, buflen, "RESTORE %d", te->dumpId);
1135  else
1136  Assert(false);
1137 }
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
static char * buf
Definition: pg_test_fsync.c:66
#define Assert(condition)
Definition: c.h:675
static void buildWorkerResponse ( ArchiveHandle AH,
TocEntry te,
T_Action  act,
int  status,
char *  buf,
int  buflen 
)
static

Definition at line 1177 of file parallel.c.

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

Referenced by WaitForCommands().

1179 {
1180  snprintf(buf, buflen, "OK %d %d %d",
1181  te->dumpId,
1182  status,
1184 }
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
int n_errors
Definition: pg_backup.h:198
#define WORKER_IGNORED_ERRORS
static char * buf
Definition: pg_test_fsync.c:66
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:224
void DispatchJobForTocEntry ( ArchiveHandle AH,
ParallelState pstate,
TocEntry te,
T_Action  act,
ParallelCompletionPtr  callback,
void *  callback_data 
)

Definition at line 1227 of file parallel.c.

References buf, buildWorkerCommand(), callback(), 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().

1233 {
1234  int worker;
1235  char buf[256];
1236 
1237  /* Get a worker, waiting if none are idle */
1238  while ((worker = GetIdleWorker(pstate)) == NO_SLOT)
1239  WaitForWorkers(AH, pstate, WFW_ONE_IDLE);
1240 
1241  /* Construct and send command string */
1242  buildWorkerCommand(AH, te, act, buf, sizeof(buf));
1243 
1244  sendMessageToWorker(pstate, worker, buf);
1245 
1246  /* Remember worker is busy, and which TocEntry it's working on */
1247  pstate->parallelSlot[worker].workerStatus = WRKR_WORKING;
1248  pstate->parallelSlot[worker].callback = callback;
1249  pstate->parallelSlot[worker].callback_data = callback_data;
1250  pstate->te[worker] = te;
1251 }
static void buildWorkerCommand(ArchiveHandle *AH, TocEntry *te, T_Action act, char *buf, int buflen)
Definition: parallel.c:1128
void * callback_data
Definition: parallel.c:95
static int GetIdleWorker(ParallelState *pstate)
Definition: parallel.c:1258
#define NO_SLOT
Definition: parallel.c:72
static void callback(struct sockaddr *addr, struct sockaddr *mask, void *unused)
Definition: test_ifaddrs.c:48
static char * buf
Definition: pg_test_fsync.c:66
ParallelSlot * parallelSlot
Definition: parallel.h:45
static void sendMessageToWorker(ParallelState *pstate, int worker, const char *str)
Definition: parallel.c:1668
void WaitForWorkers(ArchiveHandle *AH, ParallelState *pstate, WFW_WaitOption mode)
Definition: parallel.c:1475
TocEntry ** te
Definition: parallel.h:44
ParallelCompletionPtr callback
Definition: parallel.c:94
T_WorkerStatus workerStatus
Definition: parallel.c:91
static int GetIdleWorker ( ParallelState pstate)
static

Definition at line 1258 of file parallel.c.

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

Referenced by DispatchJobForTocEntry(), and WaitForWorkers().

1259 {
1260  int i;
1261 
1262  for (i = 0; i < pstate->numWorkers; i++)
1263  {
1264  if (pstate->parallelSlot[i].workerStatus == WRKR_IDLE)
1265  return i;
1266  }
1267  return NO_SLOT;
1268 }
#define NO_SLOT
Definition: parallel.c:72
ParallelSlot * parallelSlot
Definition: parallel.h:45
T_WorkerStatus workerStatus
Definition: parallel.c:91
int i
int numWorkers
Definition: parallel.h:42
static char * getMessageFromMaster ( int  pipefd[2])
static

Definition at line 1540 of file parallel.c.

References PIPE_READ, and readMessageFromPipe().

Referenced by WaitForCommands().

1541 {
1542  return readMessageFromPipe(pipefd[PIPE_READ]);
1543 }
#define PIPE_READ
Definition: parallel.c:69
static char * readMessageFromPipe(int fd)
Definition: parallel.c:1688
static char * getMessageFromWorker ( ParallelState pstate,
bool  do_wait,
int *  worker 
)
static

Definition at line 1605 of file parallel.c.

References Assert, exit_horribly(), i, modulename, NULL, ParallelState::numWorkers, ParallelState::parallelSlot, ParallelSlot::pipeRead, readMessageFromPipe(), select, select_loop(), strerror(), ParallelSlot::workerStatus, and WRKR_TERMINATED.

Referenced by ListenToWorkers().

1606 {
1607  int i;
1608  fd_set workerset;
1609  int maxFd = -1;
1610  struct timeval nowait = {0, 0};
1611 
1612  /* construct bitmap of socket descriptors for select() */
1613  FD_ZERO(&workerset);
1614  for (i = 0; i < pstate->numWorkers; i++)
1615  {
1616  if (pstate->parallelSlot[i].workerStatus == WRKR_TERMINATED)
1617  continue;
1618  FD_SET(pstate->parallelSlot[i].pipeRead, &workerset);
1619  if (pstate->parallelSlot[i].pipeRead > maxFd)
1620  maxFd = pstate->parallelSlot[i].pipeRead;
1621  }
1622 
1623  if (do_wait)
1624  {
1625  i = select_loop(maxFd, &workerset);
1626  Assert(i != 0);
1627  }
1628  else
1629  {
1630  if ((i = select(maxFd + 1, &workerset, NULL, NULL, &nowait)) == 0)
1631  return NULL;
1632  }
1633 
1634  if (i < 0)
1635  exit_horribly(modulename, "select() failed: %s\n", strerror(errno));
1636 
1637  for (i = 0; i < pstate->numWorkers; i++)
1638  {
1639  char *msg;
1640 
1641  if (!FD_ISSET(pstate->parallelSlot[i].pipeRead, &workerset))
1642  continue;
1643 
1644  /*
1645  * Read the message if any. If the socket is ready because of EOF,
1646  * we'll return NULL instead (and the socket will stay ready, so the
1647  * condition will persist).
1648  *
1649  * Note: because this is a blocking read, we'll wait if only part of
1650  * the message is available. Waiting a long time would be bad, but
1651  * since worker status messages are short and are always sent in one
1652  * operation, it shouldn't be a problem in practice.
1653  */
1654  msg = readMessageFromPipe(pstate->parallelSlot[i].pipeRead);
1655  *worker = i;
1656  return msg;
1657  }
1658  Assert(false);
1659  return NULL;
1660 }
int pipeRead
Definition: parallel.c:99
static int select_loop(int maxFd, fd_set *workerset)
Definition: parallel.c:1566
#define select(n, r, w, e, timeout)
Definition: win32.h:374
static const char * modulename
Definition: parallel.c:198
static char * readMessageFromPipe(int fd)
Definition: parallel.c:1688
ParallelSlot * parallelSlot
Definition: parallel.h:45
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
T_WorkerStatus workerStatus
Definition: parallel.c:91
void exit_horribly(const char *modulename, const char *fmt,...)
static bool do_wait
Definition: pg_ctl.c:71
int i
const char * strerror(int errnum)
Definition: strerror.c:19
int numWorkers
Definition: parallel.h:42
static ParallelSlot * GetMyPSlot ( ParallelState pstate)
static

Definition at line 281 of file parallel.c.

References i, NULL, ParallelState::numWorkers, ParallelState::parallelSlot, and ParallelSlot::pid.

Referenced by archive_close_connection().

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

Definition at line 1274 of file parallel.c.

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

Referenced by WaitForTerminatingWorkers().

1275 {
1276  int i;
1277 
1278  for (i = 0; i < pstate->numWorkers; i++)
1279  {
1280  if (pstate->parallelSlot[i].workerStatus != WRKR_TERMINATED)
1281  return false;
1282  }
1283  return true;
1284 }
ParallelSlot * parallelSlot
Definition: parallel.h:45
T_WorkerStatus workerStatus
Definition: parallel.c:91
int i
int numWorkers
Definition: parallel.h:42
void init_parallel_dump_utils ( void  )

Definition at line 249 of file parallel.c.

References _, exit_nicely, NULL, on_exit_nicely(), and progname.

Referenced by main().

250 {
251 #ifdef WIN32
252  if (!parallel_init_done)
253  {
254  WSADATA wsaData;
255  int err;
256 
257  /* Prepare for threaded operation */
258  tls_index = TlsAlloc();
259  mainThreadId = GetCurrentThreadId();
260 
261  /* Initialize socket access */
262  err = WSAStartup(MAKEWORD(2, 2), &wsaData);
263  if (err != 0)
264  {
265  fprintf(stderr, _("%s: WSAStartup failed: %d\n"), progname, err);
266  exit_nicely(1);
267  }
268  /* ... and arrange to shut it down at exit */
269  on_exit_nicely(shutdown_parallel_dump_utils, NULL);
270  parallel_init_done = true;
271  }
272 #endif
273 }
void on_exit_nicely(on_exit_nicely_callback function, void *arg)
const char * progname
Definition: pg_standby.c:37
#define exit_nicely(code)
Definition: pg_dumpall.c:89
#define NULL
Definition: c.h:229
#define _(x)
Definition: elog.c:84
bool IsEveryWorkerIdle ( ParallelState pstate)

Definition at line 1290 of file parallel.c.

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

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

1291 {
1292  int i;
1293 
1294  for (i = 0; i < pstate->numWorkers; i++)
1295  {
1296  if (pstate->parallelSlot[i].workerStatus != WRKR_IDLE)
1297  return false;
1298  }
1299  return true;
1300 }
ParallelSlot * parallelSlot
Definition: parallel.h:45
T_WorkerStatus workerStatus
Definition: parallel.c:91
int i
int numWorkers
Definition: parallel.h:42
static bool ListenToWorkers ( ArchiveHandle AH,
ParallelState pstate,
bool  do_wait 
)
static

Definition at line 1421 of file parallel.c.

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

Referenced by WaitForWorkers().

1422 {
1423  int worker;
1424  char *msg;
1425 
1426  /* Try to collect a status message */
1427  msg = getMessageFromWorker(pstate, do_wait, &worker);
1428 
1429  if (!msg)
1430  {
1431  /* If do_wait is true, we must have detected EOF on some socket */
1432  if (do_wait)
1433  exit_horribly(modulename, "a worker process died unexpectedly\n");
1434  return false;
1435  }
1436 
1437  /* Process it and update our idea of the worker's status */
1438  if (messageStartsWith(msg, "OK "))
1439  {
1440  ParallelSlot *slot = &pstate->parallelSlot[worker];
1441  TocEntry *te = pstate->te[worker];
1442  int status;
1443 
1444  status = parseWorkerResponse(AH, te, msg);
1445  slot->callback(AH, te, status, slot->callback_data);
1446  slot->workerStatus = WRKR_IDLE;
1447  pstate->te[worker] = NULL;
1448  }
1449  else
1451  "invalid message received from worker: \"%s\"\n",
1452  msg);
1453 
1454  /* Free the string returned from getMessageFromWorker */
1455  free(msg);
1456 
1457  return true;
1458 }
void * callback_data
Definition: parallel.c:95
static const char * modulename
Definition: parallel.c:198
static char * getMessageFromWorker(ParallelState *pstate, bool do_wait, int *worker)
Definition: parallel.c:1605
ParallelSlot * parallelSlot
Definition: parallel.h:45
#define free(a)
Definition: header.h:65
#define NULL
Definition: c.h:229
TocEntry ** te
Definition: parallel.h:44
ParallelCompletionPtr callback
Definition: parallel.c:94
T_WorkerStatus workerStatus
Definition: parallel.c:91
void exit_horribly(const char *modulename, const char *fmt,...)
static bool do_wait
Definition: pg_ctl.c:71
static int parseWorkerResponse(ArchiveHandle *AH, TocEntry *te, const char *msg)
Definition: parallel.c:1192
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:224
#define messageStartsWith(msg, prefix)
Definition: parallel.c:224
static void lockTableForWorker ( ArchiveHandle AH,
TocEntry te 
)
static

Definition at line 1323 of file parallel.c.

References appendPQExpBuffer(), _archiveHandle::connection, createPQExpBuffer(), PQExpBufferData::data, _tocEntry::desc, destroyPQExpBuffer(), exit_horribly(), fmtQualifiedId(), modulename, PGRES_COMMAND_OK, PQclear(), PQexec(), PQresultStatus(), _archiveHandle::public, Archive::remoteVersion, and _tocEntry::tag.

Referenced by WaitForCommands().

1324 {
1325  const char *qualId;
1326  PQExpBuffer query;
1327  PGresult *res;
1328 
1329  /* Nothing to do for BLOBS */
1330  if (strcmp(te->desc, "BLOBS") == 0)
1331  return;
1332 
1333  query = createPQExpBuffer();
1334 
1335  qualId = fmtQualifiedId(AH->public.remoteVersion, te->namespace, te->tag);
1336 
1337  appendPQExpBuffer(query, "LOCK TABLE %s IN ACCESS SHARE MODE NOWAIT",
1338  qualId);
1339 
1340  res = PQexec(AH->connection, query->data);
1341 
1342  if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
1344  "could not obtain lock on relation \"%s\"\n"
1345  "This usually means that someone requested an ACCESS EXCLUSIVE lock "
1346  "on the table after the pg_dump parent process had gotten the "
1347  "initial ACCESS SHARE lock on the table.\n", qualId);
1348 
1349  PQclear(res);
1350  destroyPQExpBuffer(query);
1351 }
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:113
static const char * modulename
Definition: parallel.c:198
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:262
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:71
void PQclear(PGresult *res)
Definition: fe-exec.c:650
void exit_horribly(const char *modulename, const char *fmt,...)
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1846
const char * fmtQualifiedId(int remoteVersion, const char *schema, const char *id)
Definition: string_utils.c:150
int remoteVersion
Definition: pg_backup.h:181
void on_exit_close_archive ( Archive AHX)

Definition at line 345 of file parallel.c.

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

Referenced by main().

346 {
347  shutdown_info.AHX = AHX;
349 }
void on_exit_nicely(on_exit_nicely_callback function, void *arg)
static ShutdownInformation shutdown_info
Definition: parallel.c:148
static void archive_close_connection(int code, void *arg)
Definition: parallel.c:356
void ParallelBackupEnd ( ArchiveHandle AH,
ParallelState pstate 
)

Definition at line 1079 of file parallel.c.

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

Referenced by _CloseArchive(), and RestoreArchive().

1080 {
1081  int i;
1082 
1083  /* No work if non-parallel */
1084  if (pstate->numWorkers == 1)
1085  return;
1086 
1087  /* There should not be any unfinished jobs */
1088  Assert(IsEveryWorkerIdle(pstate));
1089 
1090  /* Close the sockets so that the workers know they can exit */
1091  for (i = 0; i < pstate->numWorkers; i++)
1092  {
1093  closesocket(pstate->parallelSlot[i].pipeRead);
1094  closesocket(pstate->parallelSlot[i].pipeWrite);
1095  }
1096 
1097  /* Wait for them to exit */
1098  WaitForTerminatingWorkers(pstate);
1099 
1100  /*
1101  * Unlink pstate from shutdown_info, so the exit handler will not try to
1102  * use it; and likewise unlink from signal_info.
1103  */
1106 
1107  /* Release state (mere neatnik-ism, since we're about to terminate) */
1108  free(pstate->te);
1109  free(pstate->parallelSlot);
1110  free(pstate);
1111 }
int pipeRead
Definition: parallel.c:99
static void set_cancel_pstate(ParallelState *pstate)
Definition: parallel.c:801
bool IsEveryWorkerIdle(ParallelState *pstate)
Definition: parallel.c:1290
#define closesocket
Definition: port.h:328
ParallelSlot * parallelSlot
Definition: parallel.h:45
ParallelState * pstate
Definition: parallel.c:144
#define free(a)
Definition: header.h:65
static ShutdownInformation shutdown_info
Definition: parallel.c:148
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
TocEntry ** te
Definition: parallel.h:44
int pipeWrite
Definition: parallel.c:100
int i
static void WaitForTerminatingWorkers(ParallelState *pstate)
Definition: parallel.c:461
int numWorkers
Definition: parallel.h:42
ParallelState* ParallelBackupStart ( ArchiveHandle AH)

Definition at line 909 of file parallel.c.

References ParallelSlot::AH, DumpSignalInformation::am_worker, Assert, ParallelSlot::callback, ParallelSlot::callback_data, closesocket, _archiveHandle::connection, exit_horribly(), getLocalPQExpBuffer, i, modulename, NULL, 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, strerror(), ParallelState::te, ParallelSlot::workerStatus, and WRKR_IDLE.

Referenced by _CloseArchive(), and RestoreArchive().

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

Definition at line 1143 of file parallel.c.

References ACT_DUMP, ACT_RESTORE, Assert, exit_horribly(), getTocEntryByDumpId(), messageStartsWith, modulename, and NULL.

Referenced by WaitForCommands().

1145 {
1146  DumpId dumpId;
1147  int nBytes;
1148 
1149  if (messageStartsWith(msg, "DUMP "))
1150  {
1151  *act = ACT_DUMP;
1152  sscanf(msg, "DUMP %d%n", &dumpId, &nBytes);
1153  Assert(nBytes == strlen(msg));
1154  *te = getTocEntryByDumpId(AH, dumpId);
1155  Assert(*te != NULL);
1156  }
1157  else if (messageStartsWith(msg, "RESTORE "))
1158  {
1159  *act = ACT_RESTORE;
1160  sscanf(msg, "RESTORE %d%n", &dumpId, &nBytes);
1161  Assert(nBytes == strlen(msg));
1162  *te = getTocEntryByDumpId(AH, dumpId);
1163  Assert(*te != NULL);
1164  }
1165  else
1167  "unrecognized command received from master: \"%s\"\n",
1168  msg);
1169 }
int DumpId
Definition: pg_backup.h:226
static const char * modulename
Definition: parallel.c:198
TocEntry * getTocEntryByDumpId(ArchiveHandle *AH, DumpId id)
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
void exit_horribly(const char *modulename, const char *fmt,...)
#define messageStartsWith(msg, prefix)
Definition: parallel.c:224
static int parseWorkerResponse ( ArchiveHandle AH,
TocEntry te,
const char *  msg 
)
static

Definition at line 1192 of file parallel.c.

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

Referenced by ListenToWorkers().

1194 {
1195  DumpId dumpId;
1196  int nBytes,
1197  n_errors;
1198  int status = 0;
1199 
1200  if (messageStartsWith(msg, "OK "))
1201  {
1202  sscanf(msg, "OK %d %d %d%n", &dumpId, &status, &n_errors, &nBytes);
1203 
1204  Assert(dumpId == te->dumpId);
1205  Assert(nBytes == strlen(msg));
1206 
1207  AH->public.n_errors += n_errors;
1208  }
1209  else
1211  "invalid message received from worker: \"%s\"\n",
1212  msg);
1213 
1214  return status;
1215 }
int DumpId
Definition: pg_backup.h:226
int n_errors
Definition: pg_backup.h:198
static const char * modulename
Definition: parallel.c:198
#define Assert(condition)
Definition: c.h:675
void exit_horribly(const char *modulename, const char *fmt,...)
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:224
#define messageStartsWith(msg, prefix)
Definition: parallel.c:224
static char * readMessageFromPipe ( int  fd)
static

Definition at line 1688 of file parallel.c.

References Assert, NULL, pg_free(), pg_malloc(), pg_realloc(), and piperead.

Referenced by getMessageFromMaster(), and getMessageFromWorker().

1689 {
1690  char *msg;
1691  int msgsize,
1692  bufsize;
1693  int ret;
1694 
1695  /*
1696  * In theory, if we let piperead() read multiple bytes, it might give us
1697  * back fragments of multiple messages. (That can't actually occur, since
1698  * neither master nor workers send more than one message without waiting
1699  * for a reply, but we don't wish to assume that here.) For simplicity,
1700  * read a byte at a time until we get the terminating '\0'. This method
1701  * is a bit inefficient, but since this is only used for relatively short
1702  * command and status strings, it shouldn't matter.
1703  */
1704  bufsize = 64; /* could be any number */
1705  msg = (char *) pg_malloc(bufsize);
1706  msgsize = 0;
1707  for (;;)
1708  {
1709  Assert(msgsize < bufsize);
1710  ret = piperead(fd, msg + msgsize, 1);
1711  if (ret <= 0)
1712  break; /* error or connection closure */
1713 
1714  Assert(ret == 1);
1715 
1716  if (msg[msgsize] == '\0')
1717  return msg; /* collected whole message */
1718 
1719  msgsize++;
1720  if (msgsize == bufsize) /* enlarge buffer if needed */
1721  {
1722  bufsize += 16; /* could be any number */
1723  msg = (char *) pg_realloc(msg, bufsize);
1724  }
1725  }
1726 
1727  /* Other end has closed the connection */
1728  pg_free(msg);
1729  return NULL;
1730 }
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 NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
void pg_free(void *ptr)
Definition: fe_memutils.c:105
#define piperead(a, b, c)
Definition: parallel.c:134
static void RunWorker ( ArchiveHandle AH,
ParallelSlot slot 
)
static

Definition at line 841 of file parallel.c.

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

Referenced by ParallelBackupStart().

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

Definition at line 1566 of file parallel.c.

References EINTR, i, NULL, and select.

Referenced by getMessageFromWorker().

1567 {
1568  int i;
1569  fd_set saveSet = *workerset;
1570 
1571  for (;;)
1572  {
1573  *workerset = saveSet;
1574  i = select(maxFd + 1, workerset, NULL, NULL, NULL);
1575 
1576 #ifndef WIN32
1577  if (i < 0 && errno == EINTR)
1578  continue;
1579 #else
1580  if (i == SOCKET_ERROR && WSAGetLastError() == WSAEINTR)
1581  continue;
1582 #endif
1583  break;
1584  }
1585 
1586  return i;
1587 }
#define select(n, r, w, e, timeout)
Definition: win32.h:374
#define EINTR
Definition: win32.h:285
#define NULL
Definition: c.h:229
int i
static void sendMessageToMaster ( int  pipefd[2],
const char *  str 
)
static

Definition at line 1551 of file parallel.c.

References exit_horribly(), modulename, PIPE_WRITE, pipewrite, and strerror().

Referenced by WaitForCommands().

1552 {
1553  int len = strlen(str) + 1;
1554 
1555  if (pipewrite(pipefd[PIPE_WRITE], str, len) != len)
1557  "could not write to the communication channel: %s\n",
1558  strerror(errno));
1559 }
static const char * modulename
Definition: parallel.c:198
void exit_horribly(const char *modulename, const char *fmt,...)
const char * strerror(int errnum)
Definition: strerror.c:19
#define pipewrite(a, b, c)
Definition: parallel.c:135
#define PIPE_WRITE
Definition: parallel.c:70
static void sendMessageToWorker ( ParallelState pstate,
int  worker,
const char *  str 
)
static

Definition at line 1668 of file parallel.c.

References exit_horribly(), modulename, ParallelState::parallelSlot, ParallelSlot::pipeWrite, pipewrite, and strerror().

Referenced by DispatchJobForTocEntry().

1669 {
1670  int len = strlen(str) + 1;
1671 
1672  if (pipewrite(pstate->parallelSlot[worker].pipeWrite, str, len) != len)
1673  {
1675  "could not write to the communication channel: %s\n",
1676  strerror(errno));
1677  }
1678 }
static const char * modulename
Definition: parallel.c:198
ParallelSlot * parallelSlot
Definition: parallel.h:45
void exit_horribly(const char *modulename, const char *fmt,...)
int pipeWrite
Definition: parallel.c:100
const char * strerror(int errnum)
Definition: strerror.c:19
#define pipewrite(a, b, c)
Definition: parallel.c:135
void set_archive_cancel_info ( ArchiveHandle AH,
PGconn conn 
)

Definition at line 742 of file parallel.c.

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

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

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

Definition at line 801 of file parallel.c.

References DumpSignalInformation::pstate.

Referenced by ParallelBackupEnd(), and ParallelBackupStart().

802 {
803 #ifdef WIN32
804  EnterCriticalSection(&signal_info_lock);
805 #endif
806 
807  signal_info.pstate = pstate;
808 
809 #ifdef WIN32
810  LeaveCriticalSection(&signal_info_lock);
811 #endif
812 }
ParallelState * pstate
Definition: parallel.c:162
static volatile DumpSignalInformation signal_info
Definition: parallel.c:169
static void set_cancel_slot_archive ( ParallelSlot slot,
ArchiveHandle AH 
)
static

Definition at line 821 of file parallel.c.

References ParallelSlot::AH.

Referenced by RunWorker().

822 {
823 #ifdef WIN32
824  EnterCriticalSection(&signal_info_lock);
825 #endif
826 
827  slot->AH = AH;
828 
829 #ifdef WIN32
830  LeaveCriticalSection(&signal_info_lock);
831 #endif
832 }
ArchiveHandle * AH
Definition: parallel.c:97
static void setup_cancel_handler ( void  )
static

Definition at line 620 of file parallel.c.

References DumpSignalInformation::handler_set, pqsignal(), SIGQUIT, and sigTermHandler().

Referenced by main(), and set_archive_cancel_info().

621 {
622  /*
623  * When forking, signal_info.handler_set will propagate into the new
624  * process, but that's fine because the signal handler state does too.
625  */
627  {
628  signal_info.handler_set = true;
629 
630  pqsignal(SIGINT, sigTermHandler);
631  pqsignal(SIGTERM, sigTermHandler);
633  }
634 }
#define SIGQUIT
Definition: win32.h:189
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:168
static volatile DumpSignalInformation signal_info
Definition: parallel.c:169
static void sigTermHandler(SIGNAL_ARGS)
Definition: parallel.c:560
static void ShutdownWorkersHard ( ParallelState pstate)
static

Definition at line 412 of file parallel.c.

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

Referenced by archive_close_connection().

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

Definition at line 560 of file parallel.c.

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

Referenced by setup_cancel_handler().

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

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

1360 {
1361  char *command;
1362  TocEntry *te;
1363  T_Action act;
1364  int status = 0;
1365  char buf[256];
1366 
1367  for (;;)
1368  {
1369  if (!(command = getMessageFromMaster(pipefd)))
1370  {
1371  /* EOF, so done */
1372  return;
1373  }
1374 
1375  /* Decode the command */
1376  parseWorkerCommand(AH, &te, &act, command);
1377 
1378  if (act == ACT_DUMP)
1379  {
1380  /* Acquire lock on this table within the worker's session */
1381  lockTableForWorker(AH, te);
1382 
1383  /* Perform the dump command */
1384  status = (AH->WorkerJobDumpPtr) (AH, te);
1385  }
1386  else if (act == ACT_RESTORE)
1387  {
1388  /* Perform the restore command */
1389  status = (AH->WorkerJobRestorePtr) (AH, te);
1390  }
1391  else
1392  Assert(false);
1393 
1394  /* Return status to master */
1395  buildWorkerResponse(AH, te, act, status, buf, sizeof(buf));
1396 
1397  sendMessageToMaster(pipefd, buf);
1398 
1399  /* command was pg_malloc'd and we are responsible for free()ing it. */
1400  free(command);
1401  }
1402 }
static void buildWorkerResponse(ArchiveHandle *AH, TocEntry *te, T_Action act, int status, char *buf, int buflen)
Definition: parallel.c:1177
static char * getMessageFromMaster(int pipefd[2])
Definition: parallel.c:1540
static char * buf
Definition: pg_test_fsync.c:66
static void lockTableForWorker(ArchiveHandle *AH, TocEntry *te)
Definition: parallel.c:1323
#define free(a)
Definition: header.h:65
static void parseWorkerCommand(ArchiveHandle *AH, TocEntry **te, T_Action *act, const char *msg)
Definition: parallel.c:1143
#define Assert(condition)
Definition: c.h:675
WorkerJobRestorePtrType WorkerJobRestorePtr
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:224
WorkerJobDumpPtrType WorkerJobDumpPtr
static void sendMessageToMaster(int pipefd[2], const char *str)
Definition: parallel.c:1551
static void WaitForTerminatingWorkers ( ParallelState pstate)
static

Definition at line 461 of file parallel.c.

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

Referenced by ParallelBackupEnd(), and ShutdownWorkersHard().

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

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

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

Variable Documentation

ShutdownInformation shutdown_info
static

Definition at line 148 of file parallel.c.

volatile DumpSignalInformation signal_info
static

Definition at line 169 of file parallel.c.