forked from ossc-db/pg_store_plans
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pg_store_plans.c
2354 lines (2039 loc) · 63.9 KB
/
pg_store_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_store_plans.c
* Take statistics of plan selection across a whole database cluster.
*
* Execution costs are totaled for each distinct plan for each query,
* and plan and queryid are kept in a shared hashtable, each record in
* which is associated with a record in pg_stat_statements, if any, by
* the queryid.
*
* For Postgres 9.3 or earlier does not expose query id so
* pg_store_plans needs to calculate it based on the given query
* string using different algorithm from pg_stat_statements, and later
* the id will be matched against the one made from query string
* stored in pg_stat_statements. For the reason, queryid matching in
* this way will fail if the query string kept in pg_stat_statements
* is truncated in the middle.
*
* Plans are identified by fingerprinting plan representations in
* "shortened" JSON format with constants and unstable values such as
* rows, width, loops ignored. Nevertheless, stored plan entries hold
* them of the latest execution. Entry eviction is done in the same
* way to pg_stat_statements.
*
* Copyright (c) 2008-2020, PostgreSQL Global Development Group
* Copyright (c) 2012-2021, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
*
* IDENTIFICATION
* pg_store_plans/pg_store_plans.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <sys/stat.h>
#include <unistd.h>
#include <dlfcn.h>
#include <math.h>
#include "catalog/pg_authid.h"
#include "commands/explain.h"
#include "access/hash.h"
#include "executor/instrument.h"
#include "funcapi.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/lwlock.h"
#include "storage/spin.h"
#include "storage/shmem.h"
#include "tcop/utility.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#if PG_VERSION_NUM >= 140000
#include "utils/queryjumble.h"
#endif
#include "utils/timestamp.h"
#include "pgsp_json.h"
#include "pgsp_explain.h"
PG_MODULE_MAGIC;
/* Location of stats file */
#define PGSP_DUMP_FILE "global/pg_store_plans.stat"
#define PGSP_TEXT_FILE PG_STAT_TMP_DIR "/pgsp_plan_texts.stat"
/* PostgreSQL major version number, changes in which invalidate all entries */
static const uint32 PGSP_PG_MAJOR_VERSION = PG_VERSION_NUM / 100;
/* This constant defines the magic number in the stats file header */
static const uint32 PGSP_FILE_HEADER = 0x20211125;
static int max_plan_len = 5000;
/* 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 */
/* In PostgreSQL 11, queryid becomes a uint64 internally. */
#if PG_VERSION_NUM >= 110000
typedef uint64 queryid_t;
#define PGSP_NO_QUERYID UINT64CONST(0)
#else
typedef uint32 queryid_t;
#define PGSP_NO_QUERYID 0
#endif
/*
* Extension version number, for supporting older extension versions' objects
*/
typedef enum pgspVersion
{
PGSP_V1_5 = 0,
PGSP_V1_6
} pgspVersion;
/*
* 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 userid; /* user OID */
Oid dbid; /* database OID */
queryid_t queryid; /* query identifier */
uint32 planid; /* plan identifier */
} pgspHashKey;
/*
* The actual stats counters kept within pgspEntry.
*/
typedef struct Counters
{
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 */
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 */
double usage; /* usage factor */
} Counters;
/*
* Global statistics for pg_store_plans
*/
typedef struct pgspGlobalStats
{
int64 dealloc; /* # of times entries were deallocated */
TimestampTz stats_reset; /* timestamp with all stats reset */
} pgspGlobalStats;
/*
* 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 */
Size plan_offset; /* plan text offset in extern file */
int plan_len; /* # of valid bytes in query string */
int encoding; /* query encoding */
slock_t mutex; /* protects the counters only */
} pgspEntry;
/*
* Global shared state
*/
typedef struct pgspSharedState
{
LWLock *lock; /* protects hashtable search/modification */
int plan_size; /* max query length in bytes */
double cur_median_usage; /* current median usage in hashtable */
Size mean_plan_len; /* current mean entry text length */
slock_t mutex; /* protects following fields only: */
Size extent; /* current extent of plan file */
int n_writers; /* number of active writers to query file */
int gc_count; /* plan file garbage collection cycle count */
pgspGlobalStats stats; /* global statistics for pgsp */
} pgspSharedState;
/*---- 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 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 pgspSharedState *shared_state = NULL;
static HTAB *hash_table = NULL;
/*---- GUC variables ----*/
typedef enum
{
TRACK_LEVEL_NONE, /* track no statements */
TRACK_LEVEL_TOP, /* only top level statements */
TRACK_LEVEL_ALL, /* all statements, including nested ones */
TRACK_LEVEL_FORCE /* all statements, including nested ones */
} PGSPTrackLevel;
static const struct config_enum_entry track_options[] =
{
{"none", TRACK_LEVEL_NONE, false},
{"top", TRACK_LEVEL_TOP, false},
{"all", TRACK_LEVEL_ALL, false},
{NULL, 0, false}
};
typedef enum
{
PLAN_FORMAT_RAW, /* No conversion. Shorten JSON */
PLAN_FORMAT_TEXT, /* Traditional text representation */
PLAN_FORMAT_JSON, /* JSON representation */
PLAN_FORMAT_YAML, /* YAML */
PLAN_FORMAT_XML, /* XML */
} PGSPPlanFormats;
static const struct config_enum_entry plan_formats[] =
{
{"raw" , PLAN_FORMAT_RAW , false},
{"text", PLAN_FORMAT_TEXT, false},
{"json", PLAN_FORMAT_JSON, false},
{"yaml", PLAN_FORMAT_YAML, false},
{"xml" , PLAN_FORMAT_XML , false},
{NULL, 0, false}
};
/* options for plan storage */
typedef enum
{
PLAN_STORAGE_SHMEM, /* plan is stored as a part of hash entry */
PLAN_STORAGE_FILE /* plan is stored in a separate file */
} pgspPlanStorage;
static const struct config_enum_entry plan_storage_options[] =
{
{"shmem", PLAN_STORAGE_SHMEM, false},
{"file", PLAN_STORAGE_FILE, false},
{NULL, 0, false}
};
static int store_size; /* max # statements to track */
static int track_level; /* tracking level */
static int min_duration; /* min duration to record */
static bool dump_on_shutdown; /* whether to save stats across shutdown */
static bool log_analyze; /* Similar to EXPLAIN (ANALYZE *) */
static bool log_verbose; /* Similar to EXPLAIN (VERBOSE *) */
static bool log_buffers; /* Similar to EXPLAIN (BUFFERS *) */
static bool log_timing; /* Similar to EXPLAIN (TIMING *) */
static bool log_triggers; /* whether to log trigger statistics */
static int plan_format; /* Plan representation style in
* pg_store_plans.plan */
static int plan_storage; /* Plan storage type */
#if PG_VERSION_NUM >= 140000
/*
* For pg14 and later, we rely on core queryid calculation. If
* it's not available it means that the admin explicitly refused to
* compute it, for performance reason or other. In that case, we
* will also consider that this extension is disabled.
*/
#define pgsp_enabled(q) \
((track_level == TRACK_LEVEL_ALL || \
(track_level == TRACK_LEVEL_TOP && nested_level == 0)) && \
(q != PGSP_NO_QUERYID))
#else
#define pgsp_enabled(q) \
(track_level == TRACK_LEVEL_ALL || \
(track_level == TRACK_LEVEL_TOP && nested_level == 0))
#endif
#define SHMEM_PLAN_PTR(ent) (((char *) ent) + sizeof(pgspEntry))
/*---- Function declarations ----*/
void _PG_init(void);
void _PG_fini(void);
Datum pg_store_plans_reset(PG_FUNCTION_ARGS);
Datum pg_store_plans_hash_query(PG_FUNCTION_ARGS);
Datum pg_store_plans(PG_FUNCTION_ARGS);
Datum pg_store_plans_shorten(PG_FUNCTION_ARGS);
Datum pg_store_plans_normalize(PG_FUNCTION_ARGS);
Datum pg_store_plans_jsonplan(PG_FUNCTION_ARGS);
Datum pg_store_plans_yamlplan(PG_FUNCTION_ARGS);
Datum pg_store_plans_xmlplan(PG_FUNCTION_ARGS);
Datum pg_store_plans_textplan(PG_FUNCTION_ARGS);
Datum pg_store_plans_info(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(pg_store_plans_reset);
PG_FUNCTION_INFO_V1(pg_store_plans_hash_query);
PG_FUNCTION_INFO_V1(pg_store_plans);
PG_FUNCTION_INFO_V1(pg_store_plans_1_6);
PG_FUNCTION_INFO_V1(pg_store_plans_shorten);
PG_FUNCTION_INFO_V1(pg_store_plans_normalize);
PG_FUNCTION_INFO_V1(pg_store_plans_jsonplan);
PG_FUNCTION_INFO_V1(pg_store_plans_yamlplan);
PG_FUNCTION_INFO_V1(pg_store_plans_xmlplan);
PG_FUNCTION_INFO_V1(pg_store_plans_textplan);
PG_FUNCTION_INFO_V1(pg_store_plans_info);
#if PG_VERSION_NUM < 130000
#define COMPTAG_TYPE char
#else
#define COMPTAG_TYPE QueryCompletion
#endif
#if PG_VERSION_NUM < 140000
#define ROLE_PG_READ_ALL_STATS DEFAULT_ROLE_READ_ALL_STATS
#endif
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,
uint64 count, bool execute_once);
static void pgsp_ExecutorFinish(QueryDesc *queryDesc);
static void pgsp_ExecutorEnd(QueryDesc *queryDesc);
static void pgsp_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
#if PG_VERSION_NUM >= 140000
bool readOnlyTree,
#endif
ProcessUtilityContext context, ParamListInfo params,
QueryEnvironment *queryEnv,
DestReceiver *dest, COMPTAG_TYPE *completionTag);
static uint32 hash_query(const char* query);
static void pgsp_store(char *plan, queryid_t queryId,
double total_time, uint64 rows,
const BufferUsage *bufusage);
static void pg_store_plans_internal(FunctionCallInfo fcinfo,
pgspVersion api_version);
static Size shared_mem_size(void);
static pgspEntry *entry_alloc(pgspHashKey *key, Size plan_offset, int plan_len,
bool sticky);
static bool ptext_store(const char *plan, int plan_len, Size *plan_offset,
int *gc_count);
static char *ptext_load_file(Size *buffer_size);
static char *ptext_fetch(Size plan_offset, int plan_len, char *buffer,
Size buffer_size);
static bool need_gc_ptexts(void);
static void gc_ptexts(void);
static void entry_dealloc(void);
static void entry_reset(void);
/*
* 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_statements 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;
#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
/*
* Define (or redefine) custom GUC variables.
*/
DefineCustomIntVariable("pg_store_plans.max",
"Sets the maximum number of plans tracked by pg_store_plans.",
NULL,
&store_size,
1000,
100,
INT_MAX,
PGC_POSTMASTER,
0,
NULL,
NULL,
NULL);
DefineCustomIntVariable("pg_store_plans.max_plan_length",
"Sets the maximum length of plans stored by pg_store_plans.",
NULL,
&max_plan_len,
5000,
100,
INT32_MAX,
PGC_POSTMASTER,
0,
NULL,
NULL,
NULL);
DefineCustomEnumVariable("pg_store_plans.plan_storage",
"Selects where to store plan texts.",
NULL,
&plan_storage,
PLAN_STORAGE_FILE,
plan_storage_options,
PGC_POSTMASTER,
0,
NULL,
NULL,
NULL);
DefineCustomEnumVariable("pg_store_plans.track",
"Selects which plans are tracked by pg_store_plans.",
NULL,
&track_level,
TRACK_LEVEL_TOP,
track_options,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
DefineCustomEnumVariable("pg_store_plans.plan_format",
"Selects which format to be appied for plan representation in pg_store_plans.",
NULL,
&plan_format,
PLAN_FORMAT_TEXT,
plan_formats,
PGC_USERSET,
0,
NULL,
NULL,
NULL);
DefineCustomIntVariable("pg_store_plans.min_duration",
"Minimum duration to record plan in milliseconds.",
NULL,
&min_duration,
0,
0,
INT_MAX,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("pg_store_plans.save",
"Save pg_store_plans statistics across server shutdowns.",
NULL,
&dump_on_shutdown,
true,
PGC_SIGHUP,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("pg_store_plans.log_analyze",
"Use EXPLAIN ANALYZE for plan logging.",
NULL,
&log_analyze,
false,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("pg_store_plans.log_buffers",
"Log buffer usage.",
NULL,
&log_buffers,
false,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("pg_store_plans.log_timing",
"Log timings.",
NULL,
&log_timing,
true,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("pg_store_plans.log_triggers",
"Log trigger trace.",
NULL,
&log_triggers,
false,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("pg_store_plans.log_verbose",
"Set VERBOSE for EXPLAIN on logging.",
NULL,
&log_verbose,
false,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
EmitWarningsOnPlaceholders("pg_store_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(shared_mem_size());
RequestNamedLWLockTranche("pg_store_plans", 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;
prev_ExecutorFinish = ExecutorFinish_hook;
ExecutorFinish_hook = pgsp_ExecutorFinish;
prev_ExecutorEnd = ExecutorEnd_hook;
ExecutorEnd_hook = pgsp_ExecutorEnd;
prev_ProcessUtility = ProcessUtility_hook;
ProcessUtility_hook = pgsp_ProcessUtility;
}
/*
* Module unload callback
*/
void
_PG_fini(void)
{
/* Uninstall hooks. */
shmem_startup_hook = prev_shmem_startup_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.
*/
static void
pgsp_shmem_startup(void)
{
bool found;
HASHCTL info;
FILE *file = NULL;
FILE *pfile = NULL;
uint32 header;
int32 num;
int32 pgver;
int32 i;
int plan_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 */
shared_state = NULL;
hash_table = NULL;
/*
* Create or attach to the shared memory state, including hash table
*/
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
shared_state = ShmemInitStruct("pg_store_plans",
sizeof(pgspSharedState),
&found);
if (!found)
{
/* First time through ... */
shared_state->lock = &(GetNamedLWLockTranche("pg_store_plans"))->lock;
shared_state->plan_size = max_plan_len;
shared_state->cur_median_usage = ASSUMED_MEDIAN_INIT;
shared_state->mean_plan_len = ASSUMED_LENGTH_INIT;
SpinLockInit(&shared_state->mutex);
shared_state->extent = 0;
shared_state->n_writers = 0;
shared_state->gc_count = 0;
shared_state->stats.dealloc = 0;
shared_state->stats.stats_reset = GetCurrentTimestamp();
}
/* Be sure everyone agrees on the hash table entry size */
plan_size = shared_state->plan_size;
memset(&info, 0, sizeof(info));
info.keysize = sizeof(pgspHashKey);
info.entrysize = sizeof(pgspEntry);
if (plan_storage == PLAN_STORAGE_SHMEM)
info.entrysize += max_plan_len;
hash_table = ShmemInitHash("pg_store_plans hash",
store_size, store_size,
&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(pgsp_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(PGSP_TEXT_FILE);
if (plan_storage == PLAN_STORAGE_FILE)
{
/* Allocate new query text temp file */
pfile = AllocateFile(PGSP_TEXT_FILE, PG_BINARY_W);
if (pfile == 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 (!dump_on_shutdown)
{
if (pfile)
FreeFile(pfile);
return;
}
/*
* Attempt to load old statistics from the dump file.
*/
file = AllocateFile(PGSP_DUMP_FILE, PG_BINARY_R);
if (file == NULL)
{
if (errno == ENOENT)
return; /* ignore not-found error */
/* No existing persisted stats file, so we're done */
goto read_error;
}
buffer_size = plan_size;
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 != PGSP_FILE_HEADER ||
pgver != PGSP_PG_MAJOR_VERSION)
goto data_error;
for (i = 0; i < num; i++)
{
pgspEntry temp;
pgspEntry *entry;
Size plan_offset = 0;
if (fread(&temp, sizeof(pgspEntry), 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;
/* Previous incarnation might have had a larger plan_size */
if (temp.plan_len >= buffer_size)
{
buffer = (char *) repalloc(buffer, temp.plan_len + 1);
buffer_size = temp.plan_len + 1;
}
if (fread(buffer, 1, temp.plan_len + 1, file) != temp.plan_len + 1)
goto read_error;
/* Skip loading "sticky" entries */
if (temp.counters.calls == 0)
continue;
/* Clip to available length if needed */
if (temp.plan_len >= plan_size)
temp.plan_len = pg_encoding_mbcliplen(temp.encoding,
buffer,
temp.plan_len,
plan_size - 1);
buffer[temp.plan_len] = '\0';
if (plan_storage == PLAN_STORAGE_FILE)
{
/* Store the plan text */
plan_offset = shared_state->extent;
if (fwrite(buffer, 1, temp.plan_len + 1, pfile) !=
temp.plan_len + 1)
goto write_error;
shared_state->extent += temp.plan_len + 1;
}
/* make the hashtable entry (discards old entries if too many) */
entry = entry_alloc(&temp.key, plan_offset, temp.plan_len, false);
if (plan_storage == PLAN_STORAGE_SHMEM)
memcpy(SHMEM_PLAN_PTR(entry), buffer, temp.plan_len + 1);
/* copy in the actual stats */
entry->counters = temp.counters;
}
pfree(buffer);
FreeFile(file);
if (pfile)
FreeFile(pfile);
/*
* 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;
read_error:
ereport(LOG,
(errcode_for_file_access(),
errmsg("could not read file \"%s\": %m",
PGSP_DUMP_FILE)));
goto fail;
data_error:
ereport(LOG,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("ignoring invalid data in file \"%s\"",
PGSP_DUMP_FILE)));
goto fail;
write_error:
ereport(LOG,
(errcode_for_file_access(),
errmsg("could not write file \"%s\": %m",
PGSP_TEXT_FILE)));
fail:
if (buffer)
pfree(buffer);
if (file)
FreeFile(file);
if (pfile)
FreeFile(pfile);
/* If possible, throw away the bogus file; ignore any error */
unlink(PGSP_DUMP_FILE);
/*
* Don't unlink PGSP_TEXT_FILE here; it should always be around while the
* server is running with pg_stat_statements 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
pgsp_shmem_shutdown(int code, Datum arg)
{
FILE *file;
char *pbuffer = NULL;
Size pbuffer_size = 0;
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 (!shared_state || !hash_table)
return;
/* Don't dump if told not to. */
if (!dump_on_shutdown)
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;
if (fwrite(&PGSP_PG_MAJOR_VERSION, sizeof(uint32), 1, file) != 1)
goto error;
num_entries = hash_get_num_entries(hash_table);
if (fwrite(&num_entries, sizeof(int32), 1, file) != 1)
goto error;
if (plan_storage == PLAN_STORAGE_FILE)
{
pbuffer = ptext_load_file(&pbuffer_size);
if (pbuffer == NULL)
goto error;
}
hash_seq_init(&hash_seq, hash_table);
while ((entry = hash_seq_search(&hash_seq)) != NULL)
{
int len = entry->plan_len;
char *pstr;
if (plan_storage == PLAN_STORAGE_FILE)
pstr = ptext_fetch(entry->plan_offset, len,
pbuffer, pbuffer_size);
else
pstr = SHMEM_PLAN_PTR(entry);
if (pstr == NULL)
continue; /* Ignore any entries with bogus texts */
if (fwrite(entry, sizeof(pgspEntry), 1, file) != 1 ||
fwrite(pstr, 1, len + 1, file) != len + 1)
{
/* note: we assume hash_seq_term won't change errno */
hash_seq_term(&hash_seq);
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_store_plans file \"%s\": %m",
PGSP_DUMP_FILE ".tmp")));
/* Unlink query-texts file; it's not needed while shutdown */
unlink(PGSP_TEXT_FILE);
return;
error:
ereport(LOG,
(errcode_for_file_access(),
errmsg("could not write pg_store_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 (log_analyze &&
(eflags & EXEC_FLAG_EXPLAIN_ONLY) == 0)
{
queryDesc->instrument_options |=
(log_timing ? INSTRUMENT_TIMER : 0)|
(log_timing ? 0: INSTRUMENT_ROWS)|
(log_buffers ? INSTRUMENT_BUFFERS : 0);
}
if (prev_ExecutorStart)
prev_ExecutorStart(queryDesc, eflags);
else
standard_ExecutorStart(queryDesc, eflags);
/*
* Set up to track total elapsed time in ExecutorRun. Allocate in per-query
* context so as to be free at ExecutorEnd.
*/
if (queryDesc->totaltime == NULL &&
pgsp_enabled(queryDesc->plannedstmt->queryId))
{
MemoryContext oldcxt;
oldcxt = MemoryContextSwitchTo(queryDesc->estate->es_query_cxt);
queryDesc->totaltime = InstrAlloc(1, INSTRUMENT_ALL
#if PG_VERSION_NUM >= 140000
, false
#endif
);
MemoryContextSwitchTo(oldcxt);
}
}
/*
* ExecutorRun hook: all we need do is track nesting depth
*/
static void
pgsp_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count,
bool execute_once)
{
nested_level++;
PG_TRY();
{
if (prev_ExecutorRun)
prev_ExecutorRun(queryDesc, direction, count, execute_once);
else
standard_ExecutorRun(queryDesc, direction, count, execute_once);
nested_level--;
}
PG_CATCH();
{
nested_level--;
PG_RE_THROW();
}
PG_END_TRY();
}
/*
* 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();
}
/*
* ExecutorEnd hook: store results if needed
*/
static void
pgsp_ExecutorEnd(QueryDesc *queryDesc)
{
if (queryDesc->totaltime)