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 "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)
 
#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 228 of file parallel.c.

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

Definition at line 226 of file parallel.c.

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

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

Definition at line 74 of file parallel.c.

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

#define pgpipe (   a)    pipe(a)

Definition at line 135 of file parallel.c.

Referenced by ParallelBackupStart().

#define PIPE_READ   0

Definition at line 71 of file parallel.c.

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

#define PIPE_WRITE   1

Definition at line 72 of file parallel.c.

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

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

Definition at line 136 of file parallel.c.

Referenced by readMessageFromPipe().

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

Definition at line 137 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 182 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 77 of file parallel.c.

Function Documentation

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

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

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

Definition at line 1130 of file parallel.c.

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

Referenced by DispatchJobForTocEntry().

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

Definition at line 1179 of file parallel.c.

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

Referenced by WaitForCommands().

1181 {
1182  snprintf(buf, buflen, "OK %d %d %d",
1183  te->dumpId,
1184  status,
1186 }
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
int n_errors
Definition: pg_backup.h:202
#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:225
void DispatchJobForTocEntry ( ArchiveHandle AH,
ParallelState pstate,
TocEntry te,
T_Action  act,
ParallelCompletionPtr  callback,
void *  callback_data 
)

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

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

Definition at line 1260 of file parallel.c.

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

Referenced by DispatchJobForTocEntry(), and WaitForWorkers().

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

Definition at line 1542 of file parallel.c.

References PIPE_READ, and readMessageFromPipe().

Referenced by WaitForCommands().

1543 {
1544  return readMessageFromPipe(pipefd[PIPE_READ]);
1545 }
#define PIPE_READ
Definition: parallel.c:71
static char * readMessageFromPipe(int fd)
Definition: parallel.c:1690
static char * getMessageFromWorker ( ParallelState pstate,
bool  do_wait,
int *  worker 
)
static

Definition at line 1607 of file parallel.c.

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

Referenced by ListenToWorkers().

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

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

Referenced by archive_close_connection().

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

Definition at line 1276 of file parallel.c.

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

Referenced by WaitForTerminatingWorkers().

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

Definition at line 251 of file parallel.c.

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

Referenced by main().

252 {
253 #ifdef WIN32
254  if (!parallel_init_done)
255  {
256  WSADATA wsaData;
257  int err;
258 
259  /* Prepare for threaded operation */
260  tls_index = TlsAlloc();
261  mainThreadId = GetCurrentThreadId();
262 
263  /* Initialize socket access */
264  err = WSAStartup(MAKEWORD(2, 2), &wsaData);
265  if (err != 0)
266  {
267  fprintf(stderr, _("%s: WSAStartup failed: %d\n"), progname, err);
268  exit_nicely(1);
269  }
270  /* ... and arrange to shut it down at exit */
271  on_exit_nicely(shutdown_parallel_dump_utils, NULL);
272  parallel_init_done = true;
273  }
274 #endif
275 }
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:92
#define _(x)
Definition: elog.c:84
bool IsEveryWorkerIdle ( ParallelState pstate)

Definition at line 1292 of file parallel.c.

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

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

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

Definition at line 1423 of file parallel.c.

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

Referenced by WaitForWorkers().

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

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

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

Definition at line 347 of file parallel.c.

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

Referenced by main().

348 {
349  shutdown_info.AHX = AHX;
351 }
void on_exit_nicely(on_exit_nicely_callback function, void *arg)
static ShutdownInformation shutdown_info
Definition: parallel.c:150
static void archive_close_connection(int code, void *arg)
Definition: parallel.c:358
void ParallelBackupEnd ( ArchiveHandle AH,
ParallelState pstate 
)

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

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

Definition at line 911 of file parallel.c.

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

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

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

Referenced by WaitForCommands().

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

Definition at line 1194 of file parallel.c.

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

Referenced by ListenToWorkers().

1196 {
1197  DumpId dumpId;
1198  int nBytes,
1199  n_errors;
1200  int status = 0;
1201 
1202  if (messageStartsWith(msg, "OK "))
1203  {
1204  sscanf(msg, "OK %d %d %d%n", &dumpId, &status, &n_errors, &nBytes);
1205 
1206  Assert(dumpId == te->dumpId);
1207  Assert(nBytes == strlen(msg));
1208 
1209  AH->public.n_errors += n_errors;
1210  }
1211  else
1213  "invalid message received from worker: \"%s\"\n",
1214  msg);
1215 
1216  return status;
1217 }
int DumpId
Definition: pg_backup.h:230
int n_errors
Definition: pg_backup.h:202
static const char * modulename
Definition: parallel.c:200
#define Assert(condition)
Definition: c.h:681
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:225
#define messageStartsWith(msg, prefix)
Definition: parallel.c:226
static char * readMessageFromPipe ( int  fd)
static

Definition at line 1690 of file parallel.c.

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

Referenced by getMessageFromMaster(), and getMessageFromWorker().

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

Definition at line 843 of file parallel.c.

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

Referenced by ParallelBackupStart().

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

Definition at line 1568 of file parallel.c.

References EINTR, i, and select.

Referenced by getMessageFromWorker().

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

Definition at line 1553 of file parallel.c.

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

Referenced by WaitForCommands().

1554 {
1555  int len = strlen(str) + 1;
1556 
1557  if (pipewrite(pipefd[PIPE_WRITE], str, len) != len)
1559  "could not write to the communication channel: %s\n",
1560  strerror(errno));
1561 }
static const char * modulename
Definition: parallel.c:200
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:137
#define PIPE_WRITE
Definition: parallel.c:72
static void sendMessageToWorker ( ParallelState pstate,
int  worker,
const char *  str 
)
static

Definition at line 1670 of file parallel.c.

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

Referenced by DispatchJobForTocEntry().

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

Definition at line 744 of file parallel.c.

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

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

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

Definition at line 803 of file parallel.c.

References DumpSignalInformation::pstate.

Referenced by ParallelBackupEnd(), and ParallelBackupStart().

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

Definition at line 823 of file parallel.c.

References ParallelSlot::AH.

Referenced by RunWorker().

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

Definition at line 622 of file parallel.c.

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

Referenced by main(), and set_archive_cancel_info().

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

Definition at line 414 of file parallel.c.

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

Referenced by archive_close_connection().

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

Definition at line 562 of file parallel.c.

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

Referenced by setup_cancel_handler().

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

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

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

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

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

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

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

Variable Documentation

ShutdownInformation shutdown_info
static

Definition at line 150 of file parallel.c.

volatile DumpSignalInformation signal_info
static

Definition at line 171 of file parallel.c.