forked from RafiaSabih/pg_mon
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pg_mon.c
1190 lines (1070 loc) · 39.5 KB
/
pg_mon.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_mon.c
*
* Copyright (c) 2010-2019, PostgreSQL Global Development Group
*
* IDENTIFICATION
* contrib/pg_mon/pg_mon.c
* -------------------------------------------------------------------------
*/
#include <postgres.h>
#include <limits.h>
#include <miscadmin.h>
#include "storage/lwlock.h"
#include "storage/ipc.h"
#include "storage/shmem.h"
#include "utils/hsearch.h"
#include "utils/memutils.h"
#include "utils/tuplestore.h"
#include "funcapi.h"
#include "commands/explain.h"
#include "executor/instrument.h"
#include "utils/guc.h"
#include "nodes/plannodes.h"
#if PG_VERSION_NUM >= 130000
#include "common/hashfn.h"
#include "catalog/pg_type_d.h"
#else
#include "utils/hashutils.h"
#include "catalog/pg_type.h"
#endif
#include "mb/pg_wchar.h"
#include "utils/rel.h"
#include "utils/lsyscache.h"
#include "utils/builtins.h"
#include "nodes/plannodes.h"
#include "parser/parsetree.h"
#include "storage/spin.h"
#include "tcop/utility.h"
Datum pg_mon(PG_FUNCTION_ARGS);
Datum pg_mon_reset(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(pg_mon);
PG_FUNCTION_INFO_V1(pg_mon_reset);
PG_MODULE_MAGIC;
/* GUC variables */
static bool CONFIG_PLAN_INFO_IMMEDIATE = false;
static bool CONFIG_PLAN_INFO_DISABLE = false;
static bool CONFIG_LOG_NEW_QUERY = true;
static int MON_HT_SIZE = 5000;
#define MON_COLS 20
#define NUMBUCKETS 30
#define ROWNUMBUCKETS 20
#define MAX_TABLES 30
/*
* Record for a query.
*/
typedef struct mon_rec
{
int64 queryid;
double current_total_time;
double first_tuple_time;
double current_expected_rows;
double current_actual_rows;
bool is_parallel;
bool ModifyTable;
Oid seq_scans[MAX_TABLES];
Oid index_scans[MAX_TABLES];
Oid bitmap_scans[MAX_TABLES];
NameData other_scan;
int NestedLoopJoin ;
int HashJoin;
int MergeJoin;
int64 query_time_buckets[NUMBUCKETS];
int64 query_time_freq[NUMBUCKETS];
int64 actual_row_buckets[ROWNUMBUCKETS];
int64 actual_row_freq[ROWNUMBUCKETS];
int64 est_row_buckets[ROWNUMBUCKETS];
int64 est_row_freq[ROWNUMBUCKETS];
slock_t mutex;
}mon_rec;
/* Current nesting depth of ExecutorRun calls */
static int nesting_level = 0;
extern void _PG_init(void);
/* LWlock to mange the reading and writing the hash table. */
LWLock *mon_lock;
typedef enum AddHist{
QUERY_TIME,
ACTUAL_ROWS,
EST_ROWS
} AddHist;
/* Saved hook values in case of unload */
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 ProcessUtility_hook_type prev_ProcessUtility = NULL;
static void pgmon_ExecutorStart(QueryDesc *queryDesc, int eflags);
static void pgmon_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction,
uint64 count, bool execute_once);
static void pgmon_ExecutorFinish(QueryDesc *queryDesc);
static void pgmon_ExecutorEnd(QueryDesc *queryDesc);
static void pgmon_plan_store(QueryDesc *queryDesc);
static void pgmon_exec_store(QueryDesc *queryDesc);
#if PG_VERSION_NUM < 130000
static void PU_hook(PlannedStmt *pstmt, const char *queryString,
ProcessUtilityContext context, ParamListInfo params,
QueryEnvironment *queryEnv,
DestReceiver *dest, char *completionTag);
#define _PU_HOOK \
static void PU_hook(PlannedStmt *pstmt, const char *queryString,\
ProcessUtilityContext context, ParamListInfo params, \
QueryEnvironment *queryEnv, \
DestReceiver *dest, char *completionTag)
#define _prev_hook \
prev_ProcessUtility(pstmt, queryString, context, params, queryEnv, dest, completionTag)
#define _standard_ProcessUtility \
standard_ProcessUtility(pstmt, queryString, context, params, queryEnv, dest, completionTag)
#elif PG_VERSION_NUM >= 130000 && PG_VERSION_NUM < 140000
static void PU_hook(PlannedStmt *pstmt, const char *queryString,
ProcessUtilityContext context, ParamListInfo params,
QueryEnvironment *queryEnv,
DestReceiver *dest, QueryCompletion *qc);
#define _PU_HOOK \
static void PU_hook(PlannedStmt *pstmt, const char *queryString,\
ProcessUtilityContext context, ParamListInfo params, \
QueryEnvironment *queryEnv, \
DestReceiver *dest, QueryCompletion *qc)
#define _prev_hook \
prev_ProcessUtility(pstmt, queryString, context, params, queryEnv, dest, qc)
#define _standard_ProcessUtility \
standard_ProcessUtility(pstmt, queryString, context, params, queryEnv, dest, qc)
#else
static void PU_hook(PlannedStmt *pstmt, const char *queryString,
bool readOnlyTree,
ProcessUtilityContext context, ParamListInfo params,
QueryEnvironment *queryEnv,
DestReceiver *dest, QueryCompletion *qc);
#define _PU_HOOK \
static void PU_hook(PlannedStmt *pstmt, const char *queryString, bool readOnlyTree, \
ProcessUtilityContext context, ParamListInfo params, \
QueryEnvironment *queryEnv, \
DestReceiver *dest, QueryCompletion *qc)
#define _prev_hook \
prev_ProcessUtility(pstmt, queryString, readOnlyTree, context, params, queryEnv, dest, qc)
#define _standard_ProcessUtility \
standard_ProcessUtility(pstmt, queryString, readOnlyTree, context, params, queryEnv, dest, qc)
#endif
/* Saved hook values in case of unload */
#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 void shmem_shutdown(int code, Datum arg);
static void plan_tree_traversal(QueryDesc *query, Plan *plan, mon_rec *entry);
static void update_histogram(volatile mon_rec *entry, AddHist);
static void pg_mon_reset_internal(void);
static mon_rec * create_or_get_entry(mon_rec temp_entry, int64 queryId, QueryDesc *queryDesc);
static void scan_info(Plan *subplan, mon_rec *entry, QueryDesc *queryDesc);
static const char * scan_string(NodeTag type);
/* Hash table in the shared memory */
static HTAB *mon_ht;
/* Bucket boundaries for the histogram in ms, from 5 ms to 1 minute */
static int64 bucket_bounds[NUMBUCKETS] = {
1, 5, 10, 15, 20, 25, 30, 40, 50, 60, 70, 80,
90, 100, 200, 300, 400, 500, 600, 700, 1000,
2000, 3000, 5000, 7000, 10000, 20000, 30000,
50000, 60000
};
static int64 row_bucket_bounds[ROWNUMBUCKETS] = {
1, 5, 10, 50, 100, 200, 300, 400, 500,
1000, 2000, 3000, 4000, 5000, 10000,
30000, 50000, 70000, 100000, 1000000
};
/*
* Keep a temporary record to store the plan information of the
* current query
*/
static mon_rec temp_entry;
/*
* Estimate shared memory space needed.
*/
static Size
qmon_memsize(void)
{
return hash_estimate_size(MON_HT_SIZE, sizeof(mon_rec));
}
#if PG_VERSION_NUM >= 150000
/*
* shmem_request hook: request additional shared resources. We'll allocate or
* attach to the shared resources in shmem_startup().
*/
static void
shmem_request(void)
{
if (prev_shmem_request_hook)
prev_shmem_request_hook();
RequestAddinShmemSpace(qmon_memsize());
RequestNamedLWLockTranche("mon_lock", 1);
}
#endif
/*
* shmem_startup hook: allocate and attach to shared memory,
*/
static void
shmem_startup(void)
{
HASHCTL info;
if (prev_shmem_startup_hook)
prev_shmem_startup_hook();
mon_ht = NULL;
/*
* Create or attach to the shared memory state, including hash table
*/
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
memset(&info, 0, sizeof(info));
info.keysize = sizeof(uint32);
info.entrysize = sizeof(mon_rec);
#if PG_VERSION_NUM > 100000
info.hash = uint32_hash;
mon_ht = ShmemInitHash("mon_hash", MON_HT_SIZE, MON_HT_SIZE,
&info, HASH_ELEM | HASH_FUNCTION);
#else
mon_ht = ShmemInitHash("mon_hash", MON_HT_SIZE, MON_HT_SIZE,
&info, HASH_ELEM);
#endif
mon_lock = &(GetNamedLWLockTranche("mon_lock"))->lock;
LWLockRelease(AddinShmemInitLock);
/*
* If we're in the postmaster (or a standalone backend...), set up a shmem
* exit hook to dump the statistics to disk.
*/
if (!IsUnderPostmaster)
on_shmem_exit(shmem_shutdown, (Datum) 0);
}
/*
* shmem_shutdown hook
*
* Note: we don't bother with acquiring lock, because there should be no
* other processes running when this is called.
*/
static void
shmem_shutdown(int code, Datum arg)
{
mon_ht = NULL;
return;
}
/*
* Module Load Callback
*/
void
_PG_init(void)
{
if (!process_shared_preload_libraries_in_progress)
return;
DefineCustomIntVariable("pg_mon.max_statements",
"Sets the maximum number of statements tracked by pg_mon.",
NULL,
&MON_HT_SIZE,
5000,
100,
INT_MAX,
PGC_POSTMASTER,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("pg_mon.plan_info_immediate",
"Populate the plan time information immediately after planning phase.",
NULL,
&CONFIG_PLAN_INFO_IMMEDIATE,
CONFIG_PLAN_INFO_IMMEDIATE,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("pg_mon.plan_info_disable",
"Skip plan time information.",
NULL,
&CONFIG_PLAN_INFO_DISABLE,
CONFIG_PLAN_INFO_DISABLE,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("pg_mon.log_new_query",
"Log the new query.",
NULL,
&CONFIG_LOG_NEW_QUERY,
CONFIG_LOG_NEW_QUERY,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
#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 *_shmem_startup().
*/
RequestAddinShmemSpace(qmon_memsize());
RequestNamedLWLockTranche("mon_lock", 1);
#else
/* Install Hooks */
prev_shmem_request_hook = shmem_request_hook;
shmem_request_hook = shmem_request;
#endif
prev_shmem_startup_hook = shmem_startup_hook;
shmem_startup_hook = shmem_startup;
prev_ExecutorStart = ExecutorStart_hook;
ExecutorStart_hook = pgmon_ExecutorStart;
prev_ExecutorRun = ExecutorRun_hook;
ExecutorRun_hook = pgmon_ExecutorRun;
prev_ExecutorFinish = ExecutorFinish_hook;
ExecutorFinish_hook = pgmon_ExecutorFinish;
prev_ExecutorEnd = ExecutorEnd_hook;
ExecutorEnd_hook = pgmon_ExecutorEnd;
prev_ProcessUtility = ProcessUtility_hook;
ProcessUtility_hook = PU_hook;
}
/*
* ExecutorStart hook: start up logging if needed
*/
static void
pgmon_ExecutorStart(QueryDesc *queryDesc, int eflags)
{
if (prev_ExecutorStart)
prev_ExecutorStart(queryDesc, eflags);
else
standard_ExecutorStart(queryDesc, eflags);
if (queryDesc->plannedstmt->queryId != UINT64CONST(0) && nesting_level == 0)
{
/*
* Set up to track total elapsed time in ExecutorRun.Make sure the space
* is allocated in the per-query context so it will go away at ExecutorEnd.
*/
if(queryDesc->totaltime == NULL)
{
/*
* We need to be in right memory context before allocating. Similar
* to how it is done in other places, e.g. in pg_stat_statements,
* auto_explain, etc.
* https://github.com/postgres/postgres/blob/5f28b21eb3c5c2fb72c24608bc686acd7c9b113c/contrib/pg_stat_statements/pg_stat_statements.c#L1021
*/
MemoryContext oldcxt;
oldcxt = MemoryContextSwitchTo(queryDesc->estate->es_query_cxt);
#if PG_VERSION_NUM < 140000
queryDesc->totaltime = InstrAlloc(1, INSTRUMENT_ALL);
#else
queryDesc->totaltime = InstrAlloc(1, INSTRUMENT_ALL, false);
#endif
MemoryContextSwitchTo(oldcxt);
}
if (queryDesc->planstate->instrument == NULL)
{
/*
* We need to be in right memory context before allocating. Similar
* to how it is done in other places, e.g. ExecInitNode
* https://github.com/postgres/postgres/blob/5f28b21eb3c5c2fb72c24608bc686acd7c9b113c/src/backend/executor/execProcnode.c#L397
*/
MemoryContext oldcxt;
oldcxt = MemoryContextSwitchTo(queryDesc->estate->es_query_cxt);
#if PG_VERSION_NUM < 140000
queryDesc->planstate->instrument = InstrAlloc(1, INSTRUMENT_ALL);
#else
queryDesc->planstate->instrument = InstrAlloc(1, INSTRUMENT_ALL, false);
#endif
MemoryContextSwitchTo(oldcxt);
}
queryDesc->instrument_options |= INSTRUMENT_ROWS;
memset(&temp_entry, 0, sizeof(mon_rec));
temp_entry.queryid = queryDesc->plannedstmt->queryId;
/* Add the bucket boundaries for the entry */
memcpy(temp_entry.query_time_buckets, bucket_bounds, sizeof(bucket_bounds));
memcpy(temp_entry.actual_row_buckets, row_bucket_bounds, sizeof(row_bucket_bounds));
memcpy(temp_entry.est_row_buckets, row_bucket_bounds, sizeof(row_bucket_bounds));
if (!CONFIG_PLAN_INFO_DISABLE)
pgmon_plan_store(queryDesc);
}
}
/*
* ExecutorRun hook: all we need do is track nesting depth
*/
static void
pgmon_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction,
uint64 count, bool execute_once)
{
nesting_level++;
PG_TRY();
{
if (prev_ExecutorRun)
prev_ExecutorRun(queryDesc, direction, count, execute_once);
else
standard_ExecutorRun(queryDesc, direction, count, execute_once);
#if PG_VERSION_NUM < 130000
nesting_level--;
#endif
}
#if PG_VERSION_NUM < 130000
PG_CATCH();
{
nesting_level--;
PG_RE_THROW();
}
#else
PG_FINALLY();
{
nesting_level--;
}
#endif
PG_END_TRY();
}
/*
* ExecutorFinish hook: all we need do is track nesting depth
*/
static void
pgmon_ExecutorFinish(QueryDesc *queryDesc)
{
if (queryDesc->planstate->instrument && nesting_level == 0)
{
temp_entry.first_tuple_time = queryDesc->planstate->instrument->firsttuple * 1000;
}
nesting_level++;
PG_TRY();
{
if (prev_ExecutorFinish)
prev_ExecutorFinish(queryDesc);
else
standard_ExecutorFinish(queryDesc);
#if PG_VERSION_NUM < 130000
nesting_level--;
#endif
}
#if PG_VERSION_NUM < 130000
PG_CATCH();
{
nesting_level--;
PG_RE_THROW();
}
#else
PG_FINALLY();
{
nesting_level--;
}
#endif
PG_END_TRY();
}
/*
* ExecutorEnd hook: log results if needed
*/
static void
pgmon_ExecutorEnd(QueryDesc *queryDesc)
{
uint64 queryId = queryDesc->plannedstmt->queryId;
if (queryId != UINT64CONST(0) && queryDesc->totaltime && nesting_level == 0)
{
/*
* Make sure stats accumulation is done.
* (Note: it's okay if several levels of hook all do this.)
*/
InstrEndLoop(queryDesc->totaltime);
InstrEndLoop(queryDesc->planstate->instrument);
/* Save query information */
pgmon_exec_store(queryDesc);
}
if (prev_ExecutorEnd)
prev_ExecutorEnd(queryDesc);
else
standard_ExecutorEnd(queryDesc);
}
/*
* ProcessUtility hook
*/
_PU_HOOK
{
if (CONFIG_LOG_NEW_QUERY)
{
switch (nodeTag(pstmt->utilityStmt))
{
case T_AlterRoleStmt:
break;
default:
ereport(LOG, (errmsg("new query registered from pg_mon"), errhint("%s", queryString)));
break;
}
}
if (prev_ProcessUtility)
{
_prev_hook;
}
else
{
_standard_ProcessUtility;
}
}
static void
pgmon_plan_store(QueryDesc *queryDesc)
{
mon_rec *entry = NULL;
volatile mon_rec *e;
/* Safety check... */
if (!mon_ht)
return;
Assert(queryDesc != NULL);
if (!CONFIG_PLAN_INFO_DISABLE)
{
plan_tree_traversal(queryDesc, queryDesc->plannedstmt->planTree, &temp_entry);
temp_entry.current_expected_rows = queryDesc->planstate->plan->plan_rows;
}
/*
* If plan information is to be provided immediately, then take the
* lock here to update the information in hash table.
*/
if (CONFIG_PLAN_INFO_IMMEDIATE && !CONFIG_PLAN_INFO_DISABLE)
{
LWLockAcquire(mon_lock, LW_SHARED);
entry = create_or_get_entry(temp_entry, temp_entry.queryid, queryDesc);
e = (volatile mon_rec *) entry;
SpinLockAcquire(&e->mutex);
update_histogram(e, EST_ROWS);
SpinLockRelease(&e->mutex);
LWLockRelease(mon_lock);
}
}
static void
pgmon_exec_store(QueryDesc *queryDesc)
{
mon_rec *entry = NULL;
volatile mon_rec *e;
int64 queryId = queryDesc->plannedstmt->queryId;
bool is_present = false;
int i, j;
Assert(queryDesc!= NULL);
/* Safety check... */
if (!mon_ht)
return;
LWLockAcquire(mon_lock, LW_SHARED);
entry = create_or_get_entry(temp_entry, queryId, queryDesc);
e = (volatile mon_rec *) entry;
SpinLockAcquire(&e->mutex);
e->current_total_time = queryDesc->totaltime->total * 1000; //(in msec)
e->first_tuple_time = temp_entry.first_tuple_time;
update_histogram(e, QUERY_TIME);
e->current_actual_rows = queryDesc->totaltime->ntuples;
update_histogram(e, ACTUAL_ROWS);
/*
* If planning info is not already updated then only update
* estimated rows histogram.
*/
if (!CONFIG_PLAN_INFO_IMMEDIATE)
update_histogram(e, EST_ROWS);
/*
* If this query is already present in the hash table, then update the
* plan information of the query also. If the seq_scans, indexes, etc.
* used by the query are different from the previous view then add
* them to the entry here.
* However, if the number of seq_scans or index_scans has reached
* more than MAX_TABLES, then silently exit without adding.
*
* O(tables^2) in current loops may need sort aftert testing.
*/
if (!CONFIG_PLAN_INFO_DISABLE)
{
for (j = 0; j < MAX_TABLES && temp_entry.seq_scans[j] != 0; j++)
{
for (i = 0; i < MAX_TABLES && entry->seq_scans[i] != 0; i++)
{
if (temp_entry.seq_scans[j] == entry->seq_scans[i])
{
is_present = true;
break;
}
}
if (!is_present && i < MAX_TABLES)
{
entry->seq_scans[i] = temp_entry.seq_scans[j];
}
is_present = false;
}
for (j = 0; j < MAX_TABLES && temp_entry.index_scans[j] != 0; j++)
{
for (i = 0; i < MAX_TABLES && entry->index_scans[i] != 0; i++)
{
if (temp_entry.index_scans[j] == entry->index_scans[i])
{
is_present = true;
break;
}
}
if (!is_present && i < MAX_TABLES)
{
entry->index_scans[i] = temp_entry.index_scans[j];
}
is_present = false;
}
for (j = 0; j < MAX_TABLES && temp_entry.bitmap_scans[j] != 0; j++)
{
for (i = 0; i < MAX_TABLES && entry->bitmap_scans[i] != 0; i++)
{
if (temp_entry.bitmap_scans[j] == entry->bitmap_scans[i])
{
is_present = true;
break;
}
}
if (!is_present && i < MAX_TABLES)
{
entry->bitmap_scans[i] = temp_entry.bitmap_scans[j];
}
is_present = false;
}
if (entry->NestedLoopJoin < temp_entry.NestedLoopJoin)
entry->NestedLoopJoin = temp_entry.NestedLoopJoin;
if (entry->HashJoin < temp_entry.HashJoin)
entry->HashJoin = temp_entry.HashJoin;
if (entry->MergeJoin < temp_entry.MergeJoin)
entry->MergeJoin = temp_entry.MergeJoin;
}
SpinLockRelease(&e->mutex);
LWLockRelease(mon_lock);
}
/*
* Find the required hash table entry if not found then copy the
* contents of temp_entry, otherwise return the entry. The caller should have
* shared lock on hash_table which could be upgraded to exclusive mode, if new
* entry has to be added.
*/
static mon_rec * create_or_get_entry(mon_rec temp_entry, int64 queryId, QueryDesc *queryDesc)
{
mon_rec *entry = NULL;
bool found = false;
entry = (mon_rec *) hash_search(mon_ht, &queryId, HASH_FIND, &found);
if (!entry)
{
LWLockRelease(mon_lock);
LWLockAcquire(mon_lock, LW_EXCLUSIVE);
/*
* Check if the number of entries are exceeding the limit. Currently,
* we are handling this case by resetting the pg_mon view, but could be
* dealt more elegantly later, e.g. as in pg_stat_statetments remove
* the least used entries, etc.
*/
if (hash_get_num_entries(mon_ht) >= MON_HT_SIZE)
{
pg_mon_reset_internal();
}
entry = (mon_rec *) hash_search(mon_ht, &queryId, HASH_ENTER, &found);
if (!found)
{
*entry = temp_entry;
SpinLockInit(&entry->mutex);
/* Since this is a new query, log the query text */
if (CONFIG_LOG_NEW_QUERY)
{
ereport(LOG, (errmsg("new query registered from pg_mon"), errhint("%s", queryDesc->sourceText)));
}
}
}
return entry;
}
static void
plan_tree_traversal(QueryDesc *queryDesc, Plan *plan_node, mon_rec *entry)
{
#if PG_VERSION_NUM < 140000
ModifyTable *mplan;
ListCell *p;
#endif
/* Iterate through the plan to find all the required nodes*/
if (plan_node != NULL)
{
switch(plan_node->type)
{
case T_SeqScan:
case T_IndexScan:
case T_IndexOnlyScan:
case T_BitmapIndexScan:
scan_info(plan_node, entry, queryDesc);
break;
case T_FunctionScan:
case T_SampleScan:
case T_TidScan:
case T_SubqueryScan:
case T_ValuesScan:
case T_TableFuncScan:
case T_CteScan:
case T_NamedTuplestoreScan:
case T_WorkTableScan:
case T_ForeignScan:
case T_CustomScan:
namestrcpy(&entry->other_scan, scan_string(plan_node->type));
break;
case T_NestLoop:
entry->NestedLoopJoin++;
break;
case T_MergeJoin:
entry->MergeJoin++;
break;
case T_HashJoin:
entry->HashJoin++;
break;
case T_Gather:
case T_GatherMerge:
entry->is_parallel = true;
break;
case T_ModifyTable:
entry->ModifyTable = true;
#if PG_VERSION_NUM < 140000
mplan =(ModifyTable *)plan_node;
foreach (p, mplan->plans){
Plan *subplan = (Plan *) lfirst (p);
if (subplan != NULL){
scan_info(subplan, entry, queryDesc);
}
}
#endif
break;
default:
break;
}
if (plan_node->lefttree)
plan_tree_traversal(queryDesc, plan_node->lefttree, entry);
if (plan_node->righttree)
plan_tree_traversal(queryDesc, plan_node->righttree, entry);
}
}
static void
scan_info(Plan *subplan, mon_rec *entry, QueryDesc *queryDesc)
{
bool found = false;
IndexScan *idx;
BitmapIndexScan *bidx;
Scan *scan;
RangeTblEntry *rte;
Index relid;
int i = 0;
switch(subplan->type)
{
case T_SeqScan:
scan = (Scan *)subplan;
relid = scan->scanrelid;
rte = rt_fetch(relid, queryDesc->plannedstmt->rtable);
for (i = 0; i < MAX_TABLES && entry->seq_scans[i] > 0;
i++)
{
if (entry->seq_scans[i] == rte->relid)
{
found = true;
break;
}
}
if (!found && i < MAX_TABLES)
entry->seq_scans[i] = rte->relid;
break;
case T_IndexScan:
case T_IndexOnlyScan:
idx = (IndexScan *)subplan;
for (i = 0; i < MAX_TABLES && entry->index_scans[i] > 0;
i++)
{
if (entry->index_scans[i] == idx->indexid)
{
found = true;
break;
}
}
if (!found && i < MAX_TABLES)
entry->index_scans[i] = idx->indexid;
break;
case T_BitmapIndexScan:
bidx = (BitmapIndexScan *)subplan;
for (i = 0; i < MAX_TABLES && entry->bitmap_scans[i] > 0;
i++)
{
if (entry->bitmap_scans[i] == bidx->indexid)
{
found = true;
break;
}
}
if (!found && i < MAX_TABLES)
entry->bitmap_scans[i] = bidx->indexid;
break;
default:
break;
}
}
/*
* This is called when user requests the pg_mon view.
*/
Datum
pg_mon(PG_FUNCTION_ARGS)
{
ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
TupleDesc tupdesc;
Tuplestorestate *tupstore;
MemoryContext per_query_ctx;
MemoryContext oldcontext;
HASH_SEQ_STATUS status;
mon_rec *entry;
/* hash table must exist already */
if (!mon_ht)
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("pg_mon must be loaded via shared_preload_libraries")));
/* Switch into long-lived context to construct returned data structures */
per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
oldcontext = MemoryContextSwitchTo(per_query_ctx);
/* Build a tuple descriptor for our result type */
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
elog(ERROR, "return type must be a row type");
tupstore = tuplestore_begin_heap(true, false, work_mem);
MemoryContextSwitchTo(oldcontext);
LWLockAcquire(mon_lock, LW_SHARED);
hash_seq_init(&status, mon_ht);
while ((entry = hash_seq_search(&status)) != NULL)
{
Datum *numdatums = (Datum *) palloc(NUMBUCKETS * sizeof(Datum));
Datum *rownumdatums = (Datum *) palloc(ROWNUMBUCKETS * sizeof(Datum));
Datum values[MON_COLS];
bool nulls[MON_COLS] = {0};
int i = 0, n, idx = 0, last_fill_bucket = 0;
ArrayType *arry = NULL;
memset(values, 0, sizeof(values));
memset(nulls, 0, sizeof(nulls));
values[i++] = Int64GetDatum(entry->queryid);
values[i++] = Float8GetDatumFast(entry->current_total_time);
values[i++] = Float8GetDatumFast(entry->first_tuple_time);
values[i++] = Float8GetDatumFast(entry->current_expected_rows);
values[i++] = Float8GetDatumFast(entry->current_actual_rows);
values[i++] = BoolGetDatum(entry->is_parallel);
values[i++] = BoolGetDatum(entry->ModifyTable);
if (!entry->ModifyTable && entry->seq_scans[0] == 0)
nulls[i++] = true;
else
{
Datum *datums = (Datum *) palloc(MAX_TABLES * sizeof(Datum));
ArrayType *arry;
int n = 0, idx = 0;
for (n = 0; n < MAX_TABLES && entry->seq_scans[n] != 0; n++)
datums[idx++] = ObjectIdGetDatum(&entry->seq_scans[n]);
arry = construct_array(datums, idx, OIDOID, sizeof(Oid), false, 'i');
values[i++] = PointerGetDatum(arry);
}
if (!entry->ModifyTable && entry->index_scans[0] == 0)
nulls[i++] = true;
else
{
Datum *datums = (Datum *) palloc(MAX_TABLES * sizeof(Datum));
ArrayType *arry;
int n = 0, idx = 0;
for (n = 0; n < MAX_TABLES && entry->index_scans[n] != 0; n++)
datums[idx++] = ObjectIdGetDatum(&entry->index_scans[n]);
arry = construct_array(datums, idx, OIDOID, sizeof(Oid), false, 'i');
values[i++] = PointerGetDatum(arry);
}
if (!entry->ModifyTable && entry->bitmap_scans[0] == 0)
nulls[i++] = true;
else
{
Datum *datums = (Datum *) palloc(MAX_TABLES * sizeof(Datum));
ArrayType *arry;
int n = 0, idx = 0;
for (n = 0; n < MAX_TABLES && entry->bitmap_scans[n] != 0; n++)
datums[idx++] = ObjectIdGetDatum(&entry->bitmap_scans[n]);
arry = construct_array(datums, idx, OIDOID, sizeof(Oid), false, 'i');
values[i++] = PointerGetDatum(arry);
}
values[i++] = NameGetDatum(&entry->other_scan);
values[i++] = Int32GetDatum(entry->NestedLoopJoin);
values[i++] = Int32GetDatum(entry->HashJoin);
values[i++] = Int32GetDatum(entry->MergeJoin);
for (n = NUMBUCKETS-1; n >= 0; n--)
{
if (entry->query_time_freq[n] > 0)
{
last_fill_bucket = n;
break;
}
}
for (n = 0; n <= last_fill_bucket; n++)
{
numdatums[idx++] = Int64GetDatum(entry->query_time_buckets[n]);
}
arry = construct_array(numdatums, idx, INT4OID, sizeof(int), true, 'i');
values[i++] = PointerGetDatum(arry);
for (n = 0, idx = 0; n <= last_fill_bucket; n++)
{
numdatums[idx++] = Int64GetDatum(entry->query_time_freq[n]);
}
arry = construct_array(numdatums, idx, INT4OID, sizeof(int), true, 'i');
values[i++] = PointerGetDatum(arry);
numdatums = NULL;
arry = NULL;
last_fill_bucket = 0;
for (n = ROWNUMBUCKETS-1; n >= 0; n--)
{
if (entry->actual_row_freq[n] > 0)
{
last_fill_bucket = n;
break;