-
Notifications
You must be signed in to change notification settings - Fork 35
/
pg_wait_sampling.c
1200 lines (1040 loc) · 30.6 KB
/
pg_wait_sampling.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* pg_wait_sampling.c
* Track information about wait events.
*
* Copyright (c) 2015-2017, Postgres Professional
*
* IDENTIFICATION
* contrib/pg_wait_sampling/pg_wait_sampling.c
*/
#include "postgres.h"
#include "access/htup_details.h"
#include "access/twophase.h"
#include "catalog/pg_type.h"
#include "fmgr.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "optimizer/planner.h"
#include "pgstat.h"
#include "postmaster/autovacuum.h"
#include "replication/walsender.h"
#include "storage/ipc.h"
#include "storage/pg_shmem.h"
#include "storage/procarray.h"
#include "storage/shm_mq.h"
#include "storage/shm_toc.h"
#include "storage/spin.h"
#include "tcop/utility.h"
#include "utils/builtins.h"
#include "utils/datetime.h"
#include "utils/guc_tables.h"
#include "utils/guc.h"
#include "utils/memutils.h" /* TopMemoryContext. Actually for PG 9.6 only,
* but there should be no harm for others. */
#include "compat.h"
#include "pg_wait_sampling.h"
PG_MODULE_MAGIC;
void _PG_init(void);
static bool shmem_initialized = false;
/* Hooks */
static ExecutorStart_hook_type prev_ExecutorStart = NULL;
static ExecutorRun_hook_type prev_ExecutorRun = NULL;
static ExecutorFinish_hook_type prev_ExecutorFinish = NULL;
static ExecutorEnd_hook_type prev_ExecutorEnd = NULL;
static planner_hook_type planner_hook_next = NULL;
static ProcessUtility_hook_type prev_ProcessUtility = NULL;
/* Current nesting depth of planner/Executor calls */
static int nesting_level = 0;
/* Pointers to shared memory objects */
shm_mq *pgws_collector_mq = NULL;
uint64 *pgws_proc_queryids = NULL;
CollectorShmqHeader *pgws_collector_hdr = NULL;
/* Receiver (backend) local shm_mq pointers and lock */
static shm_mq *recv_mq = NULL;
static shm_mq_handle *recv_mqh = NULL;
static LOCKTAG queueTag;
#if PG_VERSION_NUM >= 150000
static shmem_request_hook_type prev_shmem_request_hook = NULL;
#endif
static shmem_startup_hook_type prev_shmem_startup_hook = NULL;
static PGPROC * search_proc(int backendPid);
static PlannedStmt *pgws_planner_hook(Query *parse,
#if PG_VERSION_NUM >= 130000
const char *query_string,
#endif
int cursorOptions, ParamListInfo boundParams);
static void pgws_ExecutorStart(QueryDesc *queryDesc, int eflags);
static void pgws_ExecutorRun(QueryDesc *queryDesc,
ScanDirection direction,
uint64 count
#if PG_VERSION_NUM >= 100000 && PG_VERSION_NUM < 180000
, bool execute_once
#endif
);
static void pgws_ExecutorFinish(QueryDesc *queryDesc);
static void pgws_ExecutorEnd(QueryDesc *queryDesc);
static void pgws_ProcessUtility(PlannedStmt *pstmt,
const char *queryString,
#if PG_VERSION_NUM >= 140000
bool readOnlyTree,
#endif
ProcessUtilityContext context,
ParamListInfo params,
QueryEnvironment *queryEnv,
DestReceiver *dest,
#if PG_VERSION_NUM >= 130000
QueryCompletion *qc
#else
char *completionTag
#endif
);
/*---- GUC variables ----*/
typedef enum
{
PGWS_PROFILE_QUERIES_NONE, /* profile no statements */
PGWS_PROFILE_QUERIES_TOP, /* only top level statements */
PGWS_PROFILE_QUERIES_ALL /* all statements, including nested ones */
} PGWSTrackLevel;
static const struct config_enum_entry pgws_profile_queries_options[] =
{
{"none", PGWS_PROFILE_QUERIES_NONE, false},
{"off", PGWS_PROFILE_QUERIES_NONE, false},
{"no", PGWS_PROFILE_QUERIES_NONE, false},
{"false", PGWS_PROFILE_QUERIES_NONE, false},
{"0", PGWS_PROFILE_QUERIES_NONE, false},
{"top", PGWS_PROFILE_QUERIES_TOP, false},
{"on", PGWS_PROFILE_QUERIES_TOP, false},
{"yes", PGWS_PROFILE_QUERIES_TOP, false},
{"true", PGWS_PROFILE_QUERIES_TOP, false},
{"1", PGWS_PROFILE_QUERIES_TOP, false},
{"all", PGWS_PROFILE_QUERIES_ALL, false},
{NULL, 0, false}
};
#define pgws_enabled(level) \
((pgws_collector_hdr->profileQueries == PGWS_PROFILE_QUERIES_ALL) || \
(pgws_collector_hdr->profileQueries == PGWS_PROFILE_QUERIES_TOP && (level) == 0))
/*
* Calculate max processes count.
*
* The value has to be in sync with ProcGlobal->allProcCount, initialized in
* InitProcGlobal() (proc.c).
*
*/
static int
get_max_procs_count(void)
{
int count = 0;
/* First, add the maximum number of backends (MaxBackends). */
#if PG_VERSION_NUM >= 150000
/*
* On pg15+, we can directly access the MaxBackends variable, as it will
* have already been initialized in shmem_request_hook.
*/
Assert(MaxBackends > 0);
count += MaxBackends;
#else
/*
* On older versions, we need to compute MaxBackends: bgworkers, autovacuum
* workers and launcher.
* This has to be in sync with the value computed in
* InitializeMaxBackends() (postinit.c)
*
* Note that we need to calculate the value as it won't initialized when we
* need it during _PG_init().
*
* Note also that the value returned during _PG_init() might be different
* from the value returned later if some third-party modules change one of
* the underlying GUC. This isn't ideal but can't lead to a crash, as the
* value returned during _PG_init() is only used to ask for additional
* shmem with RequestAddinShmemSpace(), and postgres has an extra 100kB of
* shmem to compensate some small unaccounted usage. So if the value later
* changes, we will allocate and initialize the new (and correct) memory
* size, which will either work thanks for the extra 100kB of shmem, of
* fail (and prevent postgres startup) due to an out of shared memory
* error.
*/
count += MaxConnections + autovacuum_max_workers + 1
+ max_worker_processes;
/*
* Starting with pg12, wal senders aren't part of MaxConnections anymore
* and have to be accounted for.
*/
count += max_wal_senders;
#endif /* pg 15- */
/* End of MaxBackends calculation. */
/* Add AuxiliaryProcs */
count += NUM_AUXILIARY_PROCS;
return count;
}
/*
* Estimate amount of shared memory needed.
*/
static Size
pgws_shmem_size(void)
{
shm_toc_estimator e;
Size size;
int nkeys;
shm_toc_initialize_estimator(&e);
nkeys = 3;
shm_toc_estimate_chunk(&e, sizeof(CollectorShmqHeader));
shm_toc_estimate_chunk(&e, (Size) COLLECTOR_QUEUE_SIZE);
shm_toc_estimate_chunk(&e, sizeof(uint64) * get_max_procs_count());
shm_toc_estimate_keys(&e, nkeys);
size = shm_toc_estimate(&e);
return size;
}
static bool
shmem_int_guc_check_hook(int *newval, void **extra, GucSource source)
{
if (UsedShmemSegAddr == NULL)
return false;
return true;
}
static bool
shmem_enum_guc_check_hook(int *newval, void **extra, GucSource source)
{
if (UsedShmemSegAddr == NULL)
return false;
return true;
}
static bool
shmem_bool_guc_check_hook(bool *newval, void **extra, GucSource source)
{
if (UsedShmemSegAddr == NULL)
return false;
return true;
}
/*
* This union allows us to mix the numerous different types of structs
* that we are organizing.
*/
typedef union
{
struct config_generic generic;
struct config_bool _bool;
struct config_real real;
struct config_int integer;
struct config_string string;
struct config_enum _enum;
} mixedStruct;
/*
* Setup new GUCs or modify existsing.
*/
static void
setup_gucs()
{
struct config_generic **guc_vars;
int numOpts,
i;
bool history_size_found = false,
history_period_found = false,
profile_period_found = false,
profile_pid_found = false,
profile_queries_found = false,
sample_cpu_found = false;
get_guc_variables_compat(&guc_vars, &numOpts);
for (i = 0; i < numOpts; i++)
{
mixedStruct *var = (mixedStruct *) guc_vars[i];
const char *name = var->generic.name;
if (var->generic.flags & GUC_CUSTOM_PLACEHOLDER)
continue;
if (!strcmp(name, "pg_wait_sampling.history_size"))
{
history_size_found = true;
var->integer.variable = &pgws_collector_hdr->historySize;
pgws_collector_hdr->historySize = 5000;
}
else if (!strcmp(name, "pg_wait_sampling.history_period"))
{
history_period_found = true;
var->integer.variable = &pgws_collector_hdr->historyPeriod;
pgws_collector_hdr->historyPeriod = 10;
}
else if (!strcmp(name, "pg_wait_sampling.profile_period"))
{
profile_period_found = true;
var->integer.variable = &pgws_collector_hdr->profilePeriod;
pgws_collector_hdr->profilePeriod = 10;
}
else if (!strcmp(name, "pg_wait_sampling.profile_pid"))
{
profile_pid_found = true;
var->_bool.variable = &pgws_collector_hdr->profilePid;
pgws_collector_hdr->profilePid = true;
}
else if (!strcmp(name, "pg_wait_sampling.profile_queries"))
{
profile_queries_found = true;
var->_enum.variable = &pgws_collector_hdr->profileQueries;
pgws_collector_hdr->profileQueries = PGWS_PROFILE_QUERIES_TOP;
}
else if (!strcmp(name, "pg_wait_sampling.sample_cpu"))
{
sample_cpu_found = true;
var->_bool.variable = &pgws_collector_hdr->sampleCpu;
pgws_collector_hdr->sampleCpu = true;
}
}
if (!history_size_found)
DefineCustomIntVariable("pg_wait_sampling.history_size",
"Sets size of waits history.", NULL,
&pgws_collector_hdr->historySize, 5000, 100, INT_MAX,
PGC_SUSET, 0, shmem_int_guc_check_hook, NULL, NULL);
if (!history_period_found)
DefineCustomIntVariable("pg_wait_sampling.history_period",
"Sets period of waits history sampling.", NULL,
&pgws_collector_hdr->historyPeriod, 10, 1, INT_MAX,
PGC_SUSET, 0, shmem_int_guc_check_hook, NULL, NULL);
if (!profile_period_found)
DefineCustomIntVariable("pg_wait_sampling.profile_period",
"Sets period of waits profile sampling.", NULL,
&pgws_collector_hdr->profilePeriod, 10, 1, INT_MAX,
PGC_SUSET, 0, shmem_int_guc_check_hook, NULL, NULL);
if (!profile_pid_found)
DefineCustomBoolVariable("pg_wait_sampling.profile_pid",
"Sets whether profile should be collected per pid.", NULL,
&pgws_collector_hdr->profilePid, true,
PGC_SUSET, 0, shmem_bool_guc_check_hook, NULL, NULL);
if (!profile_queries_found)
DefineCustomEnumVariable("pg_wait_sampling.profile_queries",
"Sets whether profile should be collected per query.", NULL,
&pgws_collector_hdr->profileQueries, PGWS_PROFILE_QUERIES_TOP, pgws_profile_queries_options,
PGC_SUSET, 0, shmem_enum_guc_check_hook, NULL, NULL);
if (!sample_cpu_found)
DefineCustomBoolVariable("pg_wait_sampling.sample_cpu",
"Sets whether not waiting backends should be sampled.", NULL,
&pgws_collector_hdr->sampleCpu, true,
PGC_SUSET, 0, shmem_bool_guc_check_hook, NULL, NULL);
if (history_size_found
|| history_period_found
|| profile_period_found
|| profile_pid_found
|| profile_queries_found
|| sample_cpu_found)
{
ProcessConfigFile(PGC_SIGHUP);
}
}
#if PG_VERSION_NUM >= 150000
/*
* shmem_request hook: request additional shared memory resources.
*
* If you change code here, don't forget to also report the modifications in
* _PG_init() for pg14 and below.
*/
static void
pgws_shmem_request(void)
{
if (prev_shmem_request_hook)
prev_shmem_request_hook();
RequestAddinShmemSpace(pgws_shmem_size());
}
#endif
/*
* Distribute shared memory.
*/
static void
pgws_shmem_startup(void)
{
bool found;
Size segsize = pgws_shmem_size();
void *pgws;
shm_toc *toc;
pgws = ShmemInitStruct("pg_wait_sampling", segsize, &found);
if (!found)
{
toc = shm_toc_create(PG_WAIT_SAMPLING_MAGIC, pgws, segsize);
pgws_collector_hdr = shm_toc_allocate(toc, sizeof(CollectorShmqHeader));
shm_toc_insert(toc, 0, pgws_collector_hdr);
/* needed to please check_GUC_init */
pgws_collector_hdr->profileQueries = PGWS_PROFILE_QUERIES_TOP;
pgws_collector_mq = shm_toc_allocate(toc, COLLECTOR_QUEUE_SIZE);
shm_toc_insert(toc, 1, pgws_collector_mq);
pgws_proc_queryids = shm_toc_allocate(toc,
sizeof(uint64) * get_max_procs_count());
shm_toc_insert(toc, 2, pgws_proc_queryids);
MemSet(pgws_proc_queryids, 0, sizeof(uint64) * get_max_procs_count());
/* Initialize GUC variables in shared memory */
setup_gucs();
}
else
{
toc = shm_toc_attach(PG_WAIT_SAMPLING_MAGIC, pgws);
pgws_collector_hdr = shm_toc_lookup(toc, 0, false);
pgws_collector_mq = shm_toc_lookup(toc, 1, false);
pgws_proc_queryids = shm_toc_lookup(toc, 2, false);
}
shmem_initialized = true;
if (prev_shmem_startup_hook)
prev_shmem_startup_hook();
}
/*
* Check shared memory is initialized. Report an error otherwise.
*/
static void
check_shmem(void)
{
if (!shmem_initialized)
{
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR),
errmsg("pg_wait_sampling shared memory wasn't initialized yet")));
}
}
static void
pgws_cleanup_callback(int code, Datum arg)
{
elog(DEBUG3, "pg_wait_sampling cleanup: detaching shm_mq and releasing queue lock");
shm_mq_detach(recv_mqh);
LockRelease(&queueTag, ExclusiveLock, false);
}
/*
* Module load callback
*/
void
_PG_init(void)
{
if (!process_shared_preload_libraries_in_progress)
return;
#if PG_VERSION_NUM < 150000
/*
* Request additional shared resources. (These are no-ops if we're not in
* the postmaster process.) We'll allocate or attach to the shared
* resources in pgws_shmem_startup().
*
* If you change code here, don't forget to also report the modifications
* in pgsp_shmem_request() for pg15 and later.
*/
RequestAddinShmemSpace(pgws_shmem_size());
#endif
pgws_register_wait_collector();
/*
* Install hooks.
*/
#if PG_VERSION_NUM >= 150000
prev_shmem_request_hook = shmem_request_hook;
shmem_request_hook = pgws_shmem_request;
#endif
prev_shmem_startup_hook = shmem_startup_hook;
shmem_startup_hook = pgws_shmem_startup;
planner_hook_next = planner_hook;
planner_hook = pgws_planner_hook;
prev_ExecutorStart = ExecutorStart_hook;
ExecutorStart_hook = pgws_ExecutorStart;
prev_ExecutorRun = ExecutorRun_hook;
ExecutorRun_hook = pgws_ExecutorRun;
prev_ExecutorFinish = ExecutorFinish_hook;
ExecutorFinish_hook = pgws_ExecutorFinish;
prev_ExecutorEnd = ExecutorEnd_hook;
ExecutorEnd_hook = pgws_ExecutorEnd;
prev_ProcessUtility = ProcessUtility_hook;
ProcessUtility_hook = pgws_ProcessUtility;
}
/*
* Find PGPROC entry responsible for given pid assuming ProcArrayLock was
* already taken.
*/
static PGPROC *
search_proc(int pid)
{
int i;
if (pid == 0)
return MyProc;
for (i = 0; i < ProcGlobal->allProcCount; i++)
{
PGPROC *proc = &ProcGlobal->allProcs[i];
if (proc->pid && proc->pid == pid)
{
return proc;
}
}
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR),
errmsg("backend with pid=%d not found", pid)));
return NULL;
}
/*
* Decide whether this PGPROC entry should be included in profiles and output
* views.
*/
bool
pgws_should_sample_proc(PGPROC *proc)
{
if (proc->wait_event_info == 0 && !pgws_collector_hdr->sampleCpu)
return false;
/*
* On PostgreSQL versions < 17 the PGPROC->pid field is not reset on
* process exit. This would lead to such processes getting counted for
* null wait events. So instead we make use of DisownLatch() resetting
* owner_pid during ProcKill().
*/
if (proc->pid == 0 || proc->procLatch.owner_pid == 0 || proc->pid == MyProcPid)
return false;
return true;
}
typedef struct
{
HistoryItem *items;
TimestampTz ts;
} WaitCurrentContext;
PG_FUNCTION_INFO_V1(pg_wait_sampling_get_current);
Datum
pg_wait_sampling_get_current(PG_FUNCTION_ARGS)
{
FuncCallContext *funcctx;
WaitCurrentContext *params;
check_shmem();
if (SRF_IS_FIRSTCALL())
{
MemoryContext oldcontext;
TupleDesc tupdesc;
funcctx = SRF_FIRSTCALL_INIT();
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
params = (WaitCurrentContext *)palloc0(sizeof(WaitCurrentContext));
params->ts = GetCurrentTimestamp();
funcctx->user_fctx = params;
tupdesc = CreateTemplateTupleDesc(4);
TupleDescInitEntry(tupdesc, (AttrNumber) 1, "pid",
INT4OID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 2, "type",
TEXTOID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 3, "event",
TEXTOID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 4, "queryid",
INT8OID, -1, 0);
funcctx->tuple_desc = BlessTupleDesc(tupdesc);
LWLockAcquire(ProcArrayLock, LW_SHARED);
if (!PG_ARGISNULL(0))
{
HistoryItem *item;
PGPROC *proc;
proc = search_proc(PG_GETARG_UINT32(0));
params->items = (HistoryItem *) palloc0(sizeof(HistoryItem));
item = ¶ms->items[0];
item->pid = proc->pid;
item->wait_event_info = proc->wait_event_info;
item->queryId = pgws_proc_queryids[proc - ProcGlobal->allProcs];
funcctx->max_calls = 1;
}
else
{
int procCount = ProcGlobal->allProcCount,
i,
j = 0;
params->items = (HistoryItem *) palloc0(sizeof(HistoryItem) * procCount);
for (i = 0; i < procCount; i++)
{
PGPROC *proc = &ProcGlobal->allProcs[i];
if (!pgws_should_sample_proc(proc))
continue;
params->items[j].pid = proc->pid;
params->items[j].wait_event_info = proc->wait_event_info;
params->items[j].queryId = pgws_proc_queryids[i];
j++;
}
funcctx->max_calls = j;
}
LWLockRelease(ProcArrayLock);
MemoryContextSwitchTo(oldcontext);
}
/* stuff done on every call of the function */
funcctx = SRF_PERCALL_SETUP();
params = (WaitCurrentContext *) funcctx->user_fctx;
if (funcctx->call_cntr < funcctx->max_calls)
{
HeapTuple tuple;
Datum values[4];
bool nulls[4];
const char *event_type,
*event;
HistoryItem *item;
item = ¶ms->items[funcctx->call_cntr];
/* Make and return next tuple to caller */
MemSet(values, 0, sizeof(values));
MemSet(nulls, 0, sizeof(nulls));
event_type = pgstat_get_wait_event_type(item->wait_event_info);
event = pgstat_get_wait_event(item->wait_event_info);
values[0] = Int32GetDatum(item->pid);
if (event_type)
values[1] = PointerGetDatum(cstring_to_text(event_type));
else
nulls[1] = true;
if (event)
values[2] = PointerGetDatum(cstring_to_text(event));
else
nulls[2] = true;
values[3] = UInt64GetDatum(item->queryId);
tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
}
else
{
SRF_RETURN_DONE(funcctx);
}
}
typedef struct
{
Size count;
ProfileItem *items;
} Profile;
void
pgws_init_lock_tag(LOCKTAG *tag, uint32 lock)
{
tag->locktag_field1 = PG_WAIT_SAMPLING_MAGIC;
tag->locktag_field2 = lock;
tag->locktag_field3 = 0;
tag->locktag_field4 = 0;
tag->locktag_type = LOCKTAG_USERLOCK;
tag->locktag_lockmethodid = USER_LOCKMETHOD;
}
static void *
receive_array(SHMRequest request, Size item_size, Size *count)
{
LOCKTAG collectorTag;
shm_mq_result res;
Size len,
i;
void *data;
Pointer result,
ptr;
MemoryContext oldctx;
/* Ensure nobody else trying to send request to queue */
pgws_init_lock_tag(&queueTag, PGWS_QUEUE_LOCK);
LockAcquire(&queueTag, ExclusiveLock, false, false);
pgws_init_lock_tag(&collectorTag, PGWS_COLLECTOR_LOCK);
LockAcquire(&collectorTag, ExclusiveLock, false, false);
recv_mq = shm_mq_create(pgws_collector_mq, COLLECTOR_QUEUE_SIZE);
pgws_collector_hdr->request = request;
LockRelease(&collectorTag, ExclusiveLock, false);
if (!pgws_collector_hdr->latch)
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR),
errmsg("pg_wait_sampling collector wasn't started")));
SetLatch(pgws_collector_hdr->latch);
shm_mq_set_receiver(recv_mq, MyProc);
/*
* We switch to TopMemoryContext, so that recv_mqh is allocated there
* and is guaranteed to survive until before_shmem_exit callbacks are
* fired. Anyway, shm_mq_detach() will free handler on its own.
*
* NB: we do not pass `seg` to shm_mq_attach(), so it won't set its own
* callback, i.e. we do not interfere here with shm_mq_detach_callback().
*/
oldctx = MemoryContextSwitchTo(TopMemoryContext);
recv_mqh = shm_mq_attach(recv_mq, NULL, NULL);
MemoryContextSwitchTo(oldctx);
/*
* Now we surely attached to the shm_mq and got collector's attention.
* If anything went wrong (e.g. Ctrl+C received from the client) we have
* to cleanup some things, i.e. detach from the shm_mq, so collector was
* able to continue responding to other requests.
*
* PG_ENSURE_ERROR_CLEANUP() guaranties that cleanup callback will be
* fired for both ERROR and FATAL.
*/
PG_ENSURE_ERROR_CLEANUP(pgws_cleanup_callback, 0);
{
res = shm_mq_receive(recv_mqh, &len, &data, false);
if (res != SHM_MQ_SUCCESS || len != sizeof(*count))
elog(ERROR, "error reading mq");
memcpy(count, data, sizeof(*count));
result = palloc(item_size * (*count));
ptr = result;
for (i = 0; i < *count; i++)
{
res = shm_mq_receive(recv_mqh, &len, &data, false);
if (res != SHM_MQ_SUCCESS || len != item_size)
elog(ERROR, "error reading mq");
memcpy(ptr, data, item_size);
ptr += item_size;
}
}
PG_END_ENSURE_ERROR_CLEANUP(pgws_cleanup_callback, 0);
/* We still have to detach and release lock during normal operation. */
shm_mq_detach(recv_mqh);
LockRelease(&queueTag, ExclusiveLock, false);
return result;
}
PG_FUNCTION_INFO_V1(pg_wait_sampling_get_profile);
Datum
pg_wait_sampling_get_profile(PG_FUNCTION_ARGS)
{
Profile *profile;
FuncCallContext *funcctx;
check_shmem();
if (SRF_IS_FIRSTCALL())
{
MemoryContext oldcontext;
TupleDesc tupdesc;
funcctx = SRF_FIRSTCALL_INIT();
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/* Receive profile from shmq */
profile = (Profile *) palloc0(sizeof(Profile));
profile->items = (ProfileItem *) receive_array(PROFILE_REQUEST,
sizeof(ProfileItem), &profile->count);
funcctx->user_fctx = profile;
funcctx->max_calls = profile->count;
/* Make tuple descriptor */
tupdesc = CreateTemplateTupleDesc(5);
TupleDescInitEntry(tupdesc, (AttrNumber) 1, "pid",
INT4OID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 2, "type",
TEXTOID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 3, "event",
TEXTOID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 4, "queryid",
INT8OID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 5, "count",
INT8OID, -1, 0);
funcctx->tuple_desc = BlessTupleDesc(tupdesc);
MemoryContextSwitchTo(oldcontext);
}
/* stuff done on every call of the function */
funcctx = SRF_PERCALL_SETUP();
profile = (Profile *) funcctx->user_fctx;
if (funcctx->call_cntr < funcctx->max_calls)
{
/* for each row */
Datum values[5];
bool nulls[5];
HeapTuple tuple;
ProfileItem *item;
const char *event_type,
*event;
item = &profile->items[funcctx->call_cntr];
MemSet(values, 0, sizeof(values));
MemSet(nulls, 0, sizeof(nulls));
/* Make and return next tuple to caller */
event_type = pgstat_get_wait_event_type(item->wait_event_info);
event = pgstat_get_wait_event(item->wait_event_info);
values[0] = Int32GetDatum(item->pid);
if (event_type)
values[1] = PointerGetDatum(cstring_to_text(event_type));
else
nulls[1] = true;
if (event)
values[2] = PointerGetDatum(cstring_to_text(event));
else
nulls[2] = true;
if (pgws_collector_hdr->profileQueries)
values[3] = UInt64GetDatum(item->queryId);
else
values[3] = (Datum) 0;
values[4] = UInt64GetDatum(item->count);
tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
}
else
{
/* nothing left */
SRF_RETURN_DONE(funcctx);
}
}
PG_FUNCTION_INFO_V1(pg_wait_sampling_reset_profile);
Datum
pg_wait_sampling_reset_profile(PG_FUNCTION_ARGS)
{
LOCKTAG collectorTag;
check_shmem();
pgws_init_lock_tag(&queueTag, PGWS_QUEUE_LOCK);
LockAcquire(&queueTag, ExclusiveLock, false, false);
pgws_init_lock_tag(&collectorTag, PGWS_COLLECTOR_LOCK);
LockAcquire(&collectorTag, ExclusiveLock, false, false);
pgws_collector_hdr->request = PROFILE_RESET;
LockRelease(&collectorTag, ExclusiveLock, false);
SetLatch(pgws_collector_hdr->latch);
LockRelease(&queueTag, ExclusiveLock, false);
PG_RETURN_VOID();
}
PG_FUNCTION_INFO_V1(pg_wait_sampling_get_history);
Datum
pg_wait_sampling_get_history(PG_FUNCTION_ARGS)
{
History *history;
FuncCallContext *funcctx;
check_shmem();
if (SRF_IS_FIRSTCALL())
{
MemoryContext oldcontext;
TupleDesc tupdesc;
funcctx = SRF_FIRSTCALL_INIT();
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/* Receive history from shmq */
history = (History *) palloc0(sizeof(History));
history->items = (HistoryItem *) receive_array(HISTORY_REQUEST,
sizeof(HistoryItem), &history->count);
funcctx->user_fctx = history;
funcctx->max_calls = history->count;
/* Make tuple descriptor */
tupdesc = CreateTemplateTupleDesc(5);
TupleDescInitEntry(tupdesc, (AttrNumber) 1, "pid",
INT4OID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 2, "sample_ts",
TIMESTAMPTZOID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 3, "type",
TEXTOID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 4, "event",
TEXTOID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 5, "queryid",
INT8OID, -1, 0);
funcctx->tuple_desc = BlessTupleDesc(tupdesc);
MemoryContextSwitchTo(oldcontext);
}
/* stuff done on every call of the function */
funcctx = SRF_PERCALL_SETUP();
history = (History *) funcctx->user_fctx;
if (history->index < history->count)
{
HeapTuple tuple;
HistoryItem *item;
Datum values[5];
bool nulls[5];
const char *event_type,
*event;
item = &history->items[history->index];
/* Make and return next tuple to caller */
MemSet(values, 0, sizeof(values));
MemSet(nulls, 0, sizeof(nulls));
event_type = pgstat_get_wait_event_type(item->wait_event_info);
event = pgstat_get_wait_event(item->wait_event_info);
values[0] = Int32GetDatum(item->pid);
values[1] = TimestampTzGetDatum(item->ts);
if (event_type)
values[2] = PointerGetDatum(cstring_to_text(event_type));
else
nulls[2] = true;
if (event)
values[3] = PointerGetDatum(cstring_to_text(event));
else
nulls[3] = true;
values[4] = UInt64GetDatum(item->queryId);
tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
history->index++;
SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
}
else
{
/* nothing left */
SRF_RETURN_DONE(funcctx);
}
PG_RETURN_VOID();
}
/*
* planner_hook hook, save queryId for collector
*/
static PlannedStmt *
pgws_planner_hook(Query *parse,
#if PG_VERSION_NUM >= 130000
const char *query_string,
#endif
int cursorOptions,
ParamListInfo boundParams)
{
PlannedStmt *result;
int i = MyProc - ProcGlobal->allProcs;
uint64 save_queryId = 0;
if (pgws_enabled(nesting_level))
{
save_queryId = pgws_proc_queryids[i];
pgws_proc_queryids[i] = parse->queryId;
}
nesting_level++;
PG_TRY();
{
/* Invoke original hook if needed */
if (planner_hook_next)
result = planner_hook_next(parse,
#if PG_VERSION_NUM >= 130000
query_string,
#endif
cursorOptions, boundParams);
else
result = standard_planner(parse,