-
Notifications
You must be signed in to change notification settings - Fork 2
/
pg_sortstats.c
2194 lines (1899 loc) · 58.2 KB
/
pg_sortstats.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_sortstats.c
* Track statistics about sorts performs, and also estimate how much
* work_mem would have been needed to sort data in memory.
*
* This module is heavily inspired on the great pg_stat_statements official
* contrib. The same locking rules are used, which for reference are:
*
* Note about locking issues: to create or delete an entry in the shared
* hashtable, one must hold pgsrt->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 pgsrt->extent (the next free spot in the external
* keys-text file) should be accessed only while holding either the
* pgsrt->mutex spinlock, or exclusive lock on pgsrt->lock. We use the mutex
* to allow reserving file space while holding only shared lock on pgsrt->lock.
* Rewriting the entire external keys-text file, eg for garbage collection,
* requires holding pgsrt->lock exclusively; this allows individual entries
* in the file to be read or written while holding only shared lock.
*
* Copyright (c) 2018-2023, The PoWA-team
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <sys/stat.h>
#include <unistd.h>
#include "fmgr.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "access/hash.h"
#include "access/htup_details.h"
#if PG_VERSION_NUM >= 90600
#include "access/parallel.h"
#endif
#include "mb/pg_wchar.h"
#include "nodes/nodeFuncs.h"
#include "parser/parsetree.h"
#if PG_VERSION_NUM >= 90600
#include "postmaster/autovacuum.h"
#endif
#if PG_VERSION_NUM >= 120000
#include "replication/walsender.h"
#endif
#if PG_VERSION_NUM < 100000
#include "storage/fd.h"
#endif
#include "storage/ipc.h"
#include "storage/lwlock.h"
#include "storage/shmem.h"
#if PG_VERSION_NUM < 110000
#include "storage/spin.h"
#endif
#include "utils/builtins.h"
#include "utils/guc.h"
#if PG_VERSION_NUM < 110000
#include "utils/memutils.h"
#endif
#if PG_VERSION_NUM >= 90500
#include "utils/ruleutils.h"
#endif
#include "utils/tuplesort.h"
#include "include/pg_sortstats_import.h"
PG_MODULE_MAGIC;
/*--- Macros and structs ---*/
/* Location of permanent stats file (valid when database is shut down) */
#define PGSRT_DUMP_FILE PGSTAT_STAT_PERMANENT_DIRECTORY "/pg_sortstats.stat"
/*
* Location of external keys 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_sortstats has no way of avoiding
* race conditions. Besides, we only expect modest, infrequent I/O for keys
* strings, so placing the file on a faster filesystem is not compelling.
*/
#define PGSRT_TEXT_FILE PG_STAT_TMP_DIR "/pgsrt_sortkey_texts.stat"
/* Magic number identifying the stats file format */
static const uint32 PGSRT_FILE_HEADER = 0x20180804;
/* PostgreSQL major version number, changes in which invalidate all entries */
static const uint32 PGSRT_PG_MAJOR_VERSION = PG_VERSION_NUM / 100;
#define PGSRT_COLUMNS 17 /* number of columns in pg_sortstats SRF */
#define USAGE_DECREASE_FACTOR (0.99) /* decreased every pgsrt_entry_dealloc */
#define USAGE_DEALLOC_PERCENT 5 /* free this % of entries at once */
#define USAGE_INIT (1.0)
#define ASSUMED_MEDIAN_INIT (10.0) /* initial assumed median usage */
#define ASSUMED_LENGTH_INIT 128 /* initial assumed mean keys length */
#define record_gc_ktexts() \
do { \
volatile pgsrtSharedState *s = (volatile pgsrtSharedState *) pgsrt; \
SpinLockAcquire(&s->mutex); \
s->gc_count++; \
SpinLockRelease(&s->mutex); \
} while(0)
/* In PostgreSQL 11, queryid becomes a uint64 internally.
*/
#if PG_VERSION_NUM >= 110000
typedef uint64 pgsrt_queryid;
#else
typedef uint32 pgsrt_queryid;
#endif
typedef struct pgsrtSharedState
{
LWLockId lock; /* protects hashtable search/modification */
double cur_median_usage; /* current median usage in hashtable */
Size mean_keys_len; /* current mean keys text length */
slock_t mutex; /* protects following fields only: */
Size extent; /* current extent of keys file */
int n_writers; /* number of active writers to keys file */
int gc_count; /* keys file garbage collection cycle count */
#if PG_VERSION_NUM >= 90600
LWLockId queryids_lock; /* protects following array */
pgsrt_queryid queryids[FLEXIBLE_ARRAY_MEMBER]; /* queryid of non-worker processes */
#endif
} pgsrtSharedState;
typedef struct pgsrtHashKey
{
Oid userid; /* user OID */
Oid dbid; /* database OID */
pgsrt_queryid queryid; /* query identifier */
uint32 sortid; /* sort identifier withing a query */
} pgsrtHashKey;
typedef struct pgsrtCounters
{
double usage; /* usage factor */
int64 lines; /* total number of lines in input */
int64 lines_to_sort; /* total number of lines sorted */
int64 work_mems; /* total size of estimated work_mem */
int64 topn_sorts; /* number of top-N heapsorts */
int64 quicksorts; /* number of quicksorts */
int64 external_sorts; /* number of external sorts */
int64 external_merges; /* number of external merges */
int64 nbtapes; /* total number of tapes used */
int64 space_disk; /* total disk space consumed */
int64 space_memory; /* total memory space consumed */
int64 non_parallels; /* number of non parallel sorts */
int64 nb_workers; /* total number of parallel workers (including gather node) */
} pgsrtCounters;
typedef struct pgsrtEntry
{
pgsrtHashKey key;
pgsrtCounters counters; /* statistics for this sort */
int nbkeys; /* # of columns in the sort */
Size keys_offset; /* deparsed keys text offset in external file */
int keys_len; /* # of valid bytes in deparsed keys string, or -1 */
int encoding; /* deparsed keys text encoding */
slock_t mutex; /* protects the counters only */
} pgsrtEntry;
typedef struct pgsrtWalkerContext
{
QueryDesc *queryDesc;
List *ancestors;
List *rtable;
List *rtable_names;
List *deparse_cxt;
} pgsrtWalkerContext;
/*--- Function declarations ---*/
void _PG_init(void);
extern PGDLLEXPORT Datum pg_sortstats(PG_FUNCTION_ARGS);
extern PGDLLEXPORT Datum pg_sortstats_reset(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(pg_sortstats);
PG_FUNCTION_INFO_V1(pg_sortstats_reset);
#if PG_VERSION_NUM >= 150000
static void pgsrt_shmem_request(void);
#endif
static void pgsrt_shmem_startup(void);
static void pgsrt_shmem_shutdown(int code, Datum arg);
static void pgsrt_ExecutorStart(QueryDesc *queryDesc, int eflags);
static void pgsrt_ExecutorRun(QueryDesc *queryDesc,
ScanDirection direction,
#if PG_VERSION_NUM >= 90600
uint64 count
#else
long count
#endif
#if PG_VERSION_NUM >= 100000
,bool execute_once
#endif
);
static void pgsrt_ExecutorFinish(QueryDesc *queryDesc);
static void pgsrt_ExecutorEnd(QueryDesc *queryDesc);
#if PG_VERSION_NUM >= 150000
static shmem_request_hook_type prev_shmem_request_hook = NULL;
#endif
static shmem_startup_hook_type prev_shmem_startup_hook = NULL;
static 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 Size pgsrt_memsize(void);
#if PG_VERSION_NUM >= 90600
static Size pgsrt_queryids_size(void);
static pgsrt_queryid pgsrt_get_queryid(void);
static void pgsrt_set_queryid(pgsrt_queryid);
#endif
static pgsrtEntry *pgsrt_entry_alloc(pgsrtHashKey *key, Size keys_offset,
int keys_len, int encoding, int nbkeys);
static void pgsrt_entry_dealloc(void);
static void pgsrt_entry_reset(void);
static void pgsrt_store(pgsrt_queryid queryId, int nbkeys, char *keys,
pgsrtCounters *counters);
static uint32 pgsrt_hash_fn(const void *key, Size keysize);
static int pgsrt_match_fn(const void *key1, const void *key2, Size keysize);
static bool ktext_store(const char *keys, int keys_len, Size *keys_offset,
int *gc_count);
static char *ktext_load_file(Size *buffer_size);
static char *ktext_fetch(Size keys_offset, int keys_len, char *buffer,
Size buffer_size);
static bool need_gc_ktexts(void);
static void gc_ktexts(void);
static void pgsrt_process_sortstate(SortState *srtstate, pgsrtWalkerContext *context);
static bool pgsrt_planstate_walker(PlanState *ps, pgsrtWalkerContext *context);
static char * pgsrt_get_sort_group_keys(SortState *srtstate,
int nkeys, AttrNumber *keycols,
Oid *sortOperators, Oid *collations, bool *nullsFirst,
pgsrtWalkerContext *context);
static void pgsrt_setup_walker_context(pgsrtWalkerContext *context);
static unsigned long round_up_pow2(int64 val);
static int get_alignment_overhead(TupleDesc tupdesc);
/*--- Local variables ---*/
static int nesting_level = 0;
static bool pgsrt_enabled;
static int pgsrt_max; /* max #of sorts to track */
static bool pgsrt_save; /* whether to save stats across shutdown */
static HTAB *pgsrt_hash = NULL;
static pgsrtSharedState *pgsrt = NULL;
void
_PG_init(void)
{
if (!process_shared_preload_libraries_in_progress)
{
elog(ERROR, "This module can only be loaded via shared_preload_libraries");
return;
}
DefineCustomBoolVariable("pg_sortstats.enabled",
"Enable / Disable pg_sortstats",
NULL,
&pgsrt_enabled,
true,
PGC_USERSET,
0,
NULL,
NULL,
NULL);
DefineCustomIntVariable("pg_sortstats.max",
"Sets the maximum number of statements tracked by pg_sortstats.",
NULL,
&pgsrt_max,
10000,
100,
INT_MAX,
PGC_POSTMASTER,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("pg_sortstats.save",
"Save pg_sortstats statistics across server shutdowns.",
NULL,
&pgsrt_save,
true,
PGC_SIGHUP,
0,
NULL,
NULL,
NULL);
EmitWarningsOnPlaceholders("pg_sortstats");
#if PG_VERSION_NUM < 150000
/*
* Request additional shared resources. (These are no-ops if we're not in
* the postmaster process.) We'll allocate or attach to the shared
* resources in pgsrt_shmem_startup().
* If you change code here, don't forget to also report the modifications
* in pgsrt_shmem_request() for pg15 and later.
*/
RequestAddinShmemSpace(pgsrt_memsize());
#if PG_VERSION_NUM >= 90600
RequestNamedLWLockTranche("pg_sortstats", 2);
#else
RequestAddinLWLocks(1);
#endif /* pg 9.6+ */
#endif /* pg 15- */
/* install hooks */
prev_ExecutorStart = ExecutorStart_hook;
ExecutorStart_hook = pgsrt_ExecutorStart;
prev_ExecutorRun = ExecutorRun_hook;
ExecutorRun_hook = pgsrt_ExecutorRun;
prev_ExecutorFinish = ExecutorFinish_hook;
ExecutorFinish_hook = pgsrt_ExecutorFinish;
prev_ExecutorEnd = ExecutorEnd_hook;
ExecutorEnd_hook = pgsrt_ExecutorEnd;
#if PG_VERSION_NUM >= 150000
prev_shmem_request_hook = shmem_request_hook;
shmem_request_hook = pgsrt_shmem_request;
#endif
prev_shmem_startup_hook = shmem_startup_hook;
shmem_startup_hook = pgsrt_shmem_startup;
}
#if PG_VERSION_NUM >= 150000
/*
* Request additional shared memory resources.
*
* If you change code here, don't forget to also report the modifications in
* _PG_init() for pg14 and below.
*/
static void
pgsrt_shmem_request(void)
{
if (prev_shmem_request_hook)
prev_shmem_request_hook();
RequestAddinShmemSpace(pgsrt_memsize());
RequestNamedLWLockTranche("pg_sortstats", 2);
}
#endif
static void
pgsrt_shmem_startup(void)
{
bool found;
HASHCTL info;
FILE *file = NULL;
FILE *kfile = NULL;
uint32 header;
int32 num;
int32 pgver;
int32 i;
int buffer_size;
char *buffer = NULL;
Size tottextlen;
int nvalidtexts;
if (prev_shmem_startup_hook)
prev_shmem_startup_hook();
/* reset in case this is a restart within the postmaster */
pgsrt = NULL;
/* Create or attach to the shared memory state */
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
/* global access lock */
pgsrt = ShmemInitStruct("pg_sortstats",
(sizeof(pgsrtSharedState)
#if PG_VERSION_NUM >= 90600
+ pgsrt_queryids_size()
#endif
),
&found);
if (!found)
{
/* First time through ... */
#if PG_VERSION_NUM >= 90600
LWLockPadded *locks = GetNamedLWLockTranche("pg_sortstats");
pgsrt->lock = &(locks[0]).lock;
pgsrt->queryids_lock = &(locks[1]).lock;
memset(pgsrt->queryids, 0, pgsrt_queryids_size());
#else
pgsrt->lock = LWLockAssign();
#endif
pgsrt->cur_median_usage = ASSUMED_MEDIAN_INIT;
pgsrt->mean_keys_len = ASSUMED_LENGTH_INIT;
SpinLockInit(&pgsrt->mutex);
pgsrt->extent = 0;
pgsrt->n_writers = 0;
pgsrt->gc_count = 0;
}
memset(&info, 0, sizeof(info));
info.keysize = sizeof(pgsrtHashKey);
info.entrysize = sizeof(pgsrtEntry);
info.hash = pgsrt_hash_fn;
info.match = pgsrt_match_fn;
/* allocate stats shared memory hash */
pgsrt_hash = ShmemInitHash("pg_sortstats hash",
pgsrt_max, pgsrt_max,
&info,
HASH_ELEM | HASH_FUNCTION | HASH_COMPARE);
LWLockRelease(AddinShmemInitLock);
if (!IsUnderPostmaster)
on_shmem_exit(pgsrt_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 keys text file possibly left over from crash */
unlink(PGSRT_TEXT_FILE);
/* Allocate new keys text temp file */
kfile = AllocateFile(PGSRT_TEXT_FILE, PG_BINARY_W);
if (kfile == 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 (!pgsrt_save)
{
FreeFile(kfile);
return;
}
/*
* Attempt to load old statistics from the dump file.
*/
file = AllocateFile(PGSRT_DUMP_FILE, PG_BINARY_R);
if (file == NULL)
{
if (errno != ENOENT)
goto read_error;
/* No existing persisted stats file, so we're done */
FreeFile(kfile);
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 != PGSRT_FILE_HEADER ||
pgver != PGSRT_PG_MAJOR_VERSION)
goto data_error;
tottextlen = 0;
nvalidtexts = 0;
for (i = 0; i < num; i++)
{
pgsrtEntry temp;
pgsrtEntry *entry;
Size keys_offset;
if (fread(&temp, sizeof(pgsrtEntry), 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.keys_len >= buffer_size)
{
buffer_size = Max(buffer_size * 2, temp.keys_len + 1);
buffer = repalloc(buffer, buffer_size);
}
if (fread(buffer, 1, temp.keys_len + 1, file) != temp.keys_len + 1)
goto read_error;
/* Should have a trailing null, but let's make sure */
buffer[temp.keys_len] = '\0';
/* Store the keys text */
keys_offset = pgsrt->extent;
if (fwrite(buffer, 1, temp.keys_len + 1, kfile) != temp.keys_len + 1)
goto write_error;
pgsrt->extent += temp.keys_len + 1;
/* make the hashtable entry (discards old entries if too many) */
entry = pgsrt_entry_alloc(&temp.key, keys_offset, temp.keys_len,
temp.encoding, temp.nbkeys);
/* In the mean length computation, ignore dropped texts. */
if (entry->keys_len >= 0)
{
tottextlen += entry->keys_len + 1;
nvalidtexts++;
}
/* copy in the actual stats */
entry->counters = temp.counters;
}
if (nvalidtexts > 0)
pgsrt->mean_keys_len = tottextlen / nvalidtexts;
else
pgsrt->mean_keys_len = ASSUMED_LENGTH_INIT;
pfree(buffer);
FreeFile(file);
FreeFile(kfile);
/*
* 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 PGSRT_TEXT_FILE is included in a basebackup,
* because we remove that file on startup; it acts inversely to
* PGSRT_DUMP_FILE, in that it is only supposed to be around when the
* server is running, whereas PGSRT_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(PGSRT_DUMP_FILE);
return;
read_error:
ereport(LOG,
(errcode_for_file_access(),
errmsg("could not read file \"%s\": %m",
PGSRT_DUMP_FILE)));
goto fail;
data_error:
ereport(LOG,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("ignoring invalid data in file \"%s\"",
PGSRT_DUMP_FILE)));
goto fail;
write_error:
ereport(LOG,
(errcode_for_file_access(),
errmsg("could not write file \"%s\": %m",
PGSRT_TEXT_FILE)));
fail:
if (buffer)
pfree(buffer);
if (file)
FreeFile(file);
if (kfile)
FreeFile(kfile);
/* If possible, throw away the bogus file; ignore any error */
unlink(PGSRT_DUMP_FILE);
/*
* Don't unlink PGSRT_TEXT_FILE here; it should always be around while the
* server is running with pg_sortstats enabled
*/
}
/* Save the statistics into a file at shutdown */
static void
pgsrt_shmem_shutdown(int code, Datum arg)
{
FILE *file;
char *kbuffer = NULL;
Size kbuffer_size = 0;
HASH_SEQ_STATUS hash_seq;
int32 num_entries;
pgsrtEntry *entry;
/* Don't try to dump during a crash. */
if (code)
return;
/* Safety check ... shouldn't get here unless shmem is set up. */
if (!pgsrt || !pgsrt_hash)
return;
/* Don't dump if told not to. */
if (!pgsrt_save)
return;
file = AllocateFile(PGSRT_DUMP_FILE ".tmp", PG_BINARY_W);
if (file == NULL)
goto error;
if (fwrite(&PGSRT_FILE_HEADER, sizeof(uint32), 1, file) != 1)
goto error;
if (fwrite(&PGSRT_PG_MAJOR_VERSION, sizeof(uint32), 1, file) != 1)
goto error;
num_entries = hash_get_num_entries(pgsrt_hash);
if (fwrite(&num_entries, sizeof(int32), 1, file) != 1)
goto error;
kbuffer = ktext_load_file(&kbuffer_size);
if (kbuffer == NULL)
goto error;
/*
* When serializing to disk, we store keys texts immediately after their
* entry data. Any orphaned keys texts are thereby excluded.
*/
hash_seq_init(&hash_seq, pgsrt_hash);
while ((entry = hash_seq_search(&hash_seq)) != NULL)
{
int len = entry->keys_len;
char *kstr = ktext_fetch(entry->keys_offset, len,
kbuffer, kbuffer_size);
if (kstr == NULL)
continue; /* Ignore any entries with bogus texts */
if (fwrite(entry, sizeof(pgsrtEntry), 1, file) != 1 ||
fwrite(kstr, 1, len + 1, file) != len + 1)
{
/* note: we assume hash_seq_term won't change errno */
hash_seq_term(&hash_seq);
goto error;
}
}
free(kbuffer);
kbuffer = NULL;
if (FreeFile(file))
{
file = NULL;
goto error;
}
/*
* Rename file into place, so we atomically replace any old one.
*/
(void) durable_rename(PGSRT_DUMP_FILE ".tmp", PGSRT_DUMP_FILE, LOG);
/* Unlink keys-texts file; it's not needed while shutdown */
unlink(PGSRT_TEXT_FILE);
return;
error:
ereport(LOG,
(errcode_for_file_access(),
errmsg("could not write file \"%s\": %m",
PGSRT_DUMP_FILE ".tmp")));
if (kbuffer)
free(kbuffer);
if (file)
FreeFile(file);
unlink(PGSRT_DUMP_FILE ".tmp");
unlink(PGSRT_TEXT_FILE);
}
/*
* Save this query's queryId if it's not a parallel worker
*/
static void
pgsrt_ExecutorStart(QueryDesc *queryDesc, int eflags)
{
#if PG_VERSION_NUM >= 90600
if (pgsrt_enabled && !IsParallelWorker())
pgsrt_set_queryid(queryDesc->plannedstmt->queryId);
#endif
if (prev_ExecutorStart)
prev_ExecutorStart(queryDesc, eflags);
else
standard_ExecutorStart(queryDesc, eflags);
}
/*
* ExecutorRun hook: all we need do is track nesting depth
*/
static void
pgsrt_ExecutorRun(QueryDesc *queryDesc,
ScanDirection direction,
#if PG_VERSION_NUM >= 90600
uint64 count
#else
long count
#endif
#if PG_VERSION_NUM >= 100000
,bool execute_once
#endif
)
{
nesting_level++;
PG_TRY();
{
if (prev_ExecutorRun)
#if PG_VERSION_NUM >= 100000
prev_ExecutorRun(queryDesc, direction, count, execute_once);
#else
prev_ExecutorRun(queryDesc, direction, count);
#endif
else
#if PG_VERSION_NUM >= 100000
standard_ExecutorRun(queryDesc, direction, count, execute_once);
#else
standard_ExecutorRun(queryDesc, direction, count);
#endif
nesting_level--;
}
PG_CATCH();
{
nesting_level--;
PG_RE_THROW();
}
PG_END_TRY();
}
/*
* ExecutorFinish hook: all we need do is track nesting depth
*/
static void
pgsrt_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();
}
/*
* Walk the planstates, find any sorts and gather their statistics.
*/
static void
pgsrt_ExecutorEnd(QueryDesc *queryDesc)
{
/* retrieve sorts informations, main work starts from here */
if (pgsrt_enabled)
{
pgsrtWalkerContext context;
context.queryDesc = queryDesc;
context.ancestors = NIL;
pgsrt_planstate_walker(queryDesc->planstate, &context);
#if PG_VERSION_NUM >= 90600
/* Remove the saved queryid for safety */
if (!IsParallelWorker())
pgsrt_set_queryid(0);
#endif
}
if (prev_ExecutorEnd)
prev_ExecutorEnd(queryDesc);
else
standard_ExecutorEnd(queryDesc);
}
static Size
pgsrt_memsize(void)
{
Size size;
size = MAXALIGN(sizeof(pgsrtSharedState));
size = add_size(size, hash_estimate_size(pgsrt_max, sizeof(pgsrtEntry)));
#if PG_VERSION_NUM >= 90600
size = add_size(size, pgsrt_queryids_size());
#endif
return size;
}
#if PG_VERSION_NUM >= 90600
/* Parallel workers won't have their queryid setup. We store the leader
* process' queryid in shared memory so that workers can find which queryid
* they're actually executing.
*/
static Size
pgsrt_queryids_size(void)
{
#if PG_VERSION_NUM >= 150000
Assert(MaxBackends > 0);
/* We need an extra slot since BackendId numerotation starts at 1. */
#define PGSRT_NB_BACKEND_SLOT (MaxBackends + 1)
#elif PG_VERSION_NUM >= 120000
/* We need frrom for all possible backends, plus the autovacuum launcher
* and workers, plus the background workers, and an extra one since
* BackendId numerotation starts at 1.
* Starting with pg12, wal senders aren't part of MaxConnections anymore,
* so they need to be accounted for.
*/
#define PGSRT_NB_BACKEND_SLOT (MaxConnections \
+ autovacuum_max_workers + 1 \
+ max_worker_processes \
+ max_wal_senders + 1)
#else
#define PGSRT_NB_BACKEND_SLOT (MaxConnections \
+ autovacuum_max_workers + 1 \
+ max_worker_processes + 1)
#endif
return MAXALIGN(sizeof(pgsrt_queryid) * PGSRT_NB_BACKEND_SLOT);
}
static pgsrt_queryid
pgsrt_get_queryid(void)
{
pgsrt_queryid queryId;
Assert(IsParallelWorker());
Assert(MyBackendId <= PGSRT_NB_BACKEND_SLOT);
LWLockAcquire(pgsrt->queryids_lock, LW_SHARED);
queryId = pgsrt->queryids[ParallelLeaderBackendId];
LWLockRelease(pgsrt->queryids_lock);
return queryId;
}
static void
pgsrt_set_queryid(pgsrt_queryid queryId)
{
Assert(!IsParallelWorker());
Assert(MyBackendId <= PGSRT_NB_BACKEND_SLOT);
LWLockAcquire(pgsrt->queryids_lock, LW_EXCLUSIVE);
pgsrt->queryids[MyBackendId] = queryId;
LWLockRelease(pgsrt->queryids_lock);
}
#endif
/*
* Allocate a new hashtable entry.
* caller must hold an exclusive lock on pgsrt->lock
*/
static pgsrtEntry *
pgsrt_entry_alloc(pgsrtHashKey *key, Size keys_offset, int keys_len,
int encoding, int nbkeys)
{
pgsrtEntry *entry;
bool found;
/* Make space if needed */
while (hash_get_num_entries(pgsrt_hash) >= pgsrt_max)
pgsrt_entry_dealloc();
/* Find or create an entry with desired hash code */
entry = (pgsrtEntry *) hash_search(pgsrt_hash, key, HASH_ENTER, &found);
if (!found)
{
/* New entry, initialize it */
/* reset the statistics */
memset(&entry->counters, 0, sizeof(pgsrtCounters));
/* set the appropriate initial usage count */
entry->counters.usage = USAGE_INIT;
/* re-initialize the mutex each time ... we assume no one using it */
SpinLockInit(&entry->mutex);
/* set non counters fields */
Assert(keys_len >= 0);
entry->nbkeys = nbkeys;
entry->keys_offset = keys_offset;
entry->keys_len = keys_len;
entry->encoding = encoding;
}
return entry;
}
/*
* qsort comparator for sorting into increasing usage order
*/
static int
entry_cmp(const void *lhs, const void *rhs)
{
double l_usage = (*(pgsrtEntry *const *) lhs)->counters.usage;
double r_usage = (*(pgsrtEntry *const *) rhs)->counters.usage;
if (l_usage < r_usage)
return -1;
else if (l_usage > r_usage)
return +1;
else
return 0;
}
/*
* Deallocate least used entries.
*
* Caller must hold an exclusive lock on pgsrt->lock.
*/
static void
pgsrt_entry_dealloc(void)
{
HASH_SEQ_STATUS hash_seq;
pgsrtEntry **entries;
pgsrtEntry *entry;
int nvictims;
int i;
Size tottextlen;
int nvalidtexts;
/*
* Sort entries by usage and deallocate USAGE_DEALLOC_PERCENT of them.
* While we're scanning the table, apply the decay factor to the usage
* values.
*
* Note that the mean query length is almost immediately obsolete, since
* we compute it before not after discarding the least-used entries.
* Hopefully, that doesn't affect the mean too much; it doesn't seem worth
* making two passes to get a more current result. Likewise, the new
* cur_median_usage includes the entries we're about to zap.
*/
entries = palloc(hash_get_num_entries(pgsrt_hash) * sizeof(pgsrtEntry *));
i = 0;
tottextlen = 0;
nvalidtexts = 0;
hash_seq_init(&hash_seq, pgsrt_hash);
while ((entry = hash_seq_search(&hash_seq)) != NULL)
{
entries[i++] = entry;
entry->counters.usage *= USAGE_DECREASE_FACTOR;
/* In the mean length computation, ignore dropped texts. */
if (entry->keys_len >= 0)
{
tottextlen += entry->keys_len + 1;
nvalidtexts++;
}
}
/* Sort into increasing order by usage */
qsort(entries, i, sizeof(pgsrtEntry *), entry_cmp);
/* Record the (approximate) median usage */
if (i > 0)
pgsrt->cur_median_usage = entries[i / 2]->counters.usage;
/* Record the mean query length */
if (nvalidtexts > 0)
pgsrt->mean_keys_len = tottextlen / nvalidtexts;
else
pgsrt->mean_keys_len = ASSUMED_LENGTH_INIT;
/* Now zap an appropriate fraction of lowest-usage entries */
nvictims = Max(10, i * USAGE_DEALLOC_PERCENT / 100);
nvictims = Min(nvictims, i);
for (i = 0; i < nvictims; i++)
{
hash_search(pgsrt_hash, &entries[i]->key, HASH_REMOVE, NULL);
}
pfree(entries);
}