-
Notifications
You must be signed in to change notification settings - Fork 15
/
pg_stat_plans.c
2816 lines (2486 loc) · 70.4 KB
/
pg_stat_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_plans.c
* Track plan execution times across a whole database cluster.
*
* Execution costs are totalled for each distinct source plan, and kept in a
* shared hashtable. (We track only as many distinct plans as will fit in the
* designated amount of shared memory.)
*
* Normalization is implemented by fingerprinting plans, selectively
* serializing those fields of each plans's nodes that are judged to be
* essential to the plan.
*
* This jumble is acquired within executor hooks at execution time.
*
* Note about locking issues: to create or delete an entry in the shared
* hashtable, one must hold pgsp->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.
*
*
* Portions Copyright (c) 2013, 2ndQuadrant Ltd.
* Portions Copyright (c) 2008-2012, PostgreSQL Global Development Group
*
* IDENTIFICATION
* pg_stat_plans/pg_stat_plans.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <unistd.h>
#include "access/hash.h"
#include "executor/instrument.h"
#include "catalog/namespace.h"
#include "commands/explain.h"
#include "executor/spi.h"
#include "funcapi.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/print.h"
#include "pgstat.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/spin.h"
#include "tcop/utility.h"
#include "utils/builtins.h"
#include "utils/formatting.h"
#include "utils/memutils.h"
#if PG_VERSION_NUM >= 90100
#include "catalog/pg_collation.h"
#endif
PG_MODULE_MAGIC;
/* Location of stats file */
#define PGSP_DUMP_FILE "global/pg_stat_plans.stat"
/* This constant defines the magic number in the stats file header */
static const uint32 PGSP_FILE_HEADER = 0x20121227;
/* 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 USAGE_DECREASE_FACTOR (0.99) /* decreased every entry_dealloc */
#define JUMBLE_SIZE 1024 /* plan jumble size */
#define USAGE_DEALLOC_PERCENT 5 /* free this % of entries at once */
/* pgsp entry state flags */
#define PGSP_VALID (1 << 0) /* String produces same plan */
#define PGSP_PREPARED (1 << 1) /* Entry from prepared query */
#define PGSP_TRUNCATED (1 << 2) /* SQL string truncated */
#define PGSP_UTILITY (1 << 3) /* Optimizable utility */
/*
* Hashtable key that defines the identity of a hashtable entry. We separate
* queries by user and by database even if they are otherwise identical.
*
* Presently, the query encoding is fully determined by the source database
* and so we don't really need it to be in the key. But that might not always
* be true. Anyway it's notationally convenient to pass it as part of the key.
*/
typedef struct pgspHashKey
{
Oid planid; /* plan "OID" */
Oid userid; /* user OID */
Oid dbid; /* database OID */
int encoding; /* query encoding */
} pgspHashKey;
/*
* The actual stats counters kept within pgspEntry.
*/
typedef struct Counters
{
int64 calls; /* # of times executed */
double total_time; /* total execution 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_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_written; /* # of local disk blocks written */
int64 temp_blks_read; /* # of temp blocks read */
int64 temp_blks_written; /* # of temp blocks written */
double last_startup_cost; /* last plan startup cost */
double last_total_cost; /* last plan total cost */
#if PG_VERSION_NUM >= 90200
double blk_read_time; /* time spent reading, in msec */
double blk_write_time; /* time spent writing, in msec */
#endif
double usage; /* usage factor */
} Counters;
/*
* Statistics per plan
*
* NB: see the file read/write code before changing field order here.
*/
typedef struct pgspEntry
{
pgspHashKey key; /* hash key of entry - MUST BE FIRST */
Counters counters; /* the statistics for this query */
int query_len; /* # of valid bytes in query string */
Oid spath_xor; /* XOR of search_path during first execution */
uint8 query_flags; /* Flags for query (validity, etc) */
slock_t mutex; /* protects the counters only */
char query[1]; /* VARIABLE LENGTH ARRAY - MUST BE LAST */
/* Note: the allocated length of query[] is actually pgsp->query_size */
} pgspEntry;
/*
* Global shared state
*/
typedef struct pgspSharedState
{
LWLockId lock; /* protects hashtable search/modification */
int query_size; /* max query length in bytes */
} pgspSharedState;
/*
* Working state for computing a query jumble and producing a normalized
* query string
*/
typedef struct pgspJumbleState
{
/* Jumble of current query tree */
unsigned char *jumble;
/* Number of bytes used in jumble[] */
Size jumble_len;
} pgspJumbleState;
/*---- Local variables ----*/
typedef enum
{
PGSP_NO_EXPLAIN = 0,
PGSP_EXPLAIN_TEXT,
PGSP_EXPLAIN_TREE
} PGSPExplainLevel;
/* Current nesting depth of ExecutorRun calls */
static int nested_level = 0;
/* Current query's explain text */
static char *explain_text = NULL;
/* whether currently explaining query */
static PGSPExplainLevel pgsp_explaining = PGSP_NO_EXPLAIN;
/*
* Certain queries will result in multiple plans at the same execution level
* (multiple invocations of the executor hooks). To differentiate these plans
* when explaining, we temporarily store the query (along with "EXPLAIN...")
* here. This is a little grotty, but apparently unavoidable.
*/
static char* explain_sql_text = NULL;
#if PG_VERSION_NUM >= 90100
/* current XOR'd search_path representation for backend */
static Oid search_path_xor = 0;
/* Is search_path_xor initialized? */
static bool search_path_xor_initialized = false;
#endif
/* Saved hook values in case of unload */
static shmem_startup_hook_type prev_shmem_startup_hook = NULL;
static ExecutorStart_hook_type prev_ExecutorStart = NULL;
static ExecutorRun_hook_type prev_ExecutorRun = NULL;
#if PG_VERSION_NUM >= 90100
static ExecutorFinish_hook_type prev_ExecutorFinish = NULL;
#endif
static ExecutorEnd_hook_type prev_ExecutorEnd = NULL;
static ProcessUtility_hook_type prev_ProcessUtility = NULL;
/* Links to shared memory state */
static pgspSharedState *pgsp = NULL;
static HTAB *pgsp_hash = NULL;
/*---- GUC variables ----*/
typedef enum
{
PGSP_TRACK_NONE, /* track no plans */
PGSP_TRACK_TOP, /* only top level plans */
PGSP_TRACK_ALL /* all plans, including nested ones */
} PGSPTrackLevel;
static const struct config_enum_entry track_options[] =
{
{"none", PGSP_TRACK_NONE, false},
{"top", PGSP_TRACK_TOP, false},
{"all", PGSP_TRACK_ALL, false},
{NULL, 0, false}
};
static const struct config_enum_entry format_options[] = {
{"text", EXPLAIN_FORMAT_TEXT, false},
{"xml", EXPLAIN_FORMAT_XML, false},
{"json", EXPLAIN_FORMAT_JSON, false},
{"yaml", EXPLAIN_FORMAT_YAML, false},
{NULL, 0, false}
};
static int pgsp_max; /* max # plans to track */
static int pgsp_track; /* tracking level */
static bool pgsp_save; /* whether to save stats across shutdown */
static bool pgsp_planid_notice; /* whether to give planid NOTICE */
static int pgsp_explain_format;/* Format for pg_stat_plans_explain() */
static bool pgsp_verbose; /* Should EXPLAIN be verbose? */
static Oid pgsp_planid = -1; /* last planid explained for backend */
static int plans_query_size; /* Size of stored query text */
#define pgsp_enabled() \
(pgsp_track == PGSP_TRACK_ALL || \
(pgsp_track == PGSP_TRACK_TOP && nested_level == 0))
/*---- Function declarations ----*/
void _PG_init(void);
void _PG_fini(void);
Datum pg_stat_plans_reset(PG_FUNCTION_ARGS);
Datum pg_stat_plans(PG_FUNCTION_ARGS);
text *pg_stat_plans_explain(PG_FUNCTION_ARGS);
text *pg_stat_plans_pprint(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(pg_stat_plans_reset);
PG_FUNCTION_INFO_V1(pg_stat_plans);
PG_FUNCTION_INFO_V1(pg_stat_plans_explain);
PG_FUNCTION_INFO_V1(pg_stat_plans_pprint);
static void pgsp_shmem_startup(void);
static void pgsp_shmem_shutdown(int code, Datum arg);
static void pgsp_ExecutorStart(QueryDesc *queryDesc, int eflags);
static void pgsp_ExecutorRun(QueryDesc *queryDesc,
ScanDirection direction,
long count);
#if PG_VERSION_NUM >= 90100
static void pgsp_ExecutorFinish(QueryDesc *queryDesc);
#endif
static void pgsp_ExecutorEnd(QueryDesc *queryDesc);
#if PG_VERSION_NUM >= 90100
static void pgsp_ProcessUtility(Node *parsetree, const char *queryString,
#if PG_VERSION_NUM >= 90300
ProcessUtilityContext context,
#endif
ParamListInfo params,
#if PG_VERSION_NUM < 90300
bool isTopLevel, DestReceiver *dest,
char *completionTag
#else
DestReceiver *dest, char *completionTag
#endif
);
#endif
static uint32 pgsp_hash_fn(const void *key, Size keysize);
static int pgsp_match_fn(const void *key1, const void *key2, Size keysize);
static void pgsp_store(const char *query, Oid planId,
double total_time, uint64 rows,
double startup_cost, double total_cost,
const BufferUsage *bufusage,
bool prepared, bool utility);
static char *pgsp_explain(QueryDesc *queryDesc);
static Oid get_search_path_xor(void);
static Size pgsp_memsize(void);
static pgspEntry *entry_alloc(pgspHashKey *key, const char *query,
int query_len);
static void entry_dealloc(void);
static void entry_reset(void);
static void AppendJumble(pgspJumbleState *jstate,
const unsigned char *item, Size size);
static void JumblePlan(pgspJumbleState *jstate, PlannedStmt *plan);
static void JumbleRangeTable(pgspJumbleState *jstate, List *rtable);
static void JumblePlanHeader(pgspJumbleState *jstate, Plan *plan);
static void JumbleScanHeader(pgspJumbleState *jstate, Scan *scan);
static void JumbleExpr(pgspJumbleState *jstate, Node *node);
/*
* 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_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_plans.max",
"Sets the maximum number of plans tracked by pg_stat_plans.",
NULL,
&pgsp_max,
1000,
100,
INT_MAX,
PGC_POSTMASTER,
0,
NULL,
NULL
#if PG_VERSION_NUM >= 90100
,NULL
#endif
);
DefineCustomIntVariable("pg_stat_plans.plans_query_size",
"Size of stored SQL query text.",
NULL,
&plans_query_size,
2048,
256,
INT_MAX,
PGC_POSTMASTER,
0,
NULL,
NULL
#if PG_VERSION_NUM >= 90100
,NULL
#endif
);
DefineCustomEnumVariable("pg_stat_plans.track",
"Selects which plans are tracked by pg_stat_plans.",
NULL,
&pgsp_track,
PGSP_TRACK_TOP,
track_options,
PGC_SUSET,
0,
NULL,
NULL
#if PG_VERSION_NUM >= 90100
,NULL
#endif
);
DefineCustomBoolVariable("pg_stat_plans.save",
"Save pg_stat_plans statistics across server "
"shutdowns.",
NULL,
&pgsp_save,
true,
PGC_SIGHUP,
0,
NULL,
NULL
#if PG_VERSION_NUM >= 90100
,NULL
#endif
);
DefineCustomBoolVariable("pg_stat_plans.planid_notice",
"Raise notice of a plan's id after its execution. "
"Useful for verifying explain output.",
NULL,
&pgsp_planid_notice,
false,
PGC_USERSET,
0,
NULL,
NULL
#if PG_VERSION_NUM >= 90100
,NULL
#endif
);
DefineCustomEnumVariable("pg_stat_plans.explain_format",
"EXPLAIN format to be used for "
"pg_stat_plans_explain().",
NULL,
&pgsp_explain_format,
EXPLAIN_FORMAT_TEXT,
format_options,
PGC_SUSET,
0,
NULL,
NULL
#if PG_VERSION_NUM >= 90100
,NULL
#endif
);
DefineCustomBoolVariable("pg_stat_plans.verbose",
"EXPLAIN verbosity to be used for "
"pg_stat_plans_explain().",
NULL,
&pgsp_verbose,
false,
PGC_USERSET,
0,
NULL,
NULL
#if PG_VERSION_NUM >= 90100
,NULL
#endif
);
EmitWarningsOnPlaceholders("pg_stat_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 pgsp_shmem_startup().
*/
RequestAddinShmemSpace(pgsp_memsize());
RequestAddinLWLocks(1);
/*
* Install hooks.
*/
prev_shmem_startup_hook = shmem_startup_hook;
shmem_startup_hook = pgsp_shmem_startup;
prev_ExecutorStart = ExecutorStart_hook;
ExecutorStart_hook = pgsp_ExecutorStart;
prev_ExecutorRun = ExecutorRun_hook;
ExecutorRun_hook = pgsp_ExecutorRun;
#if PG_VERSION_NUM >= 90100
prev_ExecutorFinish = ExecutorFinish_hook;
ExecutorFinish_hook = pgsp_ExecutorFinish;
#endif
prev_ExecutorEnd = ExecutorEnd_hook;
ExecutorEnd_hook = pgsp_ExecutorEnd;
prev_ProcessUtility = ProcessUtility_hook;
#if PG_VERSION_NUM >= 90100
ProcessUtility_hook = pgsp_ProcessUtility;
#endif
}
/*
* Module unload callback
*/
void
_PG_fini(void)
{
/* Uninstall hooks. */
shmem_startup_hook = prev_shmem_startup_hook;
ExecutorStart_hook = prev_ExecutorStart;
ExecutorRun_hook = prev_ExecutorRun;
#if PG_VERSION_NUM >= 90100
ExecutorFinish_hook = prev_ExecutorFinish;
#endif
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.
*/
static void
pgsp_shmem_startup(void)
{
bool found;
HASHCTL info;
FILE *file;
uint32 header;
int32 num;
int32 i;
int query_size;
int buffer_size;
char *buffer = NULL;
if (prev_shmem_startup_hook)
prev_shmem_startup_hook();
/* reset in case this is a restart within the postmaster */
pgsp = NULL;
pgsp_hash = NULL;
/*
* Create or attach to the shared memory state, including hash table
*/
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
pgsp = ShmemInitStruct("pg_stat_plans",
sizeof(pgspSharedState),
&found);
if (!found)
{
/* First time through ... */
pgsp->lock = LWLockAssign();
pgsp->query_size = plans_query_size;
}
/* Be sure everyone agrees on the hash table entry size */
query_size = pgsp->query_size;
memset(&info, 0, sizeof(info));
info.keysize = sizeof(pgspHashKey);
info.entrysize = offsetof(pgspEntry, query) +query_size;
info.hash = pgsp_hash_fn;
info.match = pgsp_match_fn;
pgsp_hash = ShmemInitHash("pg_stat_plans hash",
pgsp_max, pgsp_max,
&info,
HASH_ELEM | HASH_FUNCTION | HASH_COMPARE);
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(pgsp_shmem_shutdown, (Datum) 0);
/*
* Attempt to load old statistics from the dump file, if this is the first
* time through and we weren't told not to.
*/
if (found || !pgsp_save)
return;
/*
* Note: we don't bother with locks here, because there should be no other
* processes running when this code is reached.
*/
file = AllocateFile(PGSP_DUMP_FILE, PG_BINARY_R);
if (file == NULL)
{
if (errno == ENOENT)
return; /* ignore not-found error */
goto error;
}
buffer_size = query_size;
buffer = (char *) palloc(buffer_size);
if (fread(&header, sizeof(uint32), 1, file) != 1 ||
header != PGSP_FILE_HEADER ||
fread(&num, sizeof(int32), 1, file) != 1)
goto error;
for (i = 0; i < num; i++)
{
pgspEntry temp;
pgspEntry *entry;
if (fread(&temp, offsetof(pgspEntry, mutex), 1, file) != 1)
goto error;
/* Encoding is the only field we can easily sanity-check */
if (!PG_VALID_BE_ENCODING(temp.key.encoding))
goto error;
/* Previous incarnation might have had a larger query_size */
if (temp.query_len >= buffer_size)
{
buffer = (char *) repalloc(buffer, temp.query_len + 1);
buffer_size = temp.query_len + 1;
}
if (fread(buffer, 1, temp.query_len, file) != temp.query_len)
goto error;
buffer[temp.query_len] = '\0';
/* Clip to available length if needed */
if (temp.query_len >= query_size)
temp.query_len = pg_encoding_mbcliplen(temp.key.encoding,
buffer,
temp.query_len,
query_size - 1);
/* make the hashtable entry (discards old entries if too many) */
entry = entry_alloc(&temp.key, buffer, temp.query_len);
/* copy in the actual stats */
entry->counters = temp.counters;
}
pfree(buffer);
FreeFile(file);
/*
* Remove the file so it's not included in backups/replication slaves,
* etc. A new file will be written on next shutdown.
*/
unlink(PGSP_DUMP_FILE);
return;
error:
ereport(LOG,
(errcode_for_file_access(),
errmsg("could not read pg_stat_plans file \"%s\": %m",
PGSP_DUMP_FILE)));
if (buffer)
pfree(buffer);
if (file)
FreeFile(file);
/* If possible, throw away the bogus file; ignore any error */
unlink(PGSP_DUMP_FILE);
}
/*
* 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
pgsp_shmem_shutdown(int code, Datum arg)
{
FILE *file;
HASH_SEQ_STATUS hash_seq;
int32 num_entries;
pgspEntry *entry;
/* Don't try to dump during a crash. */
if (code)
return;
/* Safety check ... shouldn't get here unless shmem is set up. */
if (!pgsp || !pgsp_hash)
return;
/* Don't dump if told not to. */
if (!pgsp_save)
return;
file = AllocateFile(PGSP_DUMP_FILE ".tmp", PG_BINARY_W);
if (file == NULL)
goto error;
if (fwrite(&PGSP_FILE_HEADER, sizeof(uint32), 1, file) != 1)
goto error;
num_entries = hash_get_num_entries(pgsp_hash);
if (fwrite(&num_entries, sizeof(int32), 1, file) != 1)
goto error;
hash_seq_init(&hash_seq, pgsp_hash);
while ((entry = hash_seq_search(&hash_seq)) != NULL)
{
int len = entry->query_len;
if (fwrite(entry, offsetof(pgspEntry, mutex), 1, file) != 1 ||
fwrite(entry->query, 1, len, file) != len)
goto error;
}
if (FreeFile(file))
{
file = NULL;
goto error;
}
/*
* Rename file into place, so we atomically replace the old one.
*/
if (rename(PGSP_DUMP_FILE ".tmp", PGSP_DUMP_FILE) != 0)
ereport(LOG,
(errcode_for_file_access(),
errmsg("could not rename pg_stat_plans file \"%s\": %m",
PGSP_DUMP_FILE ".tmp")));
return;
error:
ereport(LOG,
(errcode_for_file_access(),
errmsg("could not write pg_stat_plans file \"%s\": %m",
PGSP_DUMP_FILE ".tmp")));
if (file)
FreeFile(file);
unlink(PGSP_DUMP_FILE ".tmp");
}
/*
* ExecutorStart hook: start up tracking if needed
*/
static void
pgsp_ExecutorStart(QueryDesc *queryDesc, int eflags)
{
#if PG_VERSION_NUM >= 90100
if (!search_path_xor_initialized)
{
/* Initialize search_path_xor */
search_path_xor = get_search_path_xor();
/*
* XXX: search_path might get changed within postgresql.conf, without a
* restart, and we'd have the wrong idea about our current search_path.
* We don't even support search_path protection on Postgres 9.0.
*
* There doesn't appear to be a better-principled approach that can be
* used while targeting back-branches, though.
*
* Do this here so that if the first query the backend executes queries
* the pg_stat_plans_explain function, it will still see that
* search_path matches.
*/
search_path_xor_initialized = true;
}
Assert(search_path_xor != 0);
#endif
if (pgsp_explaining)
queryDesc->instrument_options |= INSTRUMENT_TIMER;
if (prev_ExecutorStart)
prev_ExecutorStart(queryDesc, eflags);
else
standard_ExecutorStart(queryDesc, eflags);
if (pgsp_enabled() || (pgsp_explaining && nested_level == 1))
{
/*
* 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);
queryDesc->totaltime = InstrAlloc(1, INSTRUMENT_ALL);
MemoryContextSwitchTo(oldcxt);
}
}
}
/*
* ExecutorRun hook: all we need do is track nesting depth
*/
static void
pgsp_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, long count)
{
nested_level++;
PG_TRY();
{
if (prev_ExecutorRun)
prev_ExecutorRun(queryDesc, direction, count);
else
standard_ExecutorRun(queryDesc, direction, count);
nested_level--;
}
PG_CATCH();
{
nested_level--;
PG_RE_THROW();
}
PG_END_TRY();
}
#if PG_VERSION_NUM >= 90100
/*
* ExecutorFinish hook: all we need do is track nesting depth
*/
static void
pgsp_ExecutorFinish(QueryDesc *queryDesc)
{
nested_level++;
PG_TRY();
{
if (prev_ExecutorFinish)
prev_ExecutorFinish(queryDesc);
else
standard_ExecutorFinish(queryDesc);
nested_level--;
}
PG_CATCH();
{
nested_level--;
PG_RE_THROW();
}
PG_END_TRY();
}
#endif
/*
* ExecutorEnd hook: store results if needed
*/
static void
pgsp_ExecutorEnd(QueryDesc *queryDesc)
{
Oid planId = 0;
/* Setup common to cost aggregation and explain cases */
if (queryDesc->totaltime &&
(pgsp_enabled() || (pgsp_explaining && nested_level == 1)))
{
pgspJumbleState jstate;
/* Set up workspace for plan jumbling */
jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
jstate.jumble_len = 0;
/*
* Make sure stats accumulation is done. (Note: it's okay if several
* levels of hook all do this.)
*/
InstrEndLoop(queryDesc->totaltime);
/* Compute plan ID */
JumblePlan(&jstate, queryDesc->plannedstmt);
/* Avoid cast from int */
planId |= hash_any(jstate.jumble, jstate.jumble_len);
}
/* Aggregate costs... */
if (!pgsp_explaining && queryDesc->totaltime && pgsp_enabled())
{
bool is_utility = (queryDesc->operation == CMD_UTILITY ||
queryDesc->plannedstmt->utilityStmt != NULL);
/*
* Convert timing to msec (all supported pg versions use usec
* internally)
*/
pgsp_store(queryDesc->sourceText,
planId,
queryDesc->totaltime->total * 1000.0,
queryDesc->estate->es_processed,
queryDesc->plannedstmt->planTree->startup_cost,
queryDesc->plannedstmt->planTree->total_cost,
&queryDesc->totaltime->bufusage,
queryDesc->params != NULL,
is_utility);
if (pgsp_planid_notice)
ereport(NOTICE,
(errmsg("planid: %u", planId)));
#ifdef STAT_PLANS_DEBUG
/* Pretty-print tree */
printf("Dumping plan %u after plan_store", planId);
pprint(queryDesc->plannedstmt);
#endif
}
/* ...xor explaining a query */
else if (pgsp_explaining && nested_level == 1 &&
(explain_sql_text &&
strcmp(explain_sql_text, queryDesc->sourceText) == 0))
{
/*
* Save explain text or string representation of plan tree to a cstring
* in the top memory context.
*/
MemoryContext mct = MemoryContextSwitchTo(TopMemoryContext);
if (pgsp_explaining == PGSP_EXPLAIN_TEXT)
explain_text = pgsp_explain(queryDesc);
else if(pgsp_explaining == PGSP_EXPLAIN_TREE)
explain_text = nodeToString(queryDesc->plannedstmt);
/* Save planId for later validation */
pgsp_planid = planId;
MemoryContextSwitchTo(mct);
pgsp_explaining = PGSP_NO_EXPLAIN;
#ifdef STAT_PLANS_DEBUG
/* Pretty-print tree */
printf("Dumping plan %u after explaining", pgsp_planid);
pprint(queryDesc->plannedstmt);
#endif
}
if (prev_ExecutorEnd)
prev_ExecutorEnd(queryDesc);
else
standard_ExecutorEnd(queryDesc);
}
/*
* ProcessUtility hook
*
* Unlike pg_stat_statements, pg_stat_plans doesn't care about non-optimizable
* statements (i.e. most utility statements).
*
* However, this is how we try and monitor if search_path is set by
* applications, to enforce that the original query execution's search_path
* matches our own when explaining stored query text. This is obviously
* a kludge, but it seems to be the only mechanism available to do this.
*/
#if PG_VERSION_NUM >= 90100
static void
pgsp_ProcessUtility(Node *parsetree, const char *queryString,
#if PG_VERSION_NUM >= 90300
ProcessUtilityContext context,
#endif
ParamListInfo params,
#if PG_VERSION_NUM < 90300
bool isTopLevel, DestReceiver *dest,
char *completionTag
#else
DestReceiver *dest, char *completionTag
#endif
)
{
#if PG_VERSION_NUM < 90300
if (prev_ProcessUtility)
prev_ProcessUtility(parsetree, queryString, params,
isTopLevel, dest, completionTag);
else
standard_ProcessUtility(parsetree, queryString, params,
isTopLevel, dest, completionTag);
#else
if (prev_ProcessUtility)
prev_ProcessUtility(parsetree, queryString, context, params,
dest, completionTag);
else
standard_ProcessUtility(parsetree, queryString, context, params,
dest, completionTag);
#endif
if (IsA(parsetree, VariableSetStmt))
{
VariableSetStmt *v = (VariableSetStmt *) parsetree;
if (!v->name || strcmp(v->name, "search_path") == 0)
{
/* search_path changed - update current search_path for backend. */
search_path_xor = get_search_path_xor();
}
}
}
#endif
/*
* Calculate hash value for a key
*/
static uint32
pgsp_hash_fn(const void *key, Size keysize)
{
const pgspHashKey *k = (const pgspHashKey *) key;
/* we don't bother to include encoding in the hash */
return hash_uint32((uint32) k->userid) ^
hash_uint32((uint32) k->dbid) ^
hash_uint32((uint32) k->planid);
}
/*
* Compare two keys - zero means match
*/
static int
pgsp_match_fn(const void *key1, const void *key2, Size keysize)
{
const pgspHashKey *k1 = (const pgspHashKey *) key1;
const pgspHashKey *k2 = (const pgspHashKey *) key2;
if (k1->userid == k2->userid &&
k1->dbid == k2->dbid &&
k1->encoding == k2->encoding &&
k1->planid == k2->planid)
return 0;
else
return 1;
}
/*
* Store some statistics for a plans.
*/
static void
pgsp_store(const char *query, Oid planId,
double total_time, uint64 rows,
double startup_cost, double total_cost,
const BufferUsage *bufusage,
bool prepared, bool utility)
{
pgspHashKey key;
pgspEntry *entry;
int query_len;
Assert(query != NULL);