PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
execParallel.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * execParallel.c
4  * Support routines for parallel execution.
5  *
6  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * This file contains routines that are intended to support setting up,
10  * using, and tearing down a ParallelContext from within the PostgreSQL
11  * executor. The ParallelContext machinery will handle starting the
12  * workers and ensuring that their state generally matches that of the
13  * leader; see src/backend/access/transam/README.parallel for details.
14  * However, we must save and restore relevant executor state, such as
15  * any ParamListInfo associated with the query, buffer usage info, and
16  * the actual plan to be passed down to the worker.
17  *
18  * IDENTIFICATION
19  * src/backend/executor/execParallel.c
20  *
21  *-------------------------------------------------------------------------
22  */
23 
24 #include "postgres.h"
25 
26 #include "executor/execParallel.h"
27 #include "executor/executor.h"
28 #include "executor/nodeCustom.h"
30 #include "executor/nodeSeqscan.h"
31 #include "executor/nodeIndexscan.h"
33 #include "executor/tqueue.h"
34 #include "nodes/nodeFuncs.h"
35 #include "optimizer/planmain.h"
36 #include "optimizer/planner.h"
37 #include "storage/spin.h"
38 #include "tcop/tcopprot.h"
39 #include "utils/dsa.h"
40 #include "utils/memutils.h"
41 #include "utils/snapmgr.h"
42 #include "pgstat.h"
43 
44 /*
45  * Magic numbers for parallel executor communication. We use constants
46  * greater than any 32-bit integer here so that values < 2^32 can be used
47  * by individual parallel nodes to store their own state.
48  */
49 #define PARALLEL_KEY_PLANNEDSTMT UINT64CONST(0xE000000000000001)
50 #define PARALLEL_KEY_PARAMS UINT64CONST(0xE000000000000002)
51 #define PARALLEL_KEY_BUFFER_USAGE UINT64CONST(0xE000000000000003)
52 #define PARALLEL_KEY_TUPLE_QUEUE UINT64CONST(0xE000000000000004)
53 #define PARALLEL_KEY_INSTRUMENTATION UINT64CONST(0xE000000000000005)
54 #define PARALLEL_KEY_DSA UINT64CONST(0xE000000000000006)
55 #define PARALLEL_KEY_QUERY_TEXT UINT64CONST(0xE000000000000007)
56 
57 #define PARALLEL_TUPLE_QUEUE_SIZE 65536
58 
59 /*
60  * DSM structure for accumulating per-PlanState instrumentation.
61  *
62  * instrument_options: Same meaning here as in instrument.c.
63  *
64  * instrument_offset: Offset, relative to the start of this structure,
65  * of the first Instrumentation object. This will depend on the length of
66  * the plan_node_id array.
67  *
68  * num_workers: Number of workers.
69  *
70  * num_plan_nodes: Number of plan nodes.
71  *
72  * plan_node_id: Array of plan nodes for which we are gathering instrumentation
73  * from parallel workers. The length of this array is given by num_plan_nodes.
74  */
76 {
81  int plan_node_id[FLEXIBLE_ARRAY_MEMBER];
82  /* array of num_plan_nodes * num_workers Instrumentation objects follows */
83 };
84 #define GetInstrumentationArray(sei) \
85  (AssertVariableIsOfTypeMacro(sei, SharedExecutorInstrumentation *), \
86  (Instrumentation *) (((char *) sei) + sei->instrument_offset))
87 
88 /* Context object for ExecParallelEstimate. */
90 {
92  int nnodes;
94 
95 /* Context object for ExecParallelInitializeDSM. */
97 {
100  int nnodes;
102 
103 /* Helper functions that run in the parallel leader. */
104 static char *ExecSerializePlan(Plan *plan, EState *estate);
105 static bool ExecParallelEstimate(PlanState *node,
107 static bool ExecParallelInitializeDSM(PlanState *node,
110  bool reinitialize);
111 static bool ExecParallelRetrieveInstrumentation(PlanState *planstate,
112  SharedExecutorInstrumentation *instrumentation);
113 
114 /* Helper functions that run in the parallel worker. */
115 static void ParallelQueryMain(dsm_segment *seg, shm_toc *toc);
117 
118 /*
119  * Create a serialized representation of the plan to be sent to each worker.
120  */
121 static char *
123 {
124  PlannedStmt *pstmt;
125  ListCell *tlist;
126 
127  /* We can't scribble on the original plan, so make a copy. */
128  plan = copyObject(plan);
129 
130  /*
131  * The worker will start its own copy of the executor, and that copy will
132  * insert a junk filter if the toplevel node has any resjunk entries. We
133  * don't want that to happen, because while resjunk columns shouldn't be
134  * sent back to the user, here the tuples are coming back to another
135  * backend which may very well need them. So mutate the target list
136  * accordingly. This is sort of a hack; there might be better ways to do
137  * this...
138  */
139  foreach(tlist, plan->targetlist)
140  {
141  TargetEntry *tle = (TargetEntry *) lfirst(tlist);
142 
143  tle->resjunk = false;
144  }
145 
146  /*
147  * Create a dummy PlannedStmt. Most of the fields don't need to be valid
148  * for our purposes, but the worker will need at least a minimal
149  * PlannedStmt to start the executor.
150  */
151  pstmt = makeNode(PlannedStmt);
152  pstmt->commandType = CMD_SELECT;
153  pstmt->queryId = 0;
154  pstmt->hasReturning = false;
155  pstmt->hasModifyingCTE = false;
156  pstmt->canSetTag = true;
157  pstmt->transientPlan = false;
158  pstmt->dependsOnRole = false;
159  pstmt->parallelModeNeeded = false;
160  pstmt->planTree = plan;
161  pstmt->rtable = estate->es_range_table;
162  pstmt->resultRelations = NIL;
163  pstmt->subplans = estate->es_plannedstmt->subplans;
164  pstmt->rewindPlanIDs = NULL;
165  pstmt->rowMarks = NIL;
166  pstmt->relationOids = NIL;
167  pstmt->invalItems = NIL; /* workers can't replan anyway... */
168  pstmt->nParamExec = estate->es_plannedstmt->nParamExec;
169  pstmt->utilityStmt = NULL;
170  pstmt->stmt_location = -1;
171  pstmt->stmt_len = -1;
172 
173  /* Return serialized copy of our dummy PlannedStmt. */
174  return nodeToString(pstmt);
175 }
176 
177 /*
178  * Ordinary plan nodes won't do anything here, but parallel-aware plan nodes
179  * may need some state which is shared across all parallel workers. Before
180  * we size the DSM, give them a chance to call shm_toc_estimate_chunk or
181  * shm_toc_estimate_keys on &pcxt->estimator.
182  *
183  * While we're at it, count the number of PlanState nodes in the tree, so
184  * we know how many SharedPlanStateInstrumentation structures we need.
185  */
186 static bool
188 {
189  if (planstate == NULL)
190  return false;
191 
192  /* Count this node. */
193  e->nnodes++;
194 
195  /* Call estimators for parallel-aware nodes. */
196  if (planstate->plan->parallel_aware)
197  {
198  switch (nodeTag(planstate))
199  {
200  case T_SeqScanState:
201  ExecSeqScanEstimate((SeqScanState *) planstate,
202  e->pcxt);
203  break;
204  case T_IndexScanState:
206  e->pcxt);
207  break;
210  e->pcxt);
211  break;
212  case T_ForeignScanState:
214  e->pcxt);
215  break;
216  case T_CustomScanState:
218  e->pcxt);
219  break;
220  default:
221  break;
222  }
223  }
224 
225  return planstate_tree_walker(planstate, ExecParallelEstimate, e);
226 }
227 
228 /*
229  * Initialize the dynamic shared memory segment that will be used to control
230  * parallel execution.
231  */
232 static bool
235 {
236  if (planstate == NULL)
237  return false;
238 
239  /* If instrumentation is enabled, initialize slot for this node. */
240  if (d->instrumentation != NULL)
242  planstate->plan->plan_node_id;
243 
244  /* Count this node. */
245  d->nnodes++;
246 
247  /*
248  * Call initializers for parallel-aware plan nodes.
249  *
250  * Ordinary plan nodes won't do anything here, but parallel-aware plan
251  * nodes may need to initialize shared state in the DSM before parallel
252  * workers are available. They can allocate the space they previously
253  * estimated using shm_toc_allocate, and add the keys they previously
254  * estimated using shm_toc_insert, in each case targeting pcxt->toc.
255  */
256  if (planstate->plan->parallel_aware)
257  {
258  switch (nodeTag(planstate))
259  {
260  case T_SeqScanState:
262  d->pcxt);
263  break;
264  case T_IndexScanState:
266  d->pcxt);
267  break;
270  d->pcxt);
271  break;
272  case T_ForeignScanState:
274  d->pcxt);
275  break;
276  case T_CustomScanState:
278  d->pcxt);
279  break;
280  default:
281  break;
282  }
283  }
284 
285  return planstate_tree_walker(planstate, ExecParallelInitializeDSM, d);
286 }
287 
288 /*
289  * It sets up the response queues for backend workers to return tuples
290  * to the main backend and start the workers.
291  */
292 static shm_mq_handle **
294 {
295  shm_mq_handle **responseq;
296  char *tqueuespace;
297  int i;
298 
299  /* Skip this if no workers. */
300  if (pcxt->nworkers == 0)
301  return NULL;
302 
303  /* Allocate memory for shared memory queue handles. */
304  responseq = (shm_mq_handle **)
305  palloc(pcxt->nworkers * sizeof(shm_mq_handle *));
306 
307  /*
308  * If not reinitializing, allocate space from the DSM for the queues;
309  * otherwise, find the already allocated space.
310  */
311  if (!reinitialize)
312  tqueuespace =
313  shm_toc_allocate(pcxt->toc,
315  pcxt->nworkers));
316  else
317  tqueuespace = shm_toc_lookup(pcxt->toc, PARALLEL_KEY_TUPLE_QUEUE);
318 
319  /* Create the queues, and become the receiver for each. */
320  for (i = 0; i < pcxt->nworkers; ++i)
321  {
322  shm_mq *mq;
323 
324  mq = shm_mq_create(tqueuespace +
326  (Size) PARALLEL_TUPLE_QUEUE_SIZE);
327 
329  responseq[i] = shm_mq_attach(mq, pcxt->seg, NULL);
330  }
331 
332  /* Add array of queues to shm_toc, so others can find it. */
333  if (!reinitialize)
334  shm_toc_insert(pcxt->toc, PARALLEL_KEY_TUPLE_QUEUE, tqueuespace);
335 
336  /* Return array of handles. */
337  return responseq;
338 }
339 
340 /*
341  * Re-initialize the parallel executor info such that it can be reused by
342  * workers.
343  */
344 void
346 {
348  pei->tqueue = ExecParallelSetupTupleQueues(pei->pcxt, true);
349  pei->finished = false;
350 }
351 
352 /*
353  * Sets up the required infrastructure for backend workers to perform
354  * execution and return results to the main backend.
355  */
357 ExecInitParallelPlan(PlanState *planstate, EState *estate, int nworkers)
358 {
360  ParallelContext *pcxt;
363  char *pstmt_data;
364  char *pstmt_space;
365  char *param_space;
366  BufferUsage *bufusage_space;
367  SharedExecutorInstrumentation *instrumentation = NULL;
368  int pstmt_len;
369  int param_len;
370  int instrumentation_len = 0;
371  int instrument_offset = 0;
372  Size dsa_minsize = dsa_minimum_size();
373  char *query_string;
374  int query_len;
375 
376  /* Allocate object for return value. */
377  pei = palloc0(sizeof(ParallelExecutorInfo));
378  pei->finished = false;
379  pei->planstate = planstate;
380 
381  /* Fix up and serialize plan to be sent to workers. */
382  pstmt_data = ExecSerializePlan(planstate->plan, estate);
383 
384  /* Create a parallel context. */
385  pcxt = CreateParallelContext(ParallelQueryMain, nworkers);
386  pei->pcxt = pcxt;
387 
388  /*
389  * Before telling the parallel context to create a dynamic shared memory
390  * segment, we need to figure out how big it should be. Estimate space
391  * for the various things we need to store.
392  */
393 
394  /* Estimate space for query text. */
395  query_len = strlen(estate->es_sourceText);
396  shm_toc_estimate_chunk(&pcxt->estimator, query_len);
397  shm_toc_estimate_keys(&pcxt->estimator, 1);
398 
399  /* Estimate space for serialized PlannedStmt. */
400  pstmt_len = strlen(pstmt_data) + 1;
401  shm_toc_estimate_chunk(&pcxt->estimator, pstmt_len);
402  shm_toc_estimate_keys(&pcxt->estimator, 1);
403 
404  /* Estimate space for serialized ParamListInfo. */
405  param_len = EstimateParamListSpace(estate->es_param_list_info);
406  shm_toc_estimate_chunk(&pcxt->estimator, param_len);
407  shm_toc_estimate_keys(&pcxt->estimator, 1);
408 
409  /*
410  * Estimate space for BufferUsage.
411  *
412  * If EXPLAIN is not in use and there are no extensions loaded that care,
413  * we could skip this. But we have no way of knowing whether anyone's
414  * looking at pgBufferUsage, so do it unconditionally.
415  */
417  mul_size(sizeof(BufferUsage), pcxt->nworkers));
418  shm_toc_estimate_keys(&pcxt->estimator, 1);
419 
420  /* Estimate space for tuple queues. */
423  shm_toc_estimate_keys(&pcxt->estimator, 1);
424 
425  /*
426  * Give parallel-aware nodes a chance to add to the estimates, and get a
427  * count of how many PlanState nodes there are.
428  */
429  e.pcxt = pcxt;
430  e.nnodes = 0;
431  ExecParallelEstimate(planstate, &e);
432 
433  /* Estimate space for instrumentation, if required. */
434  if (estate->es_instrument)
435  {
436  instrumentation_len =
437  offsetof(SharedExecutorInstrumentation, plan_node_id) +
438  sizeof(int) * e.nnodes;
439  instrumentation_len = MAXALIGN(instrumentation_len);
440  instrument_offset = instrumentation_len;
441  instrumentation_len +=
442  mul_size(sizeof(Instrumentation),
443  mul_size(e.nnodes, nworkers));
444  shm_toc_estimate_chunk(&pcxt->estimator, instrumentation_len);
445  shm_toc_estimate_keys(&pcxt->estimator, 1);
446  }
447 
448  /* Estimate space for DSA area. */
449  shm_toc_estimate_chunk(&pcxt->estimator, dsa_minsize);
450  shm_toc_estimate_keys(&pcxt->estimator, 1);
451 
452  /* Everyone's had a chance to ask for space, so now create the DSM. */
453  InitializeParallelDSM(pcxt);
454 
455  /*
456  * OK, now we have a dynamic shared memory segment, and it should be big
457  * enough to store all of the data we estimated we would want to put into
458  * it, plus whatever general stuff (not specifically executor-related) the
459  * ParallelContext itself needs to store there. None of the space we
460  * asked for has been allocated or initialized yet, though, so do that.
461  */
462 
463  /* Store query string */
464  query_string = shm_toc_allocate(pcxt->toc, query_len);
465  memcpy(query_string, estate->es_sourceText, query_len);
466  shm_toc_insert(pcxt->toc, PARALLEL_KEY_QUERY_TEXT, query_string);
467 
468  /* Store serialized PlannedStmt. */
469  pstmt_space = shm_toc_allocate(pcxt->toc, pstmt_len);
470  memcpy(pstmt_space, pstmt_data, pstmt_len);
471  shm_toc_insert(pcxt->toc, PARALLEL_KEY_PLANNEDSTMT, pstmt_space);
472 
473  /* Store serialized ParamListInfo. */
474  param_space = shm_toc_allocate(pcxt->toc, param_len);
475  shm_toc_insert(pcxt->toc, PARALLEL_KEY_PARAMS, param_space);
476  SerializeParamList(estate->es_param_list_info, &param_space);
477 
478  /* Allocate space for each worker's BufferUsage; no need to initialize. */
479  bufusage_space = shm_toc_allocate(pcxt->toc,
480  mul_size(sizeof(BufferUsage), pcxt->nworkers));
481  shm_toc_insert(pcxt->toc, PARALLEL_KEY_BUFFER_USAGE, bufusage_space);
482  pei->buffer_usage = bufusage_space;
483 
484  /* Set up tuple queues. */
485  pei->tqueue = ExecParallelSetupTupleQueues(pcxt, false);
486 
487  /*
488  * If instrumentation options were supplied, allocate space for the data.
489  * It only gets partially initialized here; the rest happens during
490  * ExecParallelInitializeDSM.
491  */
492  if (estate->es_instrument)
493  {
494  Instrumentation *instrument;
495  int i;
496 
497  instrumentation = shm_toc_allocate(pcxt->toc, instrumentation_len);
498  instrumentation->instrument_options = estate->es_instrument;
499  instrumentation->instrument_offset = instrument_offset;
500  instrumentation->num_workers = nworkers;
501  instrumentation->num_plan_nodes = e.nnodes;
502  instrument = GetInstrumentationArray(instrumentation);
503  for (i = 0; i < nworkers * e.nnodes; ++i)
504  InstrInit(&instrument[i], estate->es_instrument);
506  instrumentation);
507  pei->instrumentation = instrumentation;
508  }
509 
510  /*
511  * Create a DSA area that can be used by the leader and all workers.
512  * (However, if we failed to create a DSM and are using private memory
513  * instead, then skip this.)
514  */
515  if (pcxt->seg != NULL)
516  {
517  char *area_space;
518 
519  area_space = shm_toc_allocate(pcxt->toc, dsa_minsize);
520  shm_toc_insert(pcxt->toc, PARALLEL_KEY_DSA, area_space);
521  pei->area = dsa_create_in_place(area_space, dsa_minsize,
523  pcxt->seg);
524  }
525 
526  /*
527  * Make the area available to executor nodes running in the leader. See
528  * also ParallelQueryMain which makes it available to workers.
529  */
530  estate->es_query_dsa = pei->area;
531 
532  /*
533  * Give parallel-aware nodes a chance to initialize their shared data.
534  * This also initializes the elements of instrumentation->ps_instrument,
535  * if it exists.
536  */
537  d.pcxt = pcxt;
538  d.instrumentation = instrumentation;
539  d.nnodes = 0;
540  ExecParallelInitializeDSM(planstate, &d);
541 
542  /*
543  * Make sure that the world hasn't shifted under our feat. This could
544  * probably just be an Assert(), but let's be conservative for now.
545  */
546  if (e.nnodes != d.nnodes)
547  elog(ERROR, "inconsistent count of PlanState nodes");
548 
549  /* OK, we're ready to rock and roll. */
550  return pei;
551 }
552 
553 /*
554  * Copy instrumentation information about this node and its descendants from
555  * dynamic shared memory.
556  */
557 static bool
559  SharedExecutorInstrumentation *instrumentation)
560 {
561  Instrumentation *instrument;
562  int i;
563  int n;
564  int ibytes;
565  int plan_node_id = planstate->plan->plan_node_id;
566  MemoryContext oldcontext;
567 
568  /* Find the instrumentation for this node. */
569  for (i = 0; i < instrumentation->num_plan_nodes; ++i)
570  if (instrumentation->plan_node_id[i] == plan_node_id)
571  break;
572  if (i >= instrumentation->num_plan_nodes)
573  elog(ERROR, "plan node %d not found", plan_node_id);
574 
575  /* Accumulate the statistics from all workers. */
576  instrument = GetInstrumentationArray(instrumentation);
577  instrument += i * instrumentation->num_workers;
578  for (n = 0; n < instrumentation->num_workers; ++n)
579  InstrAggNode(planstate->instrument, &instrument[n]);
580 
581  /*
582  * Also store the per-worker detail.
583  *
584  * Worker instrumentation should be allocated in the same context as
585  * the regular instrumentation information, which is the per-query
586  * context. Switch into per-query memory context.
587  */
588  oldcontext = MemoryContextSwitchTo(planstate->state->es_query_cxt);
589  ibytes = mul_size(instrumentation->num_workers, sizeof(Instrumentation));
590  planstate->worker_instrument =
591  palloc(ibytes + offsetof(WorkerInstrumentation, instrument));
592  MemoryContextSwitchTo(oldcontext);
593 
594  planstate->worker_instrument->num_workers = instrumentation->num_workers;
595  memcpy(&planstate->worker_instrument->instrument, instrument, ibytes);
596 
598  instrumentation);
599 }
600 
601 /*
602  * Finish parallel execution. We wait for parallel workers to finish, and
603  * accumulate their buffer usage and instrumentation.
604  */
605 void
607 {
608  int i;
609 
610  if (pei->finished)
611  return;
612 
613  /* First, wait for the workers to finish. */
615 
616  /* Next, accumulate buffer usage. */
617  for (i = 0; i < pei->pcxt->nworkers_launched; ++i)
619 
620  /* Finally, accumulate instrumentation, if any. */
621  if (pei->instrumentation)
623  pei->instrumentation);
624 
625  pei->finished = true;
626 }
627 
628 /*
629  * Clean up whatever ParallelExecutorInfo resources still exist after
630  * ExecParallelFinish. We separate these routines because someone might
631  * want to examine the contents of the DSM after ExecParallelFinish and
632  * before calling this routine.
633  */
634 void
636 {
637  if (pei->area != NULL)
638  {
639  dsa_detach(pei->area);
640  pei->area = NULL;
641  }
642  if (pei->pcxt != NULL)
643  {
645  pei->pcxt = NULL;
646  }
647  pfree(pei);
648 }
649 
650 /*
651  * Create a DestReceiver to write tuples we produce to the shm_mq designated
652  * for that purpose.
653  */
654 static DestReceiver *
656 {
657  char *mqspace;
658  shm_mq *mq;
659 
662  mq = (shm_mq *) mqspace;
665 }
666 
667 /*
668  * Create a QueryDesc for the PlannedStmt we are to execute, and return it.
669  */
670 static QueryDesc *
672  int instrument_options)
673 {
674  char *pstmtspace;
675  char *paramspace;
676  PlannedStmt *pstmt;
677  ParamListInfo paramLI;
678  char *queryString;
679 
680  /* Get the query string from shared memory */
681  queryString = shm_toc_lookup(toc, PARALLEL_KEY_QUERY_TEXT);
682 
683  /* Reconstruct leader-supplied PlannedStmt. */
684  pstmtspace = shm_toc_lookup(toc, PARALLEL_KEY_PLANNEDSTMT);
685  pstmt = (PlannedStmt *) stringToNode(pstmtspace);
686 
687  /* Reconstruct ParamListInfo. */
688  paramspace = shm_toc_lookup(toc, PARALLEL_KEY_PARAMS);
689  paramLI = RestoreParamList(&paramspace);
690 
691  /*
692  * Create a QueryDesc for the query.
693  *
694  * It's not obvious how to obtain the query string from here; and even if
695  * we could copying it would take more cycles than not copying it. But
696  * it's a bit unsatisfying to just use a dummy string here, so consider
697  * revising this someday.
698  */
699  return CreateQueryDesc(pstmt,
700  queryString,
702  receiver, paramLI, instrument_options);
703 }
704 
705 /*
706  * Copy instrumentation information from this node and its descendants into
707  * dynamic shared memory, so that the parallel leader can retrieve it.
708  */
709 static bool
711  SharedExecutorInstrumentation *instrumentation)
712 {
713  int i;
714  int plan_node_id = planstate->plan->plan_node_id;
715  Instrumentation *instrument;
716 
717  InstrEndLoop(planstate->instrument);
718 
719  /*
720  * If we shuffled the plan_node_id values in ps_instrument into sorted
721  * order, we could use binary search here. This might matter someday if
722  * we're pushing down sufficiently large plan trees. For now, do it the
723  * slow, dumb way.
724  */
725  for (i = 0; i < instrumentation->num_plan_nodes; ++i)
726  if (instrumentation->plan_node_id[i] == plan_node_id)
727  break;
728  if (i >= instrumentation->num_plan_nodes)
729  elog(ERROR, "plan node %d not found", plan_node_id);
730 
731  /*
732  * Add our statistics to the per-node, per-worker totals. It's possible
733  * that this could happen more than once if we relaunched workers.
734  */
735  instrument = GetInstrumentationArray(instrumentation);
736  instrument += i * instrumentation->num_workers;
738  Assert(ParallelWorkerNumber < instrumentation->num_workers);
739  InstrAggNode(&instrument[ParallelWorkerNumber], planstate->instrument);
740 
742  instrumentation);
743 }
744 
745 /*
746  * Initialize the PlanState and its descendants with the information
747  * retrieved from shared memory. This has to be done once the PlanState
748  * is allocated and initialized by executor; that is, after ExecutorStart().
749  */
750 static bool
752 {
753  if (planstate == NULL)
754  return false;
755 
756  /* Call initializers for parallel-aware plan nodes. */
757  if (planstate->plan->parallel_aware)
758  {
759  switch (nodeTag(planstate))
760  {
761  case T_SeqScanState:
762  ExecSeqScanInitializeWorker((SeqScanState *) planstate, toc);
763  break;
764  case T_IndexScanState:
765  ExecIndexScanInitializeWorker((IndexScanState *) planstate, toc);
766  break;
769  break;
770  case T_ForeignScanState:
772  toc);
773  break;
774  case T_CustomScanState:
776  toc);
777  break;
778  default:
779  break;
780  }
781  }
782 
783  return planstate_tree_walker(planstate, ExecParallelInitializeWorker, toc);
784 }
785 
786 /*
787  * Main entrypoint for parallel query worker processes.
788  *
789  * We reach this function from ParallelWorkerMain, so the setup necessary to
790  * create a sensible parallel environment has already been done;
791  * ParallelWorkerMain worries about stuff like the transaction state, combo
792  * CID mappings, and GUC values, so we don't need to deal with any of that
793  * here.
794  *
795  * Our job is to deal with concerns specific to the executor. The parallel
796  * group leader will have stored a serialized PlannedStmt, and it's our job
797  * to execute that plan and write the resulting tuples to the appropriate
798  * tuple queue. Various bits of supporting information that we need in order
799  * to do this are also stored in the dsm_segment and can be accessed through
800  * the shm_toc.
801  */
802 static void
804 {
805  BufferUsage *buffer_usage;
806  DestReceiver *receiver;
807  QueryDesc *queryDesc;
808  SharedExecutorInstrumentation *instrumentation;
809  int instrument_options = 0;
810  void *area_space;
811  dsa_area *area;
812 
813  /* Set up DestReceiver, SharedExecutorInstrumentation, and QueryDesc. */
814  receiver = ExecParallelGetReceiver(seg, toc);
815  instrumentation = shm_toc_lookup(toc, PARALLEL_KEY_INSTRUMENTATION);
816  if (instrumentation != NULL)
817  instrument_options = instrumentation->instrument_options;
818  queryDesc = ExecParallelGetQueryDesc(toc, receiver, instrument_options);
819 
820  /* Setting debug_query_string for individual workers */
821  debug_query_string = queryDesc->sourceText;
822 
823  /* Report workers' query for monitoring purposes */
825 
826  /* Prepare to track buffer usage during query execution. */
828 
829  /* Attach to the dynamic shared memory area. */
830  area_space = shm_toc_lookup(toc, PARALLEL_KEY_DSA);
831  area = dsa_attach_in_place(area_space, seg);
832 
833  /* Start up the executor */
834  ExecutorStart(queryDesc, 0);
835 
836  /* Special executor initialization steps for parallel workers */
837  queryDesc->planstate->state->es_query_dsa = area;
838  ExecParallelInitializeWorker(queryDesc->planstate, toc);
839 
840  /* Run the plan */
841  ExecutorRun(queryDesc, ForwardScanDirection, 0L);
842 
843  /* Shut down the executor */
844  ExecutorFinish(queryDesc);
845 
846  /* Report buffer usage during parallel execution. */
847  buffer_usage = shm_toc_lookup(toc, PARALLEL_KEY_BUFFER_USAGE);
849 
850  /* Report instrumentation data if any instrumentation options are set. */
851  if (instrumentation != NULL)
853  instrumentation);
854 
855  /* Must do this after capturing instrumentation. */
856  ExecutorEnd(queryDesc);
857 
858  /* Cleanup. */
859  dsa_detach(area);
860  FreeQueryDesc(queryDesc);
861  (*receiver->rDestroy) (receiver);
862 }
void ExecIndexScanInitializeWorker(IndexScanState *node, shm_toc *toc)
bool dependsOnRole
Definition: plannodes.h:57
void ExecSeqScanInitializeWorker(SeqScanState *node, shm_toc *toc)
Definition: nodeSeqscan.c:335
#define NIL
Definition: pg_list.h:69
void ExecIndexScanInitializeDSM(IndexScanState *node, ParallelContext *pcxt)
struct dsa_area * es_query_dsa
Definition: execnodes.h:437
void * stringToNode(char *str)
Definition: read.c:38
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:126
ParallelContext * pcxt
Definition: execParallel.h:27
uint32 queryId
Definition: plannodes.h:47
WorkerInstrumentation * worker_instrument
Definition: execnodes.h:1054
struct ExecParallelEstimateContext ExecParallelEstimateContext
int plan_node_id[FLEXIBLE_ARRAY_MEMBER]
Definition: execParallel.c:81
Instrumentation * instrument
Definition: execnodes.h:1053
void ExecIndexOnlyScanInitializeWorker(IndexOnlyScanState *node, shm_toc *toc)
void ExecParallelFinish(ParallelExecutorInfo *pei)
Definition: execParallel.c:606
#define PARALLEL_KEY_TUPLE_QUEUE
Definition: execParallel.c:52
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:100
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2805
static void ParallelQueryMain(dsm_segment *seg, shm_toc *toc)
Definition: execParallel.c:803
PGPROC * MyProc
Definition: proc.c:67
void InstrAggNode(Instrumentation *dst, Instrumentation *add)
Definition: instrument.c:143
dsm_segment * seg
Definition: parallel.h:43
static bool ExecParallelReportInstrumentation(PlanState *planstate, SharedExecutorInstrumentation *instrumentation)
Definition: execParallel.c:710
void ExecCustomScanInitializeWorker(CustomScanState *node, shm_toc *toc)
Definition: nodeCustom.c:192
List * relationOids
Definition: plannodes.h:74
shm_toc_estimator estimator
Definition: parallel.h:42
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:138
dsa_area * dsa_attach_in_place(void *place, dsm_segment *segment)
Definition: dsa.c:540
int plan_node_id
Definition: plannodes.h:128
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:834
PlannedStmt * es_plannedstmt
Definition: execnodes.h:373
PlanState * planstate
Definition: execParallel.h:26
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count)
Definition: execMain.c:285
void InstrEndParallelQuery(BufferUsage *result)
Definition: instrument.c:177
static char * ExecSerializePlan(Plan *plan, EState *estate)
Definition: execParallel.c:122
ParallelExecutorInfo * ExecInitParallelPlan(PlanState *planstate, EState *estate, int nworkers)
Definition: execParallel.c:357
QueryDesc * CreateQueryDesc(PlannedStmt *plannedstmt, const char *sourceText, Snapshot snapshot, Snapshot crosscheck_snapshot, DestReceiver *dest, ParamListInfo params, int instrument_options)
Definition: pquery.c:66
static shm_mq_handle ** ExecParallelSetupTupleQueues(ParallelContext *pcxt, bool reinitialize)
Definition: execParallel.c:293
EState * state
Definition: execnodes.h:1049
List * es_range_table
Definition: execnodes.h:372
#define shm_toc_estimate_chunk(e, sz)
Definition: shm_toc.h:49
bool transientPlan
Definition: plannodes.h:55
Size EstimateParamListSpace(ParamListInfo paramLI)
Definition: params.c:95
int stmt_len
Definition: plannodes.h:84
struct Plan * planTree
Definition: plannodes.h:61
List * invalItems
Definition: plannodes.h:76
void * copyObject(const void *from)
Definition: copyfuncs.c:4475
void InstrEndLoop(Instrumentation *instr)
Definition: instrument.c:114
SharedExecutorInstrumentation * instrumentation
Definition: execParallel.c:99
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:439
ParallelContext * pcxt
Definition: execParallel.c:91
void WaitForParallelWorkersToFinish(ParallelContext *pcxt)
Definition: parallel.c:519
#define PARALLEL_KEY_INSTRUMENTATION
Definition: execParallel.c:53
void DestroyParallelContext(ParallelContext *pcxt)
Definition: parallel.c:609
const char * es_sourceText
Definition: execnodes.h:374
int nParamExec
Definition: plannodes.h:78
void pfree(void *pointer)
Definition: mcxt.c:992
MemoryContext es_query_cxt
Definition: execnodes.h:397
void ExecSeqScanInitializeDSM(SeqScanState *node, ParallelContext *pcxt)
Definition: nodeSeqscan.c:313
static bool ExecParallelInitializeDSM(PlanState *node, ExecParallelInitializeDSMContext *d)
Definition: execParallel.c:233
bool resjunk
Definition: primnodes.h:1337
#define ERROR
Definition: elog.h:43
PlanState * planstate
Definition: execdesc.h:48
BufferUsage * buffer_usage
Definition: execParallel.h:28
void ExecIndexOnlyScanEstimate(IndexOnlyScanState *node, ParallelContext *pcxt)
shm_mq * shm_mq_create(void *address, Size size)
Definition: shm_mq.c:167
#define PARALLEL_KEY_PLANNEDSTMT
Definition: execParallel.c:49
ParamListInfo RestoreParamList(char **start_address)
Definition: params.c:224
int stmt_location
Definition: plannodes.h:83
void * shm_toc_lookup(shm_toc *toc, uint64 key)
Definition: shm_toc.c:218
static bool ExecParallelRetrieveInstrumentation(PlanState *planstate, SharedExecutorInstrumentation *instrumentation)
Definition: execParallel.c:558
bool hasReturning
Definition: plannodes.h:49
struct ExecParallelInitializeDSMContext ExecParallelInitializeDSMContext
void dsa_detach(dsa_area *area)
Definition: dsa.c:1875
void ExecForeignScanInitializeWorker(ForeignScanState *node, shm_toc *toc)
Node * utilityStmt
Definition: plannodes.h:80
int ParallelWorkerNumber
Definition: parallel.c:96
static bool ExecParallelInitializeWorker(PlanState *planstate, shm_toc *toc)
Definition: execParallel.c:751
bool parallel_aware
Definition: plannodes.h:123
#define PARALLEL_TUPLE_QUEUE_SIZE
Definition: execParallel.c:57
void InstrAccumParallelQuery(BufferUsage *result)
Definition: instrument.c:185
int es_instrument
Definition: execnodes.h:407
int nworkers_launched
Definition: parallel.h:37
static bool ExecParallelEstimate(PlanState *node, ExecParallelEstimateContext *e)
Definition: execParallel.c:187
dsa_area * dsa_create_in_place(void *place, size_t size, int tranche_id, dsm_segment *segment)
Definition: dsa.c:468
void shm_mq_set_sender(shm_mq *mq, PGPROC *proc)
Definition: shm_mq.c:215
#define PARALLEL_KEY_BUFFER_USAGE
Definition: execParallel.c:51
#define IsParallelWorker()
Definition: parallel.h:53
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:379
#define PARALLEL_KEY_PARAMS
Definition: execParallel.c:50
const char * debug_query_string
Definition: postgres.c:83
void InitializeParallelDSM(ParallelContext *pcxt)
Definition: parallel.c:200
#define InvalidSnapshot
Definition: snapshot.h:25
void InstrStartParallelQuery(void)
Definition: instrument.c:170
void InstrInit(Instrumentation *instr, int instrument_options)
Definition: instrument.c:54
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
bool canSetTag
Definition: plannodes.h:53
Instrumentation instrument[FLEXIBLE_ARRAY_MEMBER]
Definition: instrument.h:69
void * palloc0(Size size)
Definition: mcxt.c:920
CmdType commandType
Definition: plannodes.h:45
void ExecForeignScanInitializeDSM(ForeignScanState *node, ParallelContext *pcxt)
void ReinitializeParallelDSM(ParallelContext *pcxt)
Definition: parallel.c:396
List * rowMarks
Definition: plannodes.h:72
Plan * plan
Definition: execnodes.h:1047
void ExecParallelReinitialize(ParallelExecutorInfo *pei)
Definition: execParallel.c:345
void ExecCustomScanInitializeDSM(CustomScanState *node, ParallelContext *pcxt)
Definition: nodeCustom.c:176
Size dsa_minimum_size(void)
Definition: dsa.c:1160
#define makeNode(_type_)
Definition: nodes.h:556
void ExecParallelCleanup(ParallelExecutorInfo *pei)
Definition: execParallel.c:635
List * subplans
Definition: plannodes.h:68
#define NULL
Definition: c.h:226
void SerializeParamList(ParamListInfo paramLI, char **start_address)
Definition: params.c:158
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
Bitmapset * rewindPlanIDs
Definition: plannodes.h:70
bool hasModifyingCTE
Definition: plannodes.h:51
void ExecForeignScanEstimate(ForeignScanState *node, ParallelContext *pcxt)
size_t Size
Definition: c.h:353
void ExecSeqScanEstimate(SeqScanState *node, ParallelContext *pcxt)
Definition: nodeSeqscan.c:296
#define shm_toc_estimate_keys(e, cnt)
Definition: shm_toc.h:52
#define MAXALIGN(LEN)
Definition: c.h:584
List * rtable
Definition: plannodes.h:63
void * shm_toc_allocate(shm_toc *toc, Size nbytes)
Definition: shm_toc.c:83
#define nodeTag(nodeptr)
Definition: nodes.h:513
shm_mq_handle * shm_mq_attach(shm_mq *mq, dsm_segment *seg, BackgroundWorkerHandle *handle)
Definition: shm_mq.c:284
List * targetlist
Definition: plannodes.h:129
const char * sourceText
Definition: execdesc.h:38
#define PARALLEL_KEY_DSA
Definition: execParallel.c:54
e
Definition: preproc-init.c:82
Definition: dsa.c:354
void shm_toc_insert(shm_toc *toc, uint64 key, void *address)
Definition: shm_toc.c:161
void * palloc(Size size)
Definition: mcxt.c:891
List * resultRelations
Definition: plannodes.h:66
bool parallelModeNeeded
Definition: plannodes.h:59
int i
#define PARALLEL_KEY_QUERY_TEXT
Definition: execParallel.c:55
Definition: shm_mq.c:69
char * nodeToString(const void *obj)
Definition: outfuncs.c:3981
void ExecCustomScanEstimate(CustomScanState *node, ParallelContext *pcxt)
Definition: nodeCustom.c:163
ParamListInfo es_param_list_info
Definition: execnodes.h:393
void ExecIndexOnlyScanInitializeDSM(IndexOnlyScanState *node, ParallelContext *pcxt)
shm_mq_handle ** tqueue
Definition: execParallel.h:30
static DestReceiver * ExecParallelGetReceiver(dsm_segment *seg, shm_toc *toc)
Definition: execParallel.c:655
void shm_mq_set_receiver(shm_mq *mq, PGPROC *proc)
Definition: shm_mq.c:196
ParallelContext * CreateParallelContext(parallel_worker_main_type entrypoint, int nworkers)
Definition: parallel.c:123
#define elog
Definition: elog.h:219
DestReceiver * CreateTupleQueueDestReceiver(shm_mq_handle *handle)
Definition: tqueue.c:606
void ExecIndexScanEstimate(IndexScanState *node, ParallelContext *pcxt)
SharedExecutorInstrumentation * instrumentation
Definition: execParallel.h:29
bool planstate_tree_walker(PlanState *planstate, bool(*walker)(), void *context)
Definition: nodeFuncs.c:3639
static QueryDesc * ExecParallelGetQueryDesc(shm_toc *toc, DestReceiver *receiver, int instrument_options)
Definition: execParallel.c:671
#define offsetof(type, field)
Definition: c.h:551
#define GetInstrumentationArray(sei)
Definition: execParallel.c:84
shm_toc * toc
Definition: parallel.h:45