-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpg_stat_sql_plans.c
2909 lines (2546 loc) · 81.1 KB
/
pg_stat_sql_plans.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_sql_plans.c
* Track statement execution times across a whole database cluster.
*
* Execution costs are totalled for each distinct source query, and kept in
* a shared hashtable. (We track only as many distinct queries as will fit
* in the designated amount of shared memory.)
*
* As of Postgres 9.2, this module normalizes query entries. Normalization
* is a process whereby similar queries, typically differing only in their
* constants (though the exact rules are somewhat more subtle than that) are
* recognized as equivalent, and are tracked as a single entry. This is
* particularly useful for non-prepared queries.
*
* To save on shared memory, and to avoid having to truncate oversized query
* strings, we store these strings in a temporary external query-texts file.
* Offsets into this file are kept in shared memory.
*
* Note about locking issues: to create or delete an entry in the shared
* hashtable, one must hold pgssp->lock exclusively. Modifying any field
* in an entry except the counters requires the same. To look up an entry,
* one must hold the lock shared. To read or update the counters within
* an entry, one must hold the lock shared or exclusive (so the entry doesn't
* disappear!) and also take the entry's mutex spinlock.
* The shared state variable pgssp->extent (the next free spot in the external
* query-text file) should be accessed only while holding either the
* pgssp->mutex spinlock, or exclusive lock on pgssp->lock. We use the mutex to
* allow reserving file space while holding only shared lock on pgssp->lock.
* Rewriting the entire external query-text file, eg for garbage collection,
* requires holding pgssp->lock exclusively; this allows individual entries
* in the file to be read or written while holding only shared lock.
*
*
* Copyright (c) 2008-2018, PostgreSQL Global Development Group
*
* IDENTIFICATION
* contrib/pg_stat_sql_plans/pg_stat_sql_plans.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <math.h>
#include <sys/stat.h>
#include <unistd.h>
#include "access/hash.h"
#include "access/twophase.h"
#include "catalog/pg_authid.h"
#include "commands/explain.h"
#include "executor/instrument.h"
#include "funcapi.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "optimizer/planner.h"
#include "parser/analyze.h"
#include "parser/parsetree.h"
#include "parser/scanner.h"
#include "parser/scansup.h"
#include "parser/gram.h"
#include "pgstat.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/spin.h"
#include "storage/proc.h"
#include "tcop/utility.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "utils/timestamp.h"
PG_MODULE_MAGIC;
/* Location of permanent stats file (valid when database is shut down) */
#define pgssp_DUMP_FILE PGSTAT_STAT_PERMANENT_DIRECTORY "/pg_stat_sql_plans.stat"
/*
* Location of external query text file. We don't keep it in the core
* system's stats_temp_directory. The core system can safely use that GUC
* setting, because the statistics collector temp file paths are set only once
* as part of changing the GUC, but pg_stat_sql_plans has no way of avoiding
* race conditions. Besides, we only expect modest, infrequent I/O for query
* strings, so placing the file on a faster filesystem is not compelling.
*/
#define pgssp_TEXT_FILE PG_STAT_TMP_DIR "/pgssp_query_texts.stat"
/* Magic number identifying the stats file format */
static const uint32 pgssp_FILE_HEADER = 0x20171004;
/* PostgreSQL major version number, changes in which invalidate all entries */
static const uint32 pgssp_PG_MAJOR_VERSION = PG_VERSION_NUM / 100;
/* XXX: Should USAGE_EXEC reflect execution time and/or buffer usage? */
//#define USAGE_EXEC(duration) (1.0)
//#define USAGE_INIT (1.0) /* including initial planning */
#define ASSUMED_MEDIAN_INIT (10.0) /* initial assumed median usage */
#define ASSUMED_LENGTH_INIT 1024 /* initial assumed mean query length */
//#define USAGE_DECREASE_FACTOR (0.99) /* decreased every entry_dealloc */
//#define STICKY_DECREASE_FACTOR (0.50) /* factor for sticky entries */
#define USAGE_DEALLOC_PERCENT 5 /* free this % of entries at once */
/*
* Extension version number, for supporting older extension versions' objects
*/
typedef enum pgsspVersion
{
pgssp_V1_0 = 0,
pgssp_V1_1,
pgssp_V1_2,
pgssp_V1_3
} pgsspVersion;
/*
* Hashtable key that defines the identity of a hashtable entry. We separate
* queries by user and by database even if they are otherwise identical.
*
* Right now, this structure contains no padding. If you add any, make sure
* to teach pgssp_store() to zero the padding bytes. Otherwise, things will
* break, because pgssp_hash is created using HASH_BLOBS, and thus tag_hash
* is used to hash this.
*/
typedef struct pgsspHashKey
{
Oid userid; /* user OID */
Oid dbid; /* database OID */
uint64 qpid; /* extension identifier, combination of queryid and planid */
} pgsspHashKey;
/*
* The actual stats counters kept within pgsspEntry.
*/
typedef struct Counters
{
uint64 queryid; /* query identifier */
uint64 planid; /* plan identifier */
int64 plans; /* # of times planned */
int64 calls; /* # of times executed */
double total_time; /* total execution time, in msec */
double min_time; /* minimum execution time in msec */
double max_time; /* maximum execution time in msec */
double mean_time; /* mean execution time in msec */
double sum_var_time; /* sum of variances in execution time in msec */
double plan_time; /* total planing time, in msec */
double exec_time; /* total execution time, in msec */
double extn_time; /* total pgssp time, in msec */
int64 rows; /* total # of retrieved or affected rows */
int64 shared_blks_hit; /* # of shared buffer hits */
int64 shared_blks_read; /* # of shared disk blocks read */
int64 shared_blks_dirtied; /* # of shared disk blocks dirtied */
int64 shared_blks_written; /* # of shared disk blocks written */
int64 local_blks_hit; /* # of local buffer hits */
int64 local_blks_read; /* # of local disk blocks read */
int64 local_blks_dirtied; /* # of local disk blocks dirtied */
int64 local_blks_written; /* # of local disk blocks written */
int64 temp_blks_read; /* # of temp blocks read */
int64 temp_blks_written; /* # of temp blocks written */
double blk_read_time; /* time spent reading, in msec */
double blk_write_time; /* time spent writing, in msec */
TimestampTz first_call; /* timestamp of first call */
TimestampTz last_call; /* timestamp of last call */
} Counters;
/*
* Statistics per statement
*
* Note: in event of a failure in garbage collection of the query text file,
* we reset query_offset to zero and query_len to -1. This will be seen as
* an invalid state by qtext_fetch().
*/
typedef struct pgsspEntry
{
pgsspHashKey key; /* hash key of entry - MUST BE FIRST */
Counters counters; /* the statistics for this query */
Size query_offset; /* query text offset in external file */
int query_len; /* # of valid bytes in query string, or -1 */
int encoding; /* query text encoding */
slock_t mutex; /* protects the counters only */
} pgsspEntry;
/*
* Global shared state
*/
typedef struct pgsspSharedState
{
LWLock *lock; /* protects hashtable search/modification */
double cur_median_usage; /* current median usage in hashtable */
Size mean_query_len; /* current mean entry text length */
slock_t mutex; /* protects following fields only: */
Size extent; /* current extent of query file */
int n_writers; /* number of active writers to query file */
int gc_count; /* query file garbage collection cycle count */
} pgsspSharedState;
/*
* Struct for tracking locations/lengths of constants during normalization
*/
typedef struct pgsspLocationLen
{
int location; /* start offset in query text */
int length; /* length in bytes, or -1 to ignore */
} pgsspLocationLen;
/* get max procs */
static int get_max_procs_count(void);
/* Proc entry */
typedef struct procEntry
{
uint64 qpid;
} procEntry;
/*---- Local variables ----*/
/* Current nesting depth of ExecutorRun+ProcessUtility calls */
static int nested_level = 0;
/* Saved hook values in case of unload */
static shmem_startup_hook_type prev_shmem_startup_hook = NULL;
static planner_hook_type prev_planner_hook = NULL;
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;
/* Links to shared memory state */
static pgsspSharedState *pgssp = NULL;
static HTAB *pgssp_hash = NULL;
/*---- GUC variables ----*/
typedef enum
{
pgssp_TRACK_NONE, /* track no statements */
pgssp_TRACK_TOP, /* only top level statements */
pgssp_TRACK_ALL /* all statements, including nested ones */
} pgsspTrackLevel;
static const struct config_enum_entry track_options[] =
{
{"none", pgssp_TRACK_NONE, false},
{"top", pgssp_TRACK_TOP, false},
{"all", pgssp_TRACK_ALL, false},
{NULL, 0, false}
};
typedef enum
{
pgssp_PLAN_NONE, /* track no plan*/
pgssp_PLAN_STD /* track explain plans (costs off) */
} pgsspPlanType;
static const struct config_enum_entry plan_type_options[] =
{
{"none", pgssp_PLAN_NONE, false},
{"standard", pgssp_PLAN_STD, false},
{NULL, 0, false}
};
static int pgssp_max; /* max # statements to track */
static int pgssp_track; /* tracking level */
static bool pgssp_track_utility; /* whether to track utility commands */
static bool pgssp_track_errors; /* whether to track statements in error */
static int pgssp_plan_type; /* how to track plan id */
static bool pgssp_explain; /* whether to explain query */
static bool pgssp_track_pid; /* whether to track collected data per pid */
static bool pgssp_save; /* whether to save stats across shutdown */
#define pgssp_enabled() \
(pgssp_track == pgssp_TRACK_ALL || \
(pgssp_track == pgssp_TRACK_TOP && nested_level == 0))
#define record_gc_qtexts() \
do { \
volatile pgsspSharedState *s = (volatile pgsspSharedState *) pgssp; \
SpinLockAcquire(&s->mutex); \
s->gc_count++; \
SpinLockRelease(&s->mutex); \
} while(0)
/*---- Function declarations ----*/
void _PG_init(void);
void _PG_fini(void);
PG_FUNCTION_INFO_V1(pg_stat_sql_plans_reset);
PG_FUNCTION_INFO_V1(pg_stat_sql_plans_1_2);
PG_FUNCTION_INFO_V1(pg_stat_sql_plans_1_3);
PG_FUNCTION_INFO_V1(pg_stat_sql_plans);
PG_FUNCTION_INFO_V1(pgssp_normalize_query);
PG_FUNCTION_INFO_V1(pgssp_backend_qpid);
static void pgssp_shmem_startup(void);
static void pgssp_shmem_shutdown(int code, Datum arg);
static PlannedStmt *pgssp_planner(Query *parse,
const char *query_string,
int cursorOptions,
ParamListInfo boundParams);
static void pgssp_post_parse_analyze(ParseState *pstate, Query *query,
JumbleState *jstate);
static void pgssp_ExecutorStart(QueryDesc *queryDesc, int eflags);
static void pgssp_ExecutorRun(QueryDesc *queryDesc,
ScanDirection direction,
uint64 count, bool execute_once);
static void pgssp_ExecutorFinish(QueryDesc *queryDesc);
static void pgssp_ExecutorEnd(QueryDesc *queryDesc);
static void pgssp_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
bool readOnlyTree,
ProcessUtilityContext context, ParamListInfo params,
QueryEnvironment *queryEnv,
DestReceiver *dest, QueryCompletion *qc);
static uint64 pgssp_hash_string(const char *str, int len);
static void pgssp_store(const char *query, uint64 queryId,
PlannedStmt *plan, ParamListInfo params,
int query_location, int query_len,
double total_time, uint64 rows,
const BufferUsage *bufusage);
static void pg_stat_sql_plans_internal(FunctionCallInfo fcinfo,
pgsspVersion api_version,
bool showtext);
static Size pgssp_memsize(void);
static pgsspEntry *entry_alloc(pgsspHashKey *key, Size query_offset, int query_len,
int encoding);
static void entry_dealloc(void);
static bool qtext_store(const char *query, int query_len,
Size *query_offset, int *gc_count);
static char *qtext_load_file(Size *buffer_size);
static char *qtext_fetch(Size query_offset, int query_len,
char *buffer, Size buffer_size);
static bool need_gc_qtexts(void);
static void gc_qtexts(void);
static void entry_reset(void);
void normalize_expr(char *expr, bool preserve_space);
static uint64 hash_query(const char* query);
static procEntry *ProcEntryArray = NULL;
/*
* Module load callback
*/
void
_PG_init(void)
{
/*
* 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_sql_plans 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;
/*
* Define (or redefine) custom GUC variables.
*/
DefineCustomIntVariable("pg_stat_sql_plans.max",
"Sets the maximum number of statements tracked by pg_stat_sql_plans.",
NULL,
&pgssp_max,
5000,
100,
INT_MAX,
PGC_POSTMASTER,
0,
NULL,
NULL,
NULL);
DefineCustomEnumVariable("pg_stat_sql_plans.track",
"Selects which statements are tracked by pg_stat_sql_plans.",
NULL,
&pgssp_track,
pgssp_TRACK_TOP,
track_options,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("pg_stat_sql_plans.track_utility",
"Selects whether utility commands are tracked by pg_stat_sql_plans.",
NULL,
&pgssp_track_utility,
true,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("pg_stat_sql_plans.track_errors",
"Selects whether statements in error are tracked by pg_stat_sql_plans.",
NULL,
&pgssp_track_errors,
true,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
DefineCustomEnumVariable("pg_stat_sql_plans.plan_type",
"Selects which type of explain plan is used by pg_stat_sql_plans.",
NULL,
&pgssp_plan_type,
pgssp_PLAN_STD,
plan_type_options,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("pg_stat_sql_plans.explain",
"Selects whether explain query by pg_stat_sql_plans.",
NULL,
&pgssp_explain,
false,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("pg_stat_sql_plans.track_pid",
"Selects whether data by pid are collected by pg_stat_sql_plans.",
NULL,
&pgssp_track_pid,
true,
PGC_SIGHUP,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("pg_stat_sql_plans.save",
"Save pg_stat_sql_plans statistics across server shutdowns.",
NULL,
&pgssp_save,
true,
PGC_SIGHUP,
0,
NULL,
NULL,
NULL);
EmitWarningsOnPlaceholders("pg_stat_sql_plans");
/*
* 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 pgssp_shmem_startup().
*/
RequestAddinShmemSpace(pgssp_memsize());
RequestNamedLWLockTranche("pg_stat_sql_plans", 1);
/*
* Install hooks.
*/
prev_shmem_startup_hook = shmem_startup_hook;
shmem_startup_hook = pgssp_shmem_startup;
prev_planner_hook = planner_hook;
planner_hook = pgssp_planner;
prev_post_parse_analyze_hook = post_parse_analyze_hook;
post_parse_analyze_hook = pgssp_post_parse_analyze;
prev_ExecutorStart = ExecutorStart_hook;
ExecutorStart_hook = pgssp_ExecutorStart;
prev_ExecutorRun = ExecutorRun_hook;
ExecutorRun_hook = pgssp_ExecutorRun;
prev_ExecutorFinish = ExecutorFinish_hook;
ExecutorFinish_hook = pgssp_ExecutorFinish;
prev_ExecutorEnd = ExecutorEnd_hook;
ExecutorEnd_hook = pgssp_ExecutorEnd;
prev_ProcessUtility = ProcessUtility_hook;
ProcessUtility_hook = pgssp_ProcessUtility;
}
/*
* Module unload callback
*/
void
_PG_fini(void)
{
/* Uninstall hooks. */
shmem_startup_hook = prev_shmem_startup_hook;
planner_hook = prev_planner_hook;
post_parse_analyze_hook = prev_post_parse_analyze_hook;
ExecutorStart_hook = prev_ExecutorStart;
ExecutorRun_hook = prev_ExecutorRun;
ExecutorFinish_hook = prev_ExecutorFinish;
ExecutorEnd_hook = prev_ExecutorEnd;
ProcessUtility_hook = prev_ProcessUtility;
}
/*
* 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.
*/
static void
pgssp_shmem_startup(void)
{
bool found;
HASHCTL info;
FILE *file = NULL;
FILE *qfile = NULL;
uint32 header;
int32 num;
int32 pgver;
int32 i;
int buffer_size;
char *buffer = NULL;
int size;
if (prev_shmem_startup_hook)
prev_shmem_startup_hook();
/* reset in case this is a restart within the postmaster */
pgssp = NULL;
pgssp_hash = NULL;
/*
* Create or attach to the shared memory state, including hash table
*/
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
/* spécific for ProcEntryArray */
size = mul_size(sizeof(procEntry), get_max_procs_count());
ProcEntryArray = (procEntry *) ShmemInitStruct("Proc Entry Array", size, &found);
if (!found)
{
MemSet(ProcEntryArray, 0, size);
}
pgssp = ShmemInitStruct("pg_stat_sql_plans",
sizeof(pgsspSharedState),
&found);
if (!found)
{
/* First time through ... */
pgssp->lock = &(GetNamedLWLockTranche("pg_stat_sql_plans"))->lock;
pgssp->cur_median_usage = ASSUMED_MEDIAN_INIT;
pgssp->mean_query_len = ASSUMED_LENGTH_INIT;
SpinLockInit(&pgssp->mutex);
pgssp->extent = 0;
pgssp->n_writers = 0;
pgssp->gc_count = 0;
}
memset(&info, 0, sizeof(info));
info.keysize = sizeof(pgsspHashKey);
info.entrysize = sizeof(pgsspEntry);
pgssp_hash = ShmemInitHash("pg_stat_sql_plans hash",
pgssp_max, pgssp_max,
&info,
HASH_ELEM | HASH_BLOBS);
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(pgssp_shmem_shutdown, (Datum) 0);
/*
* Done if some other process already completed our initialization.
*/
if (found)
return;
/*
* Note: we don't bother with locks here, because there should be no other
* processes running when this code is reached.
*/
/* Unlink query text file possibly left over from crash */
unlink(pgssp_TEXT_FILE);
/* Allocate new query text temp file */
qfile = AllocateFile(pgssp_TEXT_FILE, PG_BINARY_W);
if (qfile == NULL)
goto write_error;
/*
* If we were told not to load old statistics, we're done. (Note we do
* not try to unlink any old dump file in this case. This seems a bit
* questionable but it's the historical behavior.)
*/
if (!pgssp_save)
{
FreeFile(qfile);
return;
}
/*
* Attempt to load old statistics from the dump file.
*/
file = AllocateFile(pgssp_DUMP_FILE, PG_BINARY_R);
if (file == NULL)
{
if (errno != ENOENT)
goto read_error;
/* No existing persisted stats file, so we're done */
FreeFile(qfile);
return;
}
buffer_size = 2048;
buffer = (char *) palloc(buffer_size);
if (fread(&header, sizeof(uint32), 1, file) != 1 ||
fread(&pgver, sizeof(uint32), 1, file) != 1 ||
fread(&num, sizeof(int32), 1, file) != 1)
goto read_error;
if (header != pgssp_FILE_HEADER ||
pgver != pgssp_PG_MAJOR_VERSION)
goto data_error;
for (i = 0; i < num; i++)
{
pgsspEntry temp;
pgsspEntry *entry;
Size query_offset;
if (fread(&temp, sizeof(pgsspEntry), 1, file) != 1)
goto read_error;
/* Encoding is the only field we can easily sanity-check */
if (!PG_VALID_BE_ENCODING(temp.encoding))
goto data_error;
/* Resize buffer as needed */
if (temp.query_len >= buffer_size)
{
buffer_size = Max(buffer_size * 2, temp.query_len + 1);
buffer = repalloc(buffer, buffer_size);
}
if (fread(buffer, 1, temp.query_len + 1, file) != temp.query_len + 1)
goto read_error;
/* Should have a trailing null, but let's make sure */
buffer[temp.query_len] = '\0';
/* Skip loading "sticky" entries */
if (temp.counters.calls == 0)
continue;
/* Store the query text */
query_offset = pgssp->extent;
if (fwrite(buffer, 1, temp.query_len + 1, qfile) != temp.query_len + 1)
goto write_error;
pgssp->extent += temp.query_len + 1;
/* make the hashtable entry (discards old entries if too many) */
entry = entry_alloc(&temp.key, query_offset, temp.query_len,
temp.encoding);
/* copy in the actual stats */
entry->counters = temp.counters;
}
pfree(buffer);
FreeFile(file);
FreeFile(qfile);
/*
* Remove the persisted stats file so it's not included in
* backups/replication slaves, etc. A new file will be written on next
* shutdown.
*
* Note: it's okay if the pgssp_TEXT_FILE is included in a basebackup,
* because we remove that file on startup; it acts inversely to
* pgssp_DUMP_FILE, in that it is only supposed to be around when the
* server is running, whereas pgssp_DUMP_FILE is only supposed to be around
* when the server is not running. Leaving the file creates no danger of
* a newly restored database having a spurious record of execution costs,
* which is what we're really concerned about here.
*/
unlink(pgssp_DUMP_FILE);
return;
read_error:
ereport(LOG,
(errcode_for_file_access(),
errmsg("could not read pg_stat_statement file \"%s\": %m",
pgssp_DUMP_FILE)));
goto fail;
data_error:
ereport(LOG,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("ignoring invalid data in pg_stat_statement file \"%s\"",
pgssp_DUMP_FILE)));
goto fail;
write_error:
ereport(LOG,
(errcode_for_file_access(),
errmsg("could not write pg_stat_statement file \"%s\": %m",
pgssp_TEXT_FILE)));
fail:
if (buffer)
pfree(buffer);
if (file)
FreeFile(file);
if (qfile)
FreeFile(qfile);
/* If possible, throw away the bogus file; ignore any error */
unlink(pgssp_DUMP_FILE);
/*
* Don't unlink pgssp_TEXT_FILE here; it should always be around while the
* server is running with pg_stat_sql_plans enabled
*/
}
/*
* shmem_shutdown hook: Dump statistics into file.
*
* Note: we don't bother with acquiring lock, because there should be no
* other processes running when this is called.
*/
static void
pgssp_shmem_shutdown(int code, Datum arg)
{
FILE *file;
char *qbuffer = NULL;
Size qbuffer_size = 0;
HASH_SEQ_STATUS hash_seq;
int32 num_entries;
pgsspEntry *entry;
/* Don't try to dump during a crash. */
if (code)
return;
/* Safety check ... shouldn't get here unless shmem is set up. */
if (!pgssp || !pgssp_hash)
return;
/* Don't dump if told not to. */
if (!pgssp_save)
return;
file = AllocateFile(pgssp_DUMP_FILE ".tmp", PG_BINARY_W);
if (file == NULL)
goto error;
if (fwrite(&pgssp_FILE_HEADER, sizeof(uint32), 1, file) != 1)
goto error;
if (fwrite(&pgssp_PG_MAJOR_VERSION, sizeof(uint32), 1, file) != 1)
goto error;
num_entries = hash_get_num_entries(pgssp_hash);
if (fwrite(&num_entries, sizeof(int32), 1, file) != 1)
goto error;
qbuffer = qtext_load_file(&qbuffer_size);
if (qbuffer == NULL)
goto error;
/*
* When serializing to disk, we store query texts immediately after their
* entry data. Any orphaned query texts are thereby excluded.
*/
hash_seq_init(&hash_seq, pgssp_hash);
while ((entry = hash_seq_search(&hash_seq)) != NULL)
{
int len = entry->query_len;
char *qstr = qtext_fetch(entry->query_offset, len,
qbuffer, qbuffer_size);
if (qstr == NULL)
qstr = "";
if (fwrite(entry, sizeof(pgsspEntry), 1, file) != 1 ||
fwrite(qstr, 1, len + 1, file) != len + 1)
{
/* note: we assume hash_seq_term won't change errno */
hash_seq_term(&hash_seq);
goto error;
}
}
free(qbuffer);
qbuffer = NULL;
if (FreeFile(file))
{
file = NULL;
goto error;
}
/*
* Rename file into place, so we atomically replace any old one.
*/
(void) durable_rename(pgssp_DUMP_FILE ".tmp", pgssp_DUMP_FILE, LOG);
/* Unlink query-texts file; it's not needed while shutdown */
unlink(pgssp_TEXT_FILE);
return;
error:
ereport(LOG,
(errcode_for_file_access(),
errmsg("could not write pg_stat_statement file \"%s\": %m",
pgssp_DUMP_FILE ".tmp")));
if (qbuffer)
free(qbuffer);
if (file)
FreeFile(file);
unlink(pgssp_DUMP_FILE ".tmp");
unlink(pgssp_TEXT_FILE);
}
/*
* Calculate max processes count.
*/
static int
get_max_procs_count(void)
{
int count = 0;
/* MyProcs, including autovacuum workers and launcher */
count += MaxBackends;
/* AuxiliaryProcs */
count += NUM_AUXILIARY_PROCS;
/* Prepared xacts */
count += max_prepared_xacts;
return count;
}
/*
* Post-parse-analysis hook: mark query with a queryId
*/
static void
pgssp_post_parse_analyze(ParseState *pstate, Query *query, JumbleState *jstate)
{
if (prev_post_parse_analyze_hook)
prev_post_parse_analyze_hook(pstate, query, jstate);
/* Assert we didn't do this already */
Assert(query->queryId == UINT64CONST(0));
/* Safety check... */
if (!pgssp || !pgssp_hash || !pgssp_enabled() )
return;
/* Update memory structure dedicated for pgssp_backend_qpid function */
if (MyProc && pgssp_track_pid )
{
int i = MyProc - ProcGlobal->allProcs;
const char *querytext = pstate->p_sourcetext;
int query_len;
int query_location = query->stmt_location;
query_len = query->stmt_len;
if (query_location >= 0)
{
Assert(query_location <= strlen(querytext));
querytext += query_location;
/* Length of 0 (or -1) means "rest of string" */
if (query_len <= 0)
query_len = strlen(querytext);
else
Assert(query_len <= strlen(querytext));
}
else
{
/* If query location is unknown, distrust query_len as well */
query_location = 0;
query_len = strlen(querytext);
}
/*
* Discard leading and trailing whitespace, too. Use scanner_isspace()
* not libc's isspace(), because we want to match the lexer's behavior.
*/
while (query_len > 0 && scanner_isspace(querytext[0]))
querytext++, query_location++, query_len--;
while (query_len > 0 && scanner_isspace(querytext[query_len - 1]))
query_len--;
/* store queryid based on utility statement text
* planned statements are updated during executor start hook
* after planid calculation in planner hook
*/
if (query->utilityStmt) {
ProcEntryArray[i].qpid = hash_combine64(pgssp_hash_string(querytext, query_len),UINT64CONST(0));
} else {
/* init with queryId value for planning phase */
ProcEntryArray[i].qpid = hash_query(pstate->p_sourcetext);
}
}
/*
* Utility statements get queryId zero. We do this even in cases where
* the statement contains an optimizable statement for which a queryId
* could be derived (such as EXPLAIN or DECLARE CURSOR). For such cases,
* runtime control will first go through ProcessUtility and then the
* executor, and we don't want the executor hooks to do anything, since we
* are already measuring the statement's costs at the utility level.
*/
if (query->utilityStmt)
{
query->queryId = UINT64CONST(0);
return;
}
/* Compute query ID and mark the Query node with it */
query->queryId = hash_query(pstate->p_sourcetext);
/*
* 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);
}
/*
* planner hook
*/
static PlannedStmt *
pgssp_planner(Query *parse,
const char *query_string,
int cursorOptions,
ParamListInfo boundParams)
{
PlannedStmt *result;
if (pgssp_enabled())
{
instr_time start;
instr_time duration;
BufferUsage bufusage;
// pgstat_report_wait_start(0x0B010000U); // gives ???-unknown wait event
pgstat_report_wait_start(0x050E0000U); // gives Activity-unknown wait event
INSTR_TIME_SET_CURRENT(start);
nested_level++;
PG_TRY();
{
if (prev_planner_hook)
result = prev_planner_hook(parse, query_string, cursorOptions, boundParams);
else
result = standard_planner(parse, query_string, cursorOptions, boundParams);
nested_level--;
}
PG_CATCH();
{
nested_level--;
PG_RE_THROW();
}
PG_END_TRY();
INSTR_TIME_SET_CURRENT(duration);
INSTR_TIME_SUBTRACT(duration, start);
bufusage.shared_blks_hit = 0;
bufusage.shared_blks_read = 0;
bufusage.shared_blks_dirtied = 0;
bufusage.shared_blks_written = 0;
bufusage.local_blks_hit = 0;
bufusage.local_blks_read = 0;
bufusage.local_blks_dirtied = 0;
bufusage.local_blks_written = 0;
bufusage.temp_blks_read = 0;
bufusage.temp_blks_written = 0;
//TODO
// INSTR_TIME_SUBTRACT(bufusage.blk_read_time, bufusage.blk_read_time);
// INSTR_TIME_SUBTRACT(bufusage.blk_write_time, bufusage.blk_write_time);
pgssp_store( query_string,
result->queryId,
result,
boundParams,
result->stmt_location,
result->stmt_len,