-
Notifications
You must be signed in to change notification settings - Fork 59
/
pg_stat_monitor.c
4177 lines (3597 loc) · 119 KB
/
pg_stat_monitor.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_stat_monitor.c
* Track statement execution times across a whole database cluster.
*
* Portions Copyright © 2018-2024, Percona LLC and/or its affiliates
*
* Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
*
* Portions Copyright (c) 1994, The Regents of the University of California
*
* IDENTIFICATION
* contrib/pg_stat_monitor/pg_stat_monitor.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/parallel.h"
#include "nodes/pg_list.h"
#include "utils/guc.h"
#include <regex.h>
#include <stddef.h>
#include "pgstat.h"
#include "commands/dbcommands.h"
#include "commands/explain.h"
#include "lib/stringinfo.h"
#include "pg_stat_monitor.h"
/*
* Extension version number, for supporting older extension versions' objects
*/
typedef enum pgsmVersion
{
PGSM_V1_0 = 0,
PGSM_V2_0,
PGSM_V2_1
} pgsmVersion;
PG_MODULE_MAGIC;
#define BUILD_VERSION "2.1.0"
/* Number of output arguments (columns) for various API versions */
#define PG_STAT_MONITOR_COLS_V1_0 52
#define PG_STAT_MONITOR_COLS_V2_0 64
#define PG_STAT_MONITOR_COLS_V2_1 70
#define PG_STAT_MONITOR_COLS PG_STAT_MONITOR_COLS_V2_1 /* maximum of above */
#define PGSM_TEXT_FILE PGSTAT_STAT_PERMANENT_DIRECTORY "pg_stat_monitor_query"
#define PGUNSIXBIT(val) (((val) & 0x3F) + '0')
#define _snprintf(_str_dst, _str_src, _len, _max_len)\
memcpy((void *)_str_dst, _str_src, _len < _max_len ? _len : _max_len)
#define pgsm_enabled(level) \
(!IsParallelWorker() && \
(pgsm_track == PGSM_TRACK_ALL || \
(pgsm_track == PGSM_TRACK_TOP && (level) == 0)))
#define _snprintf2(_str_dst, _str_src, _len1, _len2)\
do \
{ \
int i; \
for(i = 0; i < _len1; i++) \
strlcpy((char *)_str_dst[i], _str_src[i], _len2); \
}while(0)
#define PGSM_INVALID_IP_MASK 0xFFFFFFFF
#define pgsm_client_ip_is_valid() \
(pgsm_client_ip != PGSM_INVALID_IP_MASK)
/*---- Initicalization Function Declarations ----*/
void _PG_init(void);
/* Current nesting depth of planner/ExecutorRun/ProcessUtility calls */
static int nesting_level = 0;
volatile bool __pgsm_do_not_capture_error = false;
#if PG_VERSION_NUM >= 130000 && PG_VERSION_NUM < 170000
/* Before planner nesting level was conunted separately */
static int plan_nested_level = 0;
#endif
/* Histogram bucket variables */
static double hist_bucket_min;
static double hist_bucket_max;
static double hist_bucket_timings[MAX_RESPONSE_BUCKET + 2][2]; /* Start and end timings */
static int hist_bucket_count_user;
static int hist_bucket_count_total;
static uint32 pgsm_client_ip = PGSM_INVALID_IP_MASK;
/* The array to store outer layer query id*/
uint64 *nested_queryids;
char **nested_query_txts;
List *lentries = NIL;
/* Regex object used to extract query comments. */
static regex_t preg_query_comments;
static char relations[REL_LST][REL_LEN];
static int num_relations; /* Number of relation in the query */
static bool system_init = false;
static struct rusage rusage_start;
static struct rusage rusage_end;
/* Application name and length; set each time when an entry is created locally */
static char app_name[APPLICATIONNAME_LEN];
static int app_name_len;
/* Query buffer, store queries' text. */
static char *pgsm_explain(QueryDesc *queryDesc);
static void extract_query_comments(const char *query, char *comments, size_t max_len);
static void set_histogram_bucket_timings(void);
static void histogram_bucket_timings(int index, double *b_start, double *b_end);
static int get_histogram_bucket(double q_time);
static bool IsSystemInitialized(void);
static double time_diff(struct timeval end, struct timeval start);
static void request_additional_shared_resources(void);
/* Saved hook values in case of unload */
#if PG_VERSION_NUM >= 150000
static void pgsm_shmem_request(void);
static shmem_request_hook_type prev_shmem_request_hook = NULL;
#endif
#if PG_VERSION_NUM >= 130000
static planner_hook_type planner_hook_next = NULL;
#endif
static post_parse_analyze_hook_type prev_post_parse_analyze_hook = NULL;
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 emit_log_hook_type prev_emit_log_hook = NULL;
DECLARE_HOOK(void pgsm_emit_log_hook, ErrorData *edata);
static shmem_startup_hook_type prev_shmem_startup_hook = NULL;
static ExecutorCheckPerms_hook_type prev_ExecutorCheckPerms_hook = NULL;
PG_FUNCTION_INFO_V1(pg_stat_monitor_version);
PG_FUNCTION_INFO_V1(pg_stat_monitor_reset);
PG_FUNCTION_INFO_V1(pg_stat_monitor_1_0);
PG_FUNCTION_INFO_V1(pg_stat_monitor_2_0);
PG_FUNCTION_INFO_V1(pg_stat_monitor_2_1);
PG_FUNCTION_INFO_V1(pg_stat_monitor);
PG_FUNCTION_INFO_V1(get_histogram_timings);
PG_FUNCTION_INFO_V1(pg_stat_monitor_hook_stats);
static uint pg_get_client_addr(bool *ok);
static int pg_get_application_name(char *name, int buff_size);
static PgBackendStatus *pg_get_backend_status(void);
static Datum intarray_get_datum(int32 arr[], int len);
#if PG_VERSION_NUM < 140000
DECLARE_HOOK(void pgsm_post_parse_analyze, ParseState *pstate, Query *query);
#else
DECLARE_HOOK(void pgsm_post_parse_analyze, ParseState *pstate, Query *query, JumbleState *jstate);
#endif
DECLARE_HOOK(void pgsm_ExecutorStart, QueryDesc *queryDesc, int eflags);
DECLARE_HOOK(void pgsm_ExecutorRun, QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once);
DECLARE_HOOK(void pgsm_ExecutorFinish, QueryDesc *queryDesc);
DECLARE_HOOK(void pgsm_ExecutorEnd, QueryDesc *queryDesc);
#if PG_VERSION_NUM < 160000
DECLARE_HOOK(bool pgsm_ExecutorCheckPerms, List *rt, bool abort);
#else
DECLARE_HOOK(bool pgsm_ExecutorCheckPerms, List *rt, List *rp, bool abort);
#endif
#if PG_VERSION_NUM >= 140000
DECLARE_HOOK(PlannedStmt *pgsm_planner_hook, Query *parse, const char *query_string, int cursorOptions, ParamListInfo boundParams);
DECLARE_HOOK(void pgsm_ProcessUtility, PlannedStmt *pstmt, const char *queryString,
bool readOnlyTree,
ProcessUtilityContext context,
ParamListInfo params, QueryEnvironment *queryEnv,
DestReceiver *dest,
QueryCompletion *qc);
#elif PG_VERSION_NUM >= 130000
DECLARE_HOOK(PlannedStmt *pgsm_planner_hook, Query *parse, const char *query_string, int cursorOptions, ParamListInfo boundParams);
DECLARE_HOOK(void pgsm_ProcessUtility, PlannedStmt *pstmt, const char *queryString,
ProcessUtilityContext context,
ParamListInfo params, QueryEnvironment *queryEnv,
DestReceiver *dest,
QueryCompletion *qc);
#else
static void BufferUsageAccumDiff(BufferUsage *bufusage, BufferUsage *pgBufferUsage, BufferUsage *bufusage_start);
DECLARE_HOOK(void pgsm_ProcessUtility, PlannedStmt *pstmt, const char *queryString,
ProcessUtilityContext context, ParamListInfo params,
QueryEnvironment *queryEnv,
DestReceiver *dest,
char *completionTag);
#endif
static uint64 pgsm_hash_string(const char *str, int len);
char *unpack_sql_state(int sql_state);
static pgsmEntry *pgsm_create_hash_entry(uint64 bucket_id, uint64 queryid, PlanInfo *plan_info);
static void pgsm_add_to_list(pgsmEntry *entry, char *query_text, int query_len);
static pgsmEntry *pgsm_get_entry_for_query(uint64 queryid, PlanInfo *plan_info, const char *query_text, int query_len, bool create);
static uint64 get_pgsm_query_id_hash(const char *norm_query, int len);
static void get_param_value(const ParamListInfo plist, int idx, StringInfoData *buffer);
static StringInfoData get_denormalized_query(const ParamListInfo paramlist, const char *query_text);
static void pgsm_cleanup_callback(void *arg);
static void pgsm_store_error(const char *query, ErrorData *edata);
/*---- Local variables ----*/
MemoryContextCallback mem_cxt_reset_callback =
{
.func = pgsm_cleanup_callback,
.arg = NULL
};
volatile bool callback_setup = false;
static void pgsm_update_entry(pgsmEntry *entry,
const char *query,
char *comments,
int comments_len,
PlanInfo *plan_info,
SysInfo *sys_info,
ErrorInfo *error_info,
double plan_total_time,
double exec_total_time,
uint64 rows,
BufferUsage *bufusage,
WalUsage *walusage,
const struct JitInstrumentation *jitusage,
bool reset,
pgsmStoreKind kind);
static void pgsm_store_ex(pgsmEntry *entry, ParamListInfo params);
/* Stores query entry in normalized form */
static inline void
pgsm_store(pgsmEntry *entry)
{
pgsm_store_ex(entry, NULL);
}
static void pg_stat_monitor_internal(FunctionCallInfo fcinfo,
pgsmVersion api_version,
bool showtext);
#if PG_VERSION_NUM < 140000
static void AppendJumble(JumbleState *jstate,
const unsigned char *item, Size size);
static void JumbleQuery(JumbleState *jstate, Query *query);
static void JumbleRangeTable(JumbleState *jstate, List *rtable, CmdType cmd_type);
static void JumbleExpr(JumbleState *jstate, Node *node);
static void RecordConstLocation(JumbleState *jstate, int location);
/*
* Given a possibly multi-statement source string, confine our attention to the
* relevant part of the string.
*/
static const char *CleanQuerytext(const char *query, int *location, int *len);
static uint64 get_query_id(JumbleState *jstate, Query *query);
#endif
static char *generate_normalized_query(JumbleState *jstate, const char *query,
int query_loc, int *query_len_p, int encoding);
static void fill_in_constant_lengths(JumbleState *jstate, const char *query, int query_loc);
static int comp_location(const void *a, const void *b);
static uint64 get_next_wbucket(pgsmSharedState *pgsm);
/*
* Module load callback
*/
/* cppcheck-suppress unusedFunction */
void
_PG_init(void)
{
int rc;
elog(DEBUG2, "[pg_stat_monitor] pg_stat_monitor: %s().", __FUNCTION__);
/*
* In order to create our shared memory area, we have to be loaded via
* shared_preload_libraries. If not, fall out without hooking into any of
* the main system. (We don't throw error here because it seems useful to
* allow the pg_stat_monitor functions to be created even when the module
* isn't active. The functions must protect themselves against being
* called then, however.)
*/
if (!process_shared_preload_libraries_in_progress)
return;
/* Inilize the GUC variables */
init_guc();
set_histogram_bucket_timings();
#if PG_VERSION_NUM >= 140000
/*
* Inform the postmaster that we want to enable query_id calculation if
* compute_query_id is set to auto.
*/
EnableQueryId();
#endif
EmitWarningsOnPlaceholders("pg_stat_monitor");
/*
* Compile regular expression for extracting out query comments only once.
*/
rc = regcomp(&preg_query_comments, "/\\*([^*]|[\r\n]|(\\*+([^*/]|[\r\n])))*\\*+/", REG_EXTENDED);
if (rc != 0)
{
elog(ERROR, "[pg_stat_monitor] _PG_init: query comments regcomp() failed, return code=(%d).", rc);
}
/*
* Install hooks.
*/
#if PG_VERSION_NUM >= 150000
prev_shmem_request_hook = shmem_request_hook;
shmem_request_hook = pgsm_shmem_request;
#else
request_additional_shared_resources();
#endif
prev_shmem_startup_hook = shmem_startup_hook;
shmem_startup_hook = pgsm_shmem_startup;
prev_post_parse_analyze_hook = post_parse_analyze_hook;
post_parse_analyze_hook = HOOK(pgsm_post_parse_analyze);
prev_ExecutorStart = ExecutorStart_hook;
ExecutorStart_hook = HOOK(pgsm_ExecutorStart);
prev_ExecutorRun = ExecutorRun_hook;
ExecutorRun_hook = HOOK(pgsm_ExecutorRun);
prev_ExecutorFinish = ExecutorFinish_hook;
ExecutorFinish_hook = HOOK(pgsm_ExecutorFinish);
prev_ExecutorEnd = ExecutorEnd_hook;
ExecutorEnd_hook = HOOK(pgsm_ExecutorEnd);
prev_ProcessUtility = ProcessUtility_hook;
ProcessUtility_hook = HOOK(pgsm_ProcessUtility);
#if PG_VERSION_NUM >= 130000
planner_hook_next = planner_hook;
planner_hook = HOOK(pgsm_planner_hook);
#endif
prev_emit_log_hook = emit_log_hook;
emit_log_hook = HOOK(pgsm_emit_log_hook);
prev_ExecutorCheckPerms_hook = ExecutorCheckPerms_hook;
ExecutorCheckPerms_hook = HOOK(pgsm_ExecutorCheckPerms);
nested_queryids = (uint64 *) malloc(sizeof(uint64) * max_stack_depth);
nested_query_txts = (char **) malloc(sizeof(char *) * max_stack_depth);
system_init = true;
}
/*
* shmem_startup hook: allocate or attach to shared memory,
* then load any pre-existing statistics from file.
* Also create and load the query-texts file, which is expected to exist
* (even if empty) while the module is enabled.
*/
void
pgsm_shmem_startup(void)
{
if (prev_shmem_startup_hook)
prev_shmem_startup_hook();
pgsm_startup();
}
static void
request_additional_shared_resources(void)
{
/*
* 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 pgsm_shmem_startup().
*/
RequestAddinShmemSpace(pgsm_ShmemSize() + HOOK_STATS_SIZE);
RequestNamedLWLockTranche("pg_stat_monitor", 1);
}
/*
* Select the version of pg_stat_monitor.
*/
Datum
pg_stat_monitor_version(PG_FUNCTION_ARGS)
{
PG_RETURN_TEXT_P(cstring_to_text(BUILD_VERSION));
}
#if PG_VERSION_NUM >= 150000
/*
* shmem_request hook: request additional shared resources. We'll allocate or
* attach to the shared resources in pgsm_shmem_startup().
*/
static void
pgsm_shmem_request(void)
{
if (prev_shmem_request_hook)
prev_shmem_request_hook();
request_additional_shared_resources();
}
#endif
static void
pgsm_post_parse_analyze_internal(ParseState *pstate, Query *query, JumbleState *jstate)
{
pgsmEntry *entry;
const char *query_text;
char *norm_query = NULL;
int norm_query_len;
int location;
int query_len;
/* Safety check... */
if (!IsSystemInitialized())
return;
if (callback_setup == false)
{
/*
* If MessageContext is valid setup a callback to cleanup our local
* stats list when the MessagContext gets reset
*/
if (MemoryContextIsValid(MessageContext))
{
MemoryContextRegisterResetCallback(MessageContext, &mem_cxt_reset_callback);
callback_setup = true;
}
}
if (!pgsm_enabled(nesting_level))
return;
/*
* If it's EXECUTE, clear the queryId so that stats will accumulate for
* the underlying PREPARE. But don't do this if we're not tracking
* utility statements, to avoid messing up another extension that might be
* tracking them.
*/
if (query->utilityStmt)
{
if (pgsm_track_utility && IsA(query->utilityStmt, ExecuteStmt))
query->queryId = UINT64CONST(0);
return;
}
/*
* Let's calculate queryid for versions 13 and below. We don't have to
* check that jstate is valid, it always will be for these versions.
*/
#if PG_VERSION_NUM < 140000
query->queryId = get_query_id(jstate, query);
#endif
/*
* If we are unlucky enough to get a hash of zero, use 1 instead, to
* prevent confusion with the utility-statement case.
*/
if (query->queryId == UINT64CONST(0))
query->queryId = UINT64CONST(1);
/*
* Let's save the normalized query so that we can save the data without in
* hash later on without the need of jstate which wouldn't be available.
*/
query_text = pstate->p_sourcetext;
location = query->stmt_location;
query_len = query->stmt_len;
/* We should always have a valid query. */
query_text = CleanQuerytext(query_text, &location, &query_len);
Assert(query_text);
norm_query_len = query_len;
/* Generate a normalized query */
if (jstate && jstate->clocations_count > 0 && (pgsm_enable_pgsm_query_id || pgsm_normalized_query))
{
norm_query = generate_normalized_query(jstate,
query_text, /* query */
location, /* query location */
&norm_query_len,
GetDatabaseEncoding());
Assert(norm_query);
}
/*
* At this point, we don't know which bucket this query will land in, so
* passing 0. The store function MUST later update it based on the current
* bucket value. The correct bucket value will be needed then to search
* the hash table, or create the appropriate entry.
*/
entry = pgsm_create_hash_entry(0, query->queryId, NULL);
/*
* Update other member that are not counters, so that we don't have to
* worry about these.
*/
entry->pgsm_query_id = get_pgsm_query_id_hash(norm_query ? norm_query : query_text, norm_query_len);
entry->counters.info.cmd_type = query->commandType;
/*
* Add the query text and entry to the local list.
*
* Preserve the normalized query if needed and we got a valid one.
* Otherwise, store the actual query so that we don't have to check what
* query to store when saving into the hash.
*
* In case of query_text, request the function to duplicate it so that it
* is put in the relevant memory context.
*/
if (pgsm_normalized_query && norm_query)
pgsm_add_to_list(entry, norm_query, norm_query_len);
else
{
pgsm_add_to_list(entry, (char *) query_text, query_len);
}
/* Check that we've not exceeded max_stack_depth */
Assert(list_length(lentries) <= max_stack_depth);
if (norm_query)
pfree(norm_query);
}
#if PG_VERSION_NUM >= 140000
/*
* Post-parse-analysis hook: mark query with a queryId
*/
static void
pgsm_post_parse_analyze(ParseState *pstate, Query *query, JumbleState *jstate)
{
if (prev_post_parse_analyze_hook)
prev_post_parse_analyze_hook(pstate, query, jstate);
pgsm_post_parse_analyze_internal(pstate, query, jstate);
}
#else
/*
* Post-parse-analysis hook: mark query with a queryId
*/
static void
pgsm_post_parse_analyze(ParseState *pstate, Query *query)
{
JumbleState jstate;
if (prev_post_parse_analyze_hook)
prev_post_parse_analyze_hook(pstate, query);
pgsm_post_parse_analyze_internal(pstate, query, &jstate);
}
#endif
/*
* ExecutorStart hook: start up tracking if needed
*/
static void
pgsm_ExecutorStart(QueryDesc *queryDesc, int eflags)
{
if (getrusage(RUSAGE_SELF, &rusage_start) != 0)
elog(DEBUG1, "[pg_stat_monitor] pgsm_ExecutorStart: failed to execute getrusage.");
if (prev_ExecutorStart)
prev_ExecutorStart(queryDesc, eflags);
else
standard_ExecutorStart(queryDesc, eflags);
/*
* If query has queryId zero, don't track it. This prevents double
* counting of optimizable statements that are directly contained in
* utility statements.
*/
if (pgsm_enabled(nesting_level) &&
queryDesc->plannedstmt->queryId != UINT64CONST(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)
{
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);
}
}
}
/*
* ExecutorRun hook: all we need do is track nesting depth
*/
static void
pgsm_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count,
bool execute_once)
{
if (nesting_level >= 0 && nesting_level < max_stack_depth)
{
nested_queryids[nesting_level] = queryDesc->plannedstmt->queryId;
nested_query_txts[nesting_level] = strdup(queryDesc->sourceText);
}
nesting_level++;
PG_TRY();
{
if (prev_ExecutorRun)
prev_ExecutorRun(queryDesc, direction, count, execute_once);
else
standard_ExecutorRun(queryDesc, direction, count, execute_once);
nesting_level--;
if (nesting_level >= 0 && nesting_level < max_stack_depth)
{
nested_queryids[nesting_level] = UINT64CONST(0);
if (nested_query_txts[nesting_level])
free(nested_query_txts[nesting_level]);
nested_query_txts[nesting_level] = NULL;
}
}
PG_CATCH();
{
nesting_level--;
if (nesting_level >= 0 && nesting_level < max_stack_depth)
{
nested_queryids[nesting_level] = UINT64CONST(0);
if (nested_query_txts[nesting_level])
free(nested_query_txts[nesting_level]);
nested_query_txts[nesting_level] = NULL;
}
PG_RE_THROW();
}
PG_END_TRY();
}
/*
* ExecutorFinish hook: all we need do is track nesting depth
*/
static void
pgsm_ExecutorFinish(QueryDesc *queryDesc)
{
nesting_level++;
PG_TRY();
{
if (prev_ExecutorFinish)
prev_ExecutorFinish(queryDesc);
else
standard_ExecutorFinish(queryDesc);
nesting_level--;
}
PG_CATCH();
{
nesting_level--;
PG_RE_THROW();
}
PG_END_TRY();
}
static char *
pgsm_explain(QueryDesc *queryDesc)
{
ExplainState *es = NewExplainState();
es->buffers = false;
es->analyze = false;
es->verbose = false;
es->costs = false;
es->format = EXPLAIN_FORMAT_TEXT;
ExplainBeginOutput(es);
ExplainPrintPlan(es, queryDesc);
ExplainEndOutput(es);
if (es->str->len > 0 && es->str->data[es->str->len - 1] == '\n')
es->str->data[--es->str->len] = '\0';
return es->str->data;
}
/*
* ExecutorEnd hook: store results if needed
*/
static void
pgsm_ExecutorEnd(QueryDesc *queryDesc)
{
uint64 queryId = queryDesc->plannedstmt->queryId;
SysInfo sys_info;
PlanInfo plan_info;
PlanInfo *plan_ptr = NULL;
pgsmEntry *entry = NULL;
MemoryContext oldctx;
/* Extract the plan information in case of SELECT statement */
if (queryDesc->operation == CMD_SELECT && pgsm_enable_query_plan)
{
int rv;
/*
* Making sure it is a per query context so that there's no memory
* leak when executor ends.
*/
oldctx = MemoryContextSwitchTo(queryDesc->estate->es_query_cxt);
rv = snprintf(plan_info.plan_text, PLAN_TEXT_LEN, "%s", pgsm_explain(queryDesc));
/*
* If snprint didn't write anything or there was an error, let's keep
* planinfo as NULL.
*/
if (rv > 0)
{
plan_info.plan_len = (rv < PLAN_TEXT_LEN) ? rv : PLAN_TEXT_LEN - 1;
plan_info.planid = pgsm_hash_string(plan_info.plan_text, plan_info.plan_len);
plan_ptr = &plan_info;
}
/* Switch back to old context */
MemoryContextSwitchTo(oldctx);
}
if (queryId != UINT64CONST(0) && queryDesc->totaltime && pgsm_enabled(nesting_level))
{
entry = pgsm_get_entry_for_query(queryId, plan_ptr, (char *) queryDesc->sourceText, strlen(queryDesc->sourceText), true);
if (!entry)
{
elog(DEBUG2, "[pg_stat_monitor] pgsm_ExecutorEnd: Failed to find entry for [%lu] %s.", queryId, queryDesc->sourceText);
return;
}
if (entry->key.planid == 0)
entry->key.planid = (plan_ptr) ? plan_ptr->planid : 0;
/*
* Make sure stats accumulation is done. (Note: it's okay if several
* levels of hook all do this.)
*/
InstrEndLoop(queryDesc->totaltime);
sys_info.utime = 0;
sys_info.stime = 0;
if (getrusage(RUSAGE_SELF, &rusage_end) != 0)
elog(DEBUG1, "[pg_stat_monitor] pgsm_ExecutorEnd: Failed to execute getrusage.");
else
{
sys_info.utime = time_diff(rusage_end.ru_utime, rusage_start.ru_utime);
sys_info.stime = time_diff(rusage_end.ru_stime, rusage_start.ru_stime);
}
pgsm_update_entry(entry, /* entry */
NULL, /* query */
NULL, /* comments */
0, /* comments length */
plan_ptr, /* PlanInfo */
&sys_info, /* SysInfo */
NULL, /* ErrorInfo */
0, /* plan_total_time */
queryDesc->totaltime->total * 1000.0, /* exec_total_time */
queryDesc->estate->es_processed, /* rows */
&queryDesc->totaltime->bufusage, /* bufusage */
#if PG_VERSION_NUM >= 130000
&queryDesc->totaltime->walusage, /* walusage */
#else
NULL,
#endif
#if PG_VERSION_NUM >= 150000
queryDesc->estate->es_jit ? &queryDesc->estate->es_jit->instr : NULL, /* jitusage */
#else
NULL,
#endif
false, /* reset */
PGSM_EXEC); /* kind */
pgsm_store_ex(entry, queryDesc->params);
}
if (prev_ExecutorEnd)
prev_ExecutorEnd(queryDesc);
else
standard_ExecutorEnd(queryDesc);
num_relations = 0;
}
static bool
#if PG_VERSION_NUM < 160000
pgsm_ExecutorCheckPerms(List *rt, bool abort)
#else
pgsm_ExecutorCheckPerms(List *rt, List *rp, bool abort)
#endif
{
ListCell *lr = NULL;
int i = 0;
int j = 0;
Oid list_oid[20];
num_relations = 0;
foreach(lr, rt)
{
RangeTblEntry *rte = lfirst(lr);
if (rte->rtekind != RTE_RELATION
#if PG_VERSION_NUM >= 160000
&& (rte->rtekind != RTE_SUBQUERY && rte->relkind != 'v')
#endif
)
continue;
if (i < REL_LST)
{
bool found = false;
for (j = 0; j < i; j++)
{
if (list_oid[j] == rte->relid)
found = true;
}
if (!found)
{
char *namespace_name;
char *relation_name;
list_oid[j] = rte->relid;
namespace_name = get_namespace_name(get_rel_namespace(rte->relid));
relation_name = get_rel_name(rte->relid);
if (rte->relkind == 'v')
snprintf(relations[i++], REL_LEN, "%s.%s*", namespace_name, relation_name);
else
snprintf(relations[i++], REL_LEN, "%s.%s", namespace_name, relation_name);
}
}
}
num_relations = i;
if (prev_ExecutorCheckPerms_hook)
#if PG_VERSION_NUM < 160000
return prev_ExecutorCheckPerms_hook(rt, abort);
#else
return prev_ExecutorCheckPerms_hook(rt, rp, abort);
#endif
return true;
}
#if PG_VERSION_NUM >= 130000
static PlannedStmt *
pgsm_planner_hook(Query *parse, const char *query_string, int cursorOptions, ParamListInfo boundParams)
{
PlannedStmt *result;
/*
* We can't process the query if no query_string is provided, as
* pgsm_store needs it. We also ignore query without queryid, as it would
* be treated as a utility statement, which may not be the case.
*
* Note that planner_hook can be called from the planner itself, so we
* have a specific nesting level for the planner. However, utility
* commands containing optimizable statements can also call the planner,
* same for regular DML (for instance for underlying foreign key queries).
* So testing the planner nesting level only is not enough to detect real
* top level planner call.
*/
bool enabled;
#if PG_VERSION_NUM >= 170000
enabled = pgsm_enabled(nesting_level);
#else
enabled = pgsm_enabled(plan_nested_level + nesting_level);
#endif
if (enabled && pgsm_track_planning && query_string && parse->queryId != UINT64CONST(0))
{
pgsmEntry *entry = NULL;
instr_time start;
instr_time duration;
BufferUsage bufusage_start;
BufferUsage bufusage;
WalUsage walusage_start;
WalUsage walusage;
/* We need to track buffer usage as the planner can access them. */
bufusage_start = pgBufferUsage;
/*
* Similarly the planner could write some WAL records in some cases
* (e.g. setting a hint bit with those being WAL-logged)
*/
walusage_start = pgWalUsage;
INSTR_TIME_SET_CURRENT(start);
if (MemoryContextIsValid(MessageContext))
entry = pgsm_get_entry_for_query(parse->queryId, NULL, query_string, strlen(query_string), true);
#if PG_VERSION_NUM >= 170000
nesting_level++;
#else
plan_nested_level++;
#endif
PG_TRY();
{
/*
* If there is a previous installed hook, then assume it's going
* to call standard_planner() function, otherwise we call the
* function here. This is to avoid calling standard_planner()
* function twice, since it modifies the first argument (Query *),
* the second call would trigger an assertion failure.
*/
if (planner_hook_next)
result = planner_hook_next(parse, query_string, cursorOptions, boundParams);
else
result = standard_planner(parse, query_string, cursorOptions, boundParams);
}
PG_FINALLY();
{
#if PG_VERSION_NUM >= 170000
nesting_level--;
#else
plan_nested_level--;
#endif
}
PG_END_TRY();
INSTR_TIME_SET_CURRENT(duration);
INSTR_TIME_SUBTRACT(duration, start);
/* calc differences of buffer counters. */
memset(&bufusage, 0, sizeof(BufferUsage));
BufferUsageAccumDiff(&bufusage, &pgBufferUsage, &bufusage_start);
/* calc differences of WAL counters. */
memset(&walusage, 0, sizeof(WalUsage));
WalUsageAccumDiff(&walusage, &pgWalUsage, &walusage_start);
/* The plan details are captured when the query finishes */
if (entry)
pgsm_update_entry(entry, /* entry */
NULL, /* query */
NULL, /* comments */
0, /* comments length */
NULL, /* PlanInfo */
NULL, /* SysInfo */
NULL, /* ErrorInfo */
INSTR_TIME_GET_MILLISEC(duration), /* plan_total_time */
0, /* exec_total_time */
0, /* rows */
&bufusage, /* bufusage */
&walusage, /* walusage */
NULL, /* jitusage */
false, /* reset */
PGSM_PLAN); /* kind */
}
else
{
/*
* Even though we're not tracking plan time for this statement, we
* must still increment the nesting level, to ensure that functions
* evaluated during planning are not seen as top-level calls.
*
* If there is a previous installed hook, then assume it's going to
* call standard_planner() function, otherwise we call the function
* here. This is to avoid calling standard_planner() function twice,
* since it modifies the first argument (Query *), the second call
* would trigger an assertion failure.
*/
#if PG_VERSION_NUM >= 170000
nesting_level++;
#else
plan_nested_level++;
#endif
PG_TRY();
{
if (planner_hook_next)
result = planner_hook_next(parse, query_string, cursorOptions, boundParams);
else
result = standard_planner(parse, query_string, cursorOptions, boundParams);
}
PG_FINALLY();
{
#if PG_VERSION_NUM >= 170000