1 /*-------------------------------------------------------------------------
4 * Infrastructure for launching parallel workers
6 * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * src/backend/access/transam/parallel.c
12 *-------------------------------------------------------------------------
17 #include "access/parallel.h"
18 #include "access/xact.h"
19 #include "access/xlog.h"
20 #include "catalog/namespace.h"
21 #include "commands/async.h"
22 #include "libpq/libpq.h"
23 #include "libpq/pqformat.h"
24 #include "libpq/pqmq.h"
25 #include "miscadmin.h"
26 #include "optimizer/planmain.h"
28 #include "storage/ipc.h"
29 #include "storage/sinval.h"
30 #include "storage/spin.h"
31 #include "tcop/tcopprot.h"
32 #include "utils/combocid.h"
33 #include "utils/guc.h"
34 #include "utils/inval.h"
35 #include "utils/memutils.h"
36 #include "utils/resowner.h"
37 #include "utils/snapmgr.h"
41 * We don't want to waste a lot of memory on an error queue which, most of
42 * the time, will process only a handful of small messages. However, it is
43 * desirable to make it large enough that a typical ErrorResponse can be sent
44 * without blocking. That way, a worker that errors out can write the whole
45 * message into the queue and terminate without waiting for the user backend.
47 #define PARALLEL_ERROR_QUEUE_SIZE 16384
49 /* Magic number for parallel context TOC. */
50 #define PARALLEL_MAGIC 0x50477c7c
53 * Magic numbers for parallel state sharing. Higher-level code should use
54 * smaller values, leaving these very large ones for use by this module.
56 #define PARALLEL_KEY_FIXED UINT64CONST(0xFFFFFFFFFFFF0001)
57 #define PARALLEL_KEY_ERROR_QUEUE UINT64CONST(0xFFFFFFFFFFFF0002)
58 #define PARALLEL_KEY_LIBRARY UINT64CONST(0xFFFFFFFFFFFF0003)
59 #define PARALLEL_KEY_GUC UINT64CONST(0xFFFFFFFFFFFF0004)
60 #define PARALLEL_KEY_COMBO_CID UINT64CONST(0xFFFFFFFFFFFF0005)
61 #define PARALLEL_KEY_TRANSACTION_SNAPSHOT UINT64CONST(0xFFFFFFFFFFFF0006)
62 #define PARALLEL_KEY_ACTIVE_SNAPSHOT UINT64CONST(0xFFFFFFFFFFFF0007)
63 #define PARALLEL_KEY_TRANSACTION_STATE UINT64CONST(0xFFFFFFFFFFFF0008)
64 #define PARALLEL_KEY_EXTENSION_TRAMPOLINE UINT64CONST(0xFFFFFFFFFFFF0009)
66 /* Fixed-size parallel state. */
67 typedef struct FixedParallelState
69 /* Fixed-size state that workers must restore. */
71 Oid authenticated_user_id;
73 Oid temp_namespace_id;
74 Oid temp_toast_namespace_id;
76 PGPROC *parallel_master_pgproc;
77 pid_t parallel_master_pid;
78 BackendId parallel_master_backend_id;
80 /* Entrypoint for parallel workers. */
81 parallel_worker_main_type entrypoint;
83 /* Mutex protects remaining fields. */
86 /* Maximum XactLastRecEnd of any worker. */
87 XLogRecPtr last_xlog_end;
91 * Our parallel worker number. We initialize this to -1, meaning that we are
92 * not a parallel worker. In parallel workers, it will be set to a value >= 0
93 * and < the number of workers before any user code is invoked; each parallel
94 * worker will get a different parallel worker number.
96 int ParallelWorkerNumber = -1;
98 /* Is there a parallel message pending which we need to receive? */
99 volatile bool ParallelMessagePending = false;
101 /* Are we initializing a parallel worker? */
102 bool InitializingParallelWorker = false;
104 /* Pointer to our fixed parallel state. */
105 static FixedParallelState *MyFixedParallelState;
107 /* List of active parallel contexts. */
108 static dlist_head pcxt_list = DLIST_STATIC_INIT(pcxt_list);
110 /* Private functions. */
111 static void HandleParallelMessage(ParallelContext *pcxt, int i, StringInfo msg);
112 static void ParallelExtensionTrampoline(dsm_segment *seg, shm_toc *toc);
113 static void WaitForParallelWorkersToExit(ParallelContext *pcxt);
117 * Establish a new parallel context. This should be done after entering
118 * parallel mode, and (unless there is an error) the context should be
119 * destroyed before exiting the current subtransaction.
122 CreateParallelContext(parallel_worker_main_type entrypoint, int nworkers)
124 MemoryContext oldcontext;
125 ParallelContext *pcxt;
127 /* It is unsafe to create a parallel context if not in parallel mode. */
128 Assert(IsInParallelMode());
130 /* Number of workers should be non-negative. */
131 Assert(nworkers >= 0);
134 * If dynamic shared memory is not available, we won't be able to use
135 * background workers.
137 if (dynamic_shared_memory_type == DSM_IMPL_NONE)
141 * If we are running under serializable isolation, we can't use parallel
142 * workers, at least not until somebody enhances that mechanism to be
145 if (IsolationIsSerializable())
148 /* We might be running in a short-lived memory context. */
149 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
151 /* Initialize a new ParallelContext. */
152 pcxt = palloc0(sizeof(ParallelContext));
153 pcxt->subid = GetCurrentSubTransactionId();
154 pcxt->nworkers = nworkers;
155 pcxt->entrypoint = entrypoint;
156 pcxt->error_context_stack = error_context_stack;
157 shm_toc_initialize_estimator(&pcxt->estimator);
158 dlist_push_head(&pcxt_list, &pcxt->node);
160 /* Restore previous memory context. */
161 MemoryContextSwitchTo(oldcontext);
167 * Establish a new parallel context that calls a function provided by an
168 * extension. This works around the fact that the library might get mapped
169 * at a different address in each backend.
172 CreateParallelContextForExternalFunction(char *library_name,
176 MemoryContext oldcontext;
177 ParallelContext *pcxt;
179 /* We might be running in a very short-lived memory context. */
180 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
182 /* Create the context. */
183 pcxt = CreateParallelContext(ParallelExtensionTrampoline, nworkers);
184 pcxt->library_name = pstrdup(library_name);
185 pcxt->function_name = pstrdup(function_name);
187 /* Restore previous memory context. */
188 MemoryContextSwitchTo(oldcontext);
194 * Establish the dynamic shared memory segment for a parallel context and
195 * copy state and other bookkeeping information that will be needed by
196 * parallel workers into it.
199 InitializeParallelDSM(ParallelContext *pcxt)
201 MemoryContext oldcontext;
202 Size library_len = 0;
204 Size combocidlen = 0;
210 FixedParallelState *fps;
211 Snapshot transaction_snapshot = GetTransactionSnapshot();
212 Snapshot active_snapshot = GetActiveSnapshot();
214 /* We might be running in a very short-lived memory context. */
215 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
217 /* Allow space to store the fixed-size parallel state. */
218 shm_toc_estimate_chunk(&pcxt->estimator, sizeof(FixedParallelState));
219 shm_toc_estimate_keys(&pcxt->estimator, 1);
222 * Normally, the user will have requested at least one worker process, but
223 * if by chance they have not, we can skip a bunch of things here.
225 if (pcxt->nworkers > 0)
227 /* Estimate space for various kinds of state sharing. */
228 library_len = EstimateLibraryStateSpace();
229 shm_toc_estimate_chunk(&pcxt->estimator, library_len);
230 guc_len = EstimateGUCStateSpace();
231 shm_toc_estimate_chunk(&pcxt->estimator, guc_len);
232 combocidlen = EstimateComboCIDStateSpace();
233 shm_toc_estimate_chunk(&pcxt->estimator, combocidlen);
234 tsnaplen = EstimateSnapshotSpace(transaction_snapshot);
235 shm_toc_estimate_chunk(&pcxt->estimator, tsnaplen);
236 asnaplen = EstimateSnapshotSpace(active_snapshot);
237 shm_toc_estimate_chunk(&pcxt->estimator, asnaplen);
238 tstatelen = EstimateTransactionStateSpace();
239 shm_toc_estimate_chunk(&pcxt->estimator, tstatelen);
240 /* If you add more chunks here, you probably need to add keys. */
241 shm_toc_estimate_keys(&pcxt->estimator, 6);
243 /* Estimate space need for error queues. */
244 StaticAssertStmt(BUFFERALIGN(PARALLEL_ERROR_QUEUE_SIZE) ==
245 PARALLEL_ERROR_QUEUE_SIZE,
246 "parallel error queue size not buffer-aligned");
247 shm_toc_estimate_chunk(&pcxt->estimator,
248 mul_size(PARALLEL_ERROR_QUEUE_SIZE,
250 shm_toc_estimate_keys(&pcxt->estimator, 1);
252 /* Estimate how much we'll need for extension entrypoint info. */
253 if (pcxt->library_name != NULL)
255 Assert(pcxt->entrypoint == ParallelExtensionTrampoline);
256 Assert(pcxt->function_name != NULL);
257 shm_toc_estimate_chunk(&pcxt->estimator, strlen(pcxt->library_name)
258 + strlen(pcxt->function_name) + 2);
259 shm_toc_estimate_keys(&pcxt->estimator, 1);
264 * Create DSM and initialize with new table of contents. But if the user
265 * didn't request any workers, then don't bother creating a dynamic shared
266 * memory segment; instead, just use backend-private memory.
268 * Also, if we can't create a dynamic shared memory segment because the
269 * maximum number of segments have already been created, then fall back to
270 * backend-private memory, and plan not to use any workers. We hope this
271 * won't happen very often, but it's better to abandon the use of
272 * parallelism than to fail outright.
274 segsize = shm_toc_estimate(&pcxt->estimator);
275 if (pcxt->nworkers > 0)
276 pcxt->seg = dsm_create(segsize, DSM_CREATE_NULL_IF_MAXSEGMENTS);
277 if (pcxt->seg != NULL)
278 pcxt->toc = shm_toc_create(PARALLEL_MAGIC,
279 dsm_segment_address(pcxt->seg),
284 pcxt->private_memory = MemoryContextAlloc(TopMemoryContext, segsize);
285 pcxt->toc = shm_toc_create(PARALLEL_MAGIC, pcxt->private_memory,
289 /* Initialize fixed-size state in shared memory. */
290 fps = (FixedParallelState *)
291 shm_toc_allocate(pcxt->toc, sizeof(FixedParallelState));
292 fps->database_id = MyDatabaseId;
293 fps->authenticated_user_id = GetAuthenticatedUserId();
294 GetUserIdAndSecContext(&fps->current_user_id, &fps->sec_context);
295 GetTempNamespaceState(&fps->temp_namespace_id,
296 &fps->temp_toast_namespace_id);
297 fps->parallel_master_pgproc = MyProc;
298 fps->parallel_master_pid = MyProcPid;
299 fps->parallel_master_backend_id = MyBackendId;
300 fps->entrypoint = pcxt->entrypoint;
301 SpinLockInit(&fps->mutex);
302 fps->last_xlog_end = 0;
303 shm_toc_insert(pcxt->toc, PARALLEL_KEY_FIXED, fps);
305 /* We can skip the rest of this if we're not budgeting for any workers. */
306 if (pcxt->nworkers > 0)
314 char *error_queue_space;
316 /* Serialize shared libraries we have loaded. */
317 libraryspace = shm_toc_allocate(pcxt->toc, library_len);
318 SerializeLibraryState(library_len, libraryspace);
319 shm_toc_insert(pcxt->toc, PARALLEL_KEY_LIBRARY, libraryspace);
321 /* Serialize GUC settings. */
322 gucspace = shm_toc_allocate(pcxt->toc, guc_len);
323 SerializeGUCState(guc_len, gucspace);
324 shm_toc_insert(pcxt->toc, PARALLEL_KEY_GUC, gucspace);
326 /* Serialize combo CID state. */
327 combocidspace = shm_toc_allocate(pcxt->toc, combocidlen);
328 SerializeComboCIDState(combocidlen, combocidspace);
329 shm_toc_insert(pcxt->toc, PARALLEL_KEY_COMBO_CID, combocidspace);
331 /* Serialize transaction snapshot and active snapshot. */
332 tsnapspace = shm_toc_allocate(pcxt->toc, tsnaplen);
333 SerializeSnapshot(transaction_snapshot, tsnapspace);
334 shm_toc_insert(pcxt->toc, PARALLEL_KEY_TRANSACTION_SNAPSHOT,
336 asnapspace = shm_toc_allocate(pcxt->toc, asnaplen);
337 SerializeSnapshot(active_snapshot, asnapspace);
338 shm_toc_insert(pcxt->toc, PARALLEL_KEY_ACTIVE_SNAPSHOT, asnapspace);
340 /* Serialize transaction state. */
341 tstatespace = shm_toc_allocate(pcxt->toc, tstatelen);
342 SerializeTransactionState(tstatelen, tstatespace);
343 shm_toc_insert(pcxt->toc, PARALLEL_KEY_TRANSACTION_STATE, tstatespace);
345 /* Allocate space for worker information. */
346 pcxt->worker = palloc0(sizeof(ParallelWorkerInfo) * pcxt->nworkers);
349 * Establish error queues in dynamic shared memory.
351 * These queues should be used only for transmitting ErrorResponse,
352 * NoticeResponse, and NotifyResponse protocol messages. Tuple data
353 * should be transmitted via separate (possibly larger?) queues.
356 shm_toc_allocate(pcxt->toc,
357 mul_size(PARALLEL_ERROR_QUEUE_SIZE,
359 for (i = 0; i < pcxt->nworkers; ++i)
364 start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
365 mq = shm_mq_create(start, PARALLEL_ERROR_QUEUE_SIZE);
366 shm_mq_set_receiver(mq, MyProc);
367 pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
369 shm_toc_insert(pcxt->toc, PARALLEL_KEY_ERROR_QUEUE, error_queue_space);
371 /* Serialize extension entrypoint information. */
372 if (pcxt->library_name != NULL)
374 Size lnamelen = strlen(pcxt->library_name);
375 char *extensionstate;
377 extensionstate = shm_toc_allocate(pcxt->toc, lnamelen
378 + strlen(pcxt->function_name) + 2);
379 strcpy(extensionstate, pcxt->library_name);
380 strcpy(extensionstate + lnamelen + 1, pcxt->function_name);
381 shm_toc_insert(pcxt->toc, PARALLEL_KEY_EXTENSION_TRAMPOLINE,
386 /* Restore previous memory context. */
387 MemoryContextSwitchTo(oldcontext);
391 * Reinitialize the dynamic shared memory segment for a parallel context such
392 * that we could launch workers for it again.
395 ReinitializeParallelDSM(ParallelContext *pcxt)
397 FixedParallelState *fps;
398 char *error_queue_space;
401 /* Wait for any old workers to exit. */
402 if (pcxt->nworkers_launched > 0)
404 WaitForParallelWorkersToFinish(pcxt);
405 WaitForParallelWorkersToExit(pcxt);
406 pcxt->nworkers_launched = 0;
409 /* Reset a few bits of fixed parallel state to a clean state. */
410 fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED);
411 fps->last_xlog_end = 0;
413 /* Recreate error queues. */
415 shm_toc_lookup(pcxt->toc, PARALLEL_KEY_ERROR_QUEUE);
416 for (i = 0; i < pcxt->nworkers; ++i)
421 start = error_queue_space + i * PARALLEL_ERROR_QUEUE_SIZE;
422 mq = shm_mq_create(start, PARALLEL_ERROR_QUEUE_SIZE);
423 shm_mq_set_receiver(mq, MyProc);
424 pcxt->worker[i].error_mqh = shm_mq_attach(mq, pcxt->seg, NULL);
429 * Launch parallel workers.
432 LaunchParallelWorkers(ParallelContext *pcxt)
434 MemoryContext oldcontext;
435 BackgroundWorker worker;
437 bool any_registrations_failed = false;
439 /* Skip this if we have no workers. */
440 if (pcxt->nworkers == 0)
443 /* We need to be a lock group leader. */
444 BecomeLockGroupLeader();
446 /* If we do have workers, we'd better have a DSM segment. */
447 Assert(pcxt->seg != NULL);
449 /* We might be running in a short-lived memory context. */
450 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
452 /* Configure a worker. */
453 snprintf(worker.bgw_name, BGW_MAXLEN, "parallel worker for PID %d",
456 BGWORKER_SHMEM_ACCESS | BGWORKER_BACKEND_DATABASE_CONNECTION
457 | BGWORKER_CLASS_PARALLEL;
458 worker.bgw_start_time = BgWorkerStart_ConsistentState;
459 worker.bgw_restart_time = BGW_NEVER_RESTART;
460 sprintf(worker.bgw_library_name, "postgres");
461 sprintf(worker.bgw_function_name, "ParallelWorkerMain");
462 worker.bgw_main_arg = UInt32GetDatum(dsm_segment_handle(pcxt->seg));
463 worker.bgw_notify_pid = MyProcPid;
464 memset(&worker.bgw_extra, 0, BGW_EXTRALEN);
469 * The caller must be able to tolerate ending up with fewer workers than
470 * expected, so there is no need to throw an error here if registration
471 * fails. It wouldn't help much anyway, because registering the worker in
472 * no way guarantees that it will start up and initialize successfully.
474 for (i = 0; i < pcxt->nworkers; ++i)
476 memcpy(worker.bgw_extra, &i, sizeof(int));
477 if (!any_registrations_failed &&
478 RegisterDynamicBackgroundWorker(&worker,
479 &pcxt->worker[i].bgwhandle))
481 shm_mq_set_handle(pcxt->worker[i].error_mqh,
482 pcxt->worker[i].bgwhandle);
483 pcxt->nworkers_launched++;
488 * If we weren't able to register the worker, then we've bumped up
489 * against the max_worker_processes limit, and future
490 * registrations will probably fail too, so arrange to skip them.
491 * But we still have to execute this code for the remaining slots
492 * to make sure that we forget about the error queues we budgeted
493 * for those workers. Otherwise, we'll wait for them to start,
494 * but they never will.
496 any_registrations_failed = true;
497 pcxt->worker[i].bgwhandle = NULL;
498 pfree(pcxt->worker[i].error_mqh);
499 pcxt->worker[i].error_mqh = NULL;
503 /* Restore previous memory context. */
504 MemoryContextSwitchTo(oldcontext);
508 * Wait for all workers to finish computing.
510 * Even if the parallel operation seems to have completed successfully, it's
511 * important to call this function afterwards. We must not miss any errors
512 * the workers may have thrown during the parallel operation, or any that they
513 * may yet throw while shutting down.
515 * Also, we want to update our notion of XactLastRecEnd based on worker
519 WaitForParallelWorkersToFinish(ParallelContext *pcxt)
523 bool anyone_alive = false;
527 * This will process any parallel messages that are pending, which may
528 * change the outcome of the loop that follows. It may also throw an
529 * error propagated from a worker.
531 CHECK_FOR_INTERRUPTS();
533 for (i = 0; i < pcxt->nworkers_launched; ++i)
535 if (pcxt->worker[i].error_mqh != NULL)
545 WaitLatch(&MyProc->procLatch, WL_LATCH_SET, -1,
546 WAIT_EVENT_PARALLEL_FINISH);
547 ResetLatch(&MyProc->procLatch);
550 if (pcxt->toc != NULL)
552 FixedParallelState *fps;
554 fps = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_FIXED);
555 if (fps->last_xlog_end > XactLastRecEnd)
556 XactLastRecEnd = fps->last_xlog_end;
561 * Wait for all workers to exit.
563 * This function ensures that workers have been completely shutdown. The
564 * difference between WaitForParallelWorkersToFinish and this function is
565 * that former just ensures that last message sent by worker backend is
566 * received by master backend whereas this ensures the complete shutdown.
569 WaitForParallelWorkersToExit(ParallelContext *pcxt)
573 /* Wait until the workers actually die. */
574 for (i = 0; i < pcxt->nworkers_launched; ++i)
576 BgwHandleStatus status;
578 if (pcxt->worker == NULL || pcxt->worker[i].bgwhandle == NULL)
581 status = WaitForBackgroundWorkerShutdown(pcxt->worker[i].bgwhandle);
584 * If the postmaster kicked the bucket, we have no chance of cleaning
585 * up safely -- we won't be able to tell when our workers are actually
586 * dead. This doesn't necessitate a PANIC since they will all abort
587 * eventually, but we can't safely continue this session.
589 if (status == BGWH_POSTMASTER_DIED)
591 (errcode(ERRCODE_ADMIN_SHUTDOWN),
592 errmsg("postmaster exited during a parallel transaction")));
594 /* Release memory. */
595 pfree(pcxt->worker[i].bgwhandle);
596 pcxt->worker[i].bgwhandle = NULL;
601 * Destroy a parallel context.
603 * If expecting a clean exit, you should use WaitForParallelWorkersToFinish()
604 * first, before calling this function. When this function is invoked, any
605 * remaining workers are forcibly killed; the dynamic shared memory segment
606 * is unmapped; and we then wait (uninterruptibly) for the workers to exit.
609 DestroyParallelContext(ParallelContext *pcxt)
614 * Be careful about order of operations here! We remove the parallel
615 * context from the list before we do anything else; otherwise, if an
616 * error occurs during a subsequent step, we might try to nuke it again
617 * from AtEOXact_Parallel or AtEOSubXact_Parallel.
619 dlist_delete(&pcxt->node);
621 /* Kill each worker in turn, and forget their error queues. */
622 if (pcxt->worker != NULL)
624 for (i = 0; i < pcxt->nworkers_launched; ++i)
626 if (pcxt->worker[i].error_mqh != NULL)
628 TerminateBackgroundWorker(pcxt->worker[i].bgwhandle);
630 pfree(pcxt->worker[i].error_mqh);
631 pcxt->worker[i].error_mqh = NULL;
637 * If we have allocated a shared memory segment, detach it. This will
638 * implicitly detach the error queues, and any other shared memory queues,
641 if (pcxt->seg != NULL)
643 dsm_detach(pcxt->seg);
648 * If this parallel context is actually in backend-private memory rather
649 * than shared memory, free that memory instead.
651 if (pcxt->private_memory != NULL)
653 pfree(pcxt->private_memory);
654 pcxt->private_memory = NULL;
658 * We can't finish transaction commit or abort until all of the workers
659 * have exited. This means, in particular, that we can't respond to
660 * interrupts at this stage.
663 WaitForParallelWorkersToExit(pcxt);
666 /* Free the worker array itself. */
667 if (pcxt->worker != NULL)
678 * Are there any parallel contexts currently active?
681 ParallelContextActive(void)
683 return !dlist_is_empty(&pcxt_list);
687 * Handle receipt of an interrupt indicating a parallel worker message.
689 * Note: this is called within a signal handler! All we can do is set
690 * a flag that will cause the next CHECK_FOR_INTERRUPTS() to invoke
691 * HandleParallelMessages().
694 HandleParallelMessageInterrupt(void)
696 InterruptPending = true;
697 ParallelMessagePending = true;
702 * Handle any queued protocol messages received from parallel workers.
705 HandleParallelMessages(void)
708 MemoryContext oldcontext;
710 static MemoryContext hpm_context = NULL;
713 * This is invoked from ProcessInterrupts(), and since some of the
714 * functions it calls contain CHECK_FOR_INTERRUPTS(), there is a potential
715 * for recursive calls if more signals are received while this runs. It's
716 * unclear that recursive entry would be safe, and it doesn't seem useful
717 * even if it is safe, so let's block interrupts until done.
722 * Moreover, CurrentMemoryContext might be pointing almost anywhere. We
723 * don't want to risk leaking data into long-lived contexts, so let's do
724 * our work here in a private context that we can reset on each use.
726 if (hpm_context == NULL) /* first time through? */
727 hpm_context = AllocSetContextCreate(TopMemoryContext,
728 "HandleParallelMessages",
729 ALLOCSET_DEFAULT_SIZES);
731 MemoryContextReset(hpm_context);
733 oldcontext = MemoryContextSwitchTo(hpm_context);
735 /* OK to process messages. Reset the flag saying there are more to do. */
736 ParallelMessagePending = false;
738 dlist_foreach(iter, &pcxt_list)
740 ParallelContext *pcxt;
743 pcxt = dlist_container(ParallelContext, node, iter.cur);
744 if (pcxt->worker == NULL)
747 for (i = 0; i < pcxt->nworkers_launched; ++i)
750 * Read as many messages as we can from each worker, but stop when
751 * either (1) the worker's error queue goes away, which can happen
752 * if we receive a Terminate message from the worker; or (2) no
753 * more messages can be read from the worker without blocking.
755 while (pcxt->worker[i].error_mqh != NULL)
761 res = shm_mq_receive(pcxt->worker[i].error_mqh, &nbytes,
763 if (res == SHM_MQ_WOULD_BLOCK)
765 else if (res == SHM_MQ_SUCCESS)
769 initStringInfo(&msg);
770 appendBinaryStringInfo(&msg, data, nbytes);
771 HandleParallelMessage(pcxt, i, &msg);
776 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
777 errmsg("lost connection to parallel worker")));
782 MemoryContextSwitchTo(oldcontext);
784 /* Might as well clear the context on our way out */
785 MemoryContextReset(hpm_context);
791 * Handle a single protocol message received from a single parallel worker.
794 HandleParallelMessage(ParallelContext *pcxt, int i, StringInfo msg)
798 msgtype = pq_getmsgbyte(msg);
802 case 'K': /* BackendKeyData */
804 int32 pid = pq_getmsgint(msg, 4);
806 (void) pq_getmsgint(msg, 4); /* discard cancel key */
807 (void) pq_getmsgend(msg);
808 pcxt->worker[i].pid = pid;
812 case 'E': /* ErrorResponse */
813 case 'N': /* NoticeResponse */
816 ErrorContextCallback *save_error_context_stack;
818 /* Parse ErrorResponse or NoticeResponse. */
819 pq_parse_errornotice(msg, &edata);
821 /* Death of a worker isn't enough justification for suicide. */
822 edata.elevel = Min(edata.elevel, ERROR);
825 * If desired, add a context line to show that this is a
826 * message propagated from a parallel worker. Otherwise, it
827 * can sometimes be confusing to understand what actually
828 * happened. (We don't do this in FORCE_PARALLEL_REGRESS mode
829 * because it causes test-result instability depending on
830 * whether a parallel worker is actually used or not.)
832 if (force_parallel_mode != FORCE_PARALLEL_REGRESS)
835 edata.context = psprintf("%s\n%s", edata.context,
836 _("parallel worker"));
838 edata.context = pstrdup(_("parallel worker"));
842 * Context beyond that should use the error context callbacks
843 * that were in effect when the ParallelContext was created,
844 * not the current ones.
846 save_error_context_stack = error_context_stack;
847 error_context_stack = pcxt->error_context_stack;
849 /* Rethrow error or print notice. */
850 ThrowErrorData(&edata);
852 /* Not an error, so restore previous context stack. */
853 error_context_stack = save_error_context_stack;
858 case 'A': /* NotifyResponse */
860 /* Propagate NotifyResponse. */
865 pid = pq_getmsgint(msg, 4);
866 channel = pq_getmsgrawstring(msg);
867 payload = pq_getmsgrawstring(msg);
870 NotifyMyFrontEnd(channel, payload, pid);
875 case 'X': /* Terminate, indicating clean exit */
877 pfree(pcxt->worker[i].error_mqh);
878 pcxt->worker[i].error_mqh = NULL;
884 elog(ERROR, "unrecognized message type received from parallel worker: %c (message length %d bytes)",
891 * End-of-subtransaction cleanup for parallel contexts.
893 * Currently, it's forbidden to enter or leave a subtransaction while
894 * parallel mode is in effect, so we could just blow away everything. But
895 * we may want to relax that restriction in the future, so this code
896 * contemplates that there may be multiple subtransaction IDs in pcxt_list.
899 AtEOSubXact_Parallel(bool isCommit, SubTransactionId mySubId)
901 while (!dlist_is_empty(&pcxt_list))
903 ParallelContext *pcxt;
905 pcxt = dlist_head_element(ParallelContext, node, &pcxt_list);
906 if (pcxt->subid != mySubId)
909 elog(WARNING, "leaked parallel context");
910 DestroyParallelContext(pcxt);
915 * End-of-transaction cleanup for parallel contexts.
918 AtEOXact_Parallel(bool isCommit)
920 while (!dlist_is_empty(&pcxt_list))
922 ParallelContext *pcxt;
924 pcxt = dlist_head_element(ParallelContext, node, &pcxt_list);
926 elog(WARNING, "leaked parallel context");
927 DestroyParallelContext(pcxt);
932 * Main entrypoint for parallel workers.
935 ParallelWorkerMain(Datum main_arg)
939 FixedParallelState *fps;
940 char *error_queue_space;
949 StringInfoData msgbuf;
951 /* Set flag to indicate that we're initializing a parallel worker. */
952 InitializingParallelWorker = true;
954 /* Establish signal handlers. */
955 pqsignal(SIGTERM, die);
956 BackgroundWorkerUnblockSignals();
958 /* Determine and set our parallel worker number. */
959 Assert(ParallelWorkerNumber == -1);
960 memcpy(&ParallelWorkerNumber, MyBgworkerEntry->bgw_extra, sizeof(int));
962 /* Set up a memory context and resource owner. */
963 Assert(CurrentResourceOwner == NULL);
964 CurrentResourceOwner = ResourceOwnerCreate(NULL, "parallel toplevel");
965 CurrentMemoryContext = AllocSetContextCreate(TopMemoryContext,
967 ALLOCSET_DEFAULT_SIZES);
970 * Now that we have a resource owner, we can attach to the dynamic shared
971 * memory segment and read the table of contents.
973 seg = dsm_attach(DatumGetUInt32(main_arg));
976 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
977 errmsg("could not map dynamic shared memory segment")));
978 toc = shm_toc_attach(PARALLEL_MAGIC, dsm_segment_address(seg));
981 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
982 errmsg("invalid magic number in dynamic shared memory segment")));
984 /* Look up fixed parallel state. */
985 fps = shm_toc_lookup(toc, PARALLEL_KEY_FIXED);
987 MyFixedParallelState = fps;
990 * Now that we have a worker number, we can find and attach to the error
991 * queue provided for us. That's good, because until we do that, any
992 * errors that happen here will not be reported back to the process that
993 * requested that this worker be launched.
995 error_queue_space = shm_toc_lookup(toc, PARALLEL_KEY_ERROR_QUEUE);
996 mq = (shm_mq *) (error_queue_space +
997 ParallelWorkerNumber * PARALLEL_ERROR_QUEUE_SIZE);
998 shm_mq_set_sender(mq, MyProc);
999 mqh = shm_mq_attach(mq, seg, NULL);
1000 pq_redirect_to_shm_mq(seg, mqh);
1001 pq_set_parallel_master(fps->parallel_master_pid,
1002 fps->parallel_master_backend_id);
1005 * Send a BackendKeyData message to the process that initiated parallelism
1006 * so that it has access to our PID before it receives any other messages
1007 * from us. Our cancel key is sent, too, since that's the way the
1008 * protocol message is defined, but it won't actually be used for anything
1011 pq_beginmessage(&msgbuf, 'K');
1012 pq_sendint(&msgbuf, (int32) MyProcPid, sizeof(int32));
1013 pq_sendint(&msgbuf, (int32) MyCancelKey, sizeof(int32));
1014 pq_endmessage(&msgbuf);
1017 * Hooray! Primary initialization is complete. Now, we need to set up our
1018 * backend-local state to match the original backend.
1022 * Join locking group. We must do this before anything that could try to
1023 * acquire a heavyweight lock, because any heavyweight locks acquired to
1024 * this point could block either directly against the parallel group
1025 * leader or against some process which in turn waits for a lock that
1026 * conflicts with the parallel group leader, causing an undetected
1027 * deadlock. (If we can't join the lock group, the leader has gone away,
1028 * so just exit quietly.)
1030 if (!BecomeLockGroupMember(fps->parallel_master_pgproc,
1031 fps->parallel_master_pid))
1035 * Load libraries that were loaded by original backend. We want to do
1036 * this before restoring GUCs, because the libraries might define custom
1039 libraryspace = shm_toc_lookup(toc, PARALLEL_KEY_LIBRARY);
1040 Assert(libraryspace != NULL);
1041 RestoreLibraryState(libraryspace);
1043 /* Restore database connection. */
1044 BackgroundWorkerInitializeConnectionByOid(fps->database_id,
1045 fps->authenticated_user_id);
1048 * Set the client encoding to the database encoding, since that is what
1049 * the leader will expect.
1051 SetClientEncoding(GetDatabaseEncoding());
1053 /* Restore GUC values from launching backend. */
1054 gucspace = shm_toc_lookup(toc, PARALLEL_KEY_GUC);
1055 Assert(gucspace != NULL);
1056 StartTransactionCommand();
1057 RestoreGUCState(gucspace);
1058 CommitTransactionCommand();
1060 /* Crank up a transaction state appropriate to a parallel worker. */
1061 tstatespace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_STATE);
1062 StartParallelWorkerTransaction(tstatespace);
1064 /* Restore combo CID state. */
1065 combocidspace = shm_toc_lookup(toc, PARALLEL_KEY_COMBO_CID);
1066 Assert(combocidspace != NULL);
1067 RestoreComboCIDState(combocidspace);
1069 /* Restore transaction snapshot. */
1070 tsnapspace = shm_toc_lookup(toc, PARALLEL_KEY_TRANSACTION_SNAPSHOT);
1071 Assert(tsnapspace != NULL);
1072 RestoreTransactionSnapshot(RestoreSnapshot(tsnapspace),
1073 fps->parallel_master_pgproc);
1075 /* Restore active snapshot. */
1076 asnapspace = shm_toc_lookup(toc, PARALLEL_KEY_ACTIVE_SNAPSHOT);
1077 Assert(asnapspace != NULL);
1078 PushActiveSnapshot(RestoreSnapshot(asnapspace));
1081 * We've changed which tuples we can see, and must therefore invalidate
1084 InvalidateSystemCaches();
1086 /* Restore user ID and security context. */
1087 SetUserIdAndSecContext(fps->current_user_id, fps->sec_context);
1089 /* Restore temp-namespace state to ensure search path matches leader's. */
1090 SetTempNamespaceState(fps->temp_namespace_id,
1091 fps->temp_toast_namespace_id);
1093 /* Set ParallelMasterBackendId so we know how to address temp relations. */
1094 ParallelMasterBackendId = fps->parallel_master_backend_id;
1097 * We've initialized all of our state now; nothing should change
1100 InitializingParallelWorker = false;
1101 EnterParallelMode();
1104 * Time to do the real work: invoke the caller-supplied code.
1106 * If you get a crash at this line, see the comments for
1107 * ParallelExtensionTrampoline.
1109 fps->entrypoint(seg, toc);
1111 /* Must exit parallel mode to pop active snapshot. */
1114 /* Must pop active snapshot so resowner.c doesn't complain. */
1115 PopActiveSnapshot();
1117 /* Shut down the parallel-worker transaction. */
1118 EndParallelWorkerTransaction();
1120 /* Report success. */
1121 pq_putmessage('X', NULL, 0);
1125 * It's unsafe for the entrypoint invoked by ParallelWorkerMain to be a
1126 * function living in a dynamically loaded module, because the module might
1127 * not be loaded in every process, or might be loaded but not at the same
1128 * address. To work around that problem, CreateParallelContextForExtension()
1129 * arranges to call this function rather than calling the extension-provided
1130 * function directly; and this function then looks up the real entrypoint and
1134 ParallelExtensionTrampoline(dsm_segment *seg, shm_toc *toc)
1136 char *extensionstate;
1138 char *function_name;
1139 parallel_worker_main_type entrypt;
1141 extensionstate = shm_toc_lookup(toc, PARALLEL_KEY_EXTENSION_TRAMPOLINE);
1142 Assert(extensionstate != NULL);
1143 library_name = extensionstate;
1144 function_name = extensionstate + strlen(library_name) + 1;
1146 entrypt = (parallel_worker_main_type)
1147 load_external_function(library_name, function_name, true, NULL);
1152 * Update shared memory with the ending location of the last WAL record we
1153 * wrote, if it's greater than the value already stored there.
1156 ParallelWorkerReportLastRecEnd(XLogRecPtr last_xlog_end)
1158 FixedParallelState *fps = MyFixedParallelState;
1160 Assert(fps != NULL);
1161 SpinLockAcquire(&fps->mutex);
1162 if (fps->last_xlog_end < last_xlog_end)
1163 fps->last_xlog_end = last_xlog_end;
1164 SpinLockRelease(&fps->mutex);