-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpg_stat_query_plans_storage.c
1173 lines (1055 loc) · 38.4 KB
/
pg_stat_query_plans_storage.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
#include "postgres.h"
#include "access/parallel.h"
#include "catalog/pg_authid.h"
#if PG_VERSION_NUM >= 130000
#include "common/hashfn.h"
#elif PG_VERSION_NUM >= 120000
#include "utils/hashutils.h"
#else
#include "access/hash.h"
#endif
#include "commands/explain.h"
#include "executor/instrument.h"
#include "funcapi.h"
#include "jit/jit.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 "pgstat.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/lwlock.h"
#include "storage/shmem.h"
#include "storage/spin.h"
#include "tcop/utility.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#if PG_VERSION_NUM >= 140000 && PG_VERSION_NUM < 160000
#include "utils/queryjumble.h"
#endif
#if PG_VERSION_NUM >= 160000
#include "nodes/queryjumble.h"
#endif
#include "common/pg_lzcompress.h"
#include "utils/memutils.h"
#include "utils/timestamp.h"
#include "pg_stat_query_plans_common.h"
#include "pg_stat_query_plans_parser.h"
#include "pg_stat_query_plans_storage.h"
#include "pg_stat_query_plans_assert.h"
static int lock_iteration_count = 10;
static int lock_backoff_timeout = 100;
static void pgqp_update_counters(volatile pgqpCounters *counters,
pgqpStoreKind kind, double total_time,
uint64 rows, const BufferUsage *bufusage,
#if PG_VERSION_NUM >= 130000
const WalUsage *walusage,
#else
const void *walusage,
#endif
const struct JitInstrumentation *jitusage);
static void pgqp_remove_text(pgqpTextStorageEntry *entry);
/*
* Decode stored text
* if no encoding configured, return text address in the shared storage area
* otherwise allocate memory, decompress data and return address of decomressed
* text. Caller should free memory after usage.
*/
char *get_decoded_text(volatile pgqpTextStorageEntry *s) {
char *uncompressed_dst;
char *fail_dec_str = "failed to decompress";
int dlen;
pgqpAssert(s);
pgqpAssert(s->text_len >= 0);
pgqpAssert(s->text_offset + s->text_len < pgqp_storage_memory);
if (s->text_encoding == PGQP_PLAINTEXT)
return SHMEM_TEXT_PTR(s->text_offset);
else {
uncompressed_dst = palloc(s->origin_text_len);
dlen = pglz_decompress(SHMEM_TEXT_PTR(s->text_offset), s->text_len,
uncompressed_dst, s->origin_text_len
#if PG_VERSION_NUM >= 120000
,
true
#endif
);
if (dlen < 0) {
pfree(uncompressed_dst);
uncompressed_dst = palloc(strlen(fail_dec_str) + 1);
strcpy(uncompressed_dst, fail_dec_str);
}
return uncompressed_dst;
}
}
/*
* Store texts in storage
*
* Caller could call multiple method multiple times
* So we expect here that:
* - storage have free space for all data
* - caller holding exclusive memory lock so no-one could insert data
* between calls
*/
pgqpTextStorageEntry *pgqp_store_text(const char *data, pgqpTextsKind kind,
uint64 id_low, uint64 id_high) {
bool found;
pgqpTextStorageKey key;
pgqpTextStorageEntry *entry;
pgqpAssert(data);
if (!pgqp || !pgqp_texts || !pgqp_storage)
return NULL;
/* memset() is required when pgqpTextStorageKey is without padding only */
memset(&key, 0, sizeof(pgqpTextStorageKey));
key.item_mark = kind;
key.item_id_low = id_low;
key.item_id_high = id_high;
if (id_low == 0) {
// re-calculate if identifier is zero
key.item_id_low = hash_any_extended((const unsigned char *)data,
strlen(data), PGQP_ID_SEEDVALUE);
}
entry =
(pgqpTextStorageEntry *)hash_search(pgqp_texts, &key, HASH_ENTER, &found);
if (!found) {
/* the new key - should store new offset value */
int max_size;
volatile pgqpSharedState *s = (volatile pgqpSharedState *)pgqp;
pgqpTextsEnc needed_encoding = pgqp_encoding;
pgqpAssert(s->storage_offset < pgqp_storage_memory);
if (kind == PGQP_SQLTEXT)
max_size = pgqp_max_query_len;
else
max_size = pgqp_max_plan_len;
/* store offset to string */
entry->text_offset = s->storage_offset;
if (needed_encoding == PGQP_PGLZ) {
char *compressed_dst;
int len;
entry->origin_text_len = strlen(data) + 1;
compressed_dst = palloc(PGLZ_MAX_OUTPUT(entry->origin_text_len));
len = pglz_compress(data, entry->origin_text_len, compressed_dst,
PGLZ_strategy_default);
if (len > max_size) {
// too big to store text - should be truncated
needed_encoding = PGQP_PLAINTEXT;
} else if (len > 0) {
entry->text_len = len;
pgqpAssert(s->storage_offset + entry->text_len < pgqp_storage_memory);
memcpy(SHMEM_TEXT_PTR(s->storage_offset), compressed_dst, len);
entry->text_encoding = PGQP_PGLZ;
} else {
// most probably data is not compressable - so store them in plain text
needed_encoding = PGQP_PLAINTEXT;
}
pfree(compressed_dst);
}
if (needed_encoding == PGQP_PLAINTEXT) {
if (strlen(data) + 1 <= max_size) {
/* store text len */
entry->text_len = strlen(data) + 1;
pgqpAssert(s->storage_offset + entry->text_len < pgqp_storage_memory);
/* copy data to storage*/
strcpy(SHMEM_TEXT_PTR(s->storage_offset), data);
} else {
char *additional_comment;
int comment_len =
asprintf(&additional_comment, "<deleted tail %li symbols>",
strlen(data) + 1 - max_size);
pgqpAssert(comment_len > 0);
/* store text len */
entry->text_len = max_size + comment_len + 1;
pgqpAssert(s->storage_offset + entry->text_len < pgqp_storage_memory);
/* copy data to storage*/
strncpy(SHMEM_TEXT_PTR(s->storage_offset), data, max_size);
strncpy(SHMEM_TEXT_PTR(s->storage_offset + max_size),
additional_comment, comment_len + 1);
free(additional_comment);
}
entry->origin_text_len = entry->text_len;
entry->text_encoding = PGQP_PLAINTEXT;
}
/* increase offset */
s->storage_offset += entry->text_len;
/* update statistics */
if (kind == PGQP_SQLTEXT) {
s->stats.compressed_queries_size += entry->text_len;
s->stats.queries_size += entry->origin_text_len;
} else {
s->stats.compressed_plans_size += entry->text_len;
s->stats.plans_size += entry->origin_text_len;
}
entry->usage_count = 1;
} else {
/* increase the number of pointers to data */
entry->usage_count++;
}
return entry;
}
void pgqp_remove_text(pgqpTextStorageEntry *entry) {
/* Safety check... */
if (!pgqp || !pgqp_texts || !pgqp_storage)
return;
if (entry) {
entry->usage_count--;
pgqpAssert(entry->usage_count >= 0);
if (entry->usage_count == 0) {
volatile pgqpSharedState *s = (volatile pgqpSharedState *)pgqp;
/* mark string as empty */
pgqpAssert(entry->text_offset >=0 && entry->text_offset < pgqp_storage_memory);
strncpy(SHMEM_TEXT_PTR(entry->text_offset), "", 1);
/* remove item from hash table */
hash_search(pgqp_texts, &entry->text_key, HASH_REMOVE, NULL);
/* update statistics */
if (entry->text_key.item_mark == PGQP_SQLTEXT) {
s->stats.queries_size -= entry->origin_text_len;
s->stats.compressed_queries_size -= entry->text_len;
} else {
s->stats.plans_size -= entry->origin_text_len;
s->stats.compressed_plans_size -= entry->text_len;
}
entry->text_len = 1;
}
}
};
/*
* Update counters, method is not thread-safe, so lock should be taken before
* call update
*/
static void pgqp_update_counters(volatile pgqpCounters *counters,
pgqpStoreKind kind, double total_time,
uint64 rows, const BufferUsage *bufusage,
#if PG_VERSION_NUM >= 130000
const WalUsage *walusage,
#else
const void *walusage,
#endif
const struct JitInstrumentation *jitusage) {
pgqpAssert(kind > PGQP_INVALID && kind < PGQP_NUMKIND);
pgqpAssert(counters);
pgqpAssert(bufusage);
if (PGQP_IS_STICKY(counters))
counters->usage = PGQP_USAGE_INIT;
counters->calls[kind] += 1;
counters->total_time[kind] += total_time;
if (counters->calls[kind] == 1) {
counters->min_time[kind] = total_time;
counters->max_time[kind] = total_time;
counters->mean_time[kind] = total_time;
} else {
/*
* Welford's method for accurately computing variance. See
* <http://www.johndcook.com/blog/standard_deviation/>
*/
double old_mean = counters->mean_time[kind];
counters->mean_time[kind] +=
(total_time - old_mean) / counters->calls[kind];
counters->sum_var_time[kind] +=
(total_time - old_mean) * (total_time - counters->mean_time[kind]);
/* calculate min and max time */
if (counters->min_time[kind] > total_time)
counters->min_time[kind] = total_time;
if (counters->max_time[kind] < total_time)
counters->max_time[kind] = total_time;
}
counters->rows += rows;
counters->shared_blks_hit += bufusage->shared_blks_hit;
counters->shared_blks_read += bufusage->shared_blks_read;
counters->shared_blks_dirtied += bufusage->shared_blks_dirtied;
counters->shared_blks_written += bufusage->shared_blks_written;
counters->local_blks_hit += bufusage->local_blks_hit;
counters->local_blks_read += bufusage->local_blks_read;
counters->local_blks_dirtied += bufusage->local_blks_dirtied;
counters->local_blks_written += bufusage->local_blks_written;
counters->temp_blks_read += bufusage->temp_blks_read;
counters->temp_blks_written += bufusage->temp_blks_written;
#if PG_VERSION_NUM >= 170000
counters->blk_read_time += INSTR_TIME_GET_MILLISEC(bufusage->shared_blk_read_time);
counters->blk_write_time += INSTR_TIME_GET_MILLISEC(bufusage->shared_blk_write_time);
#else
counters->blk_read_time += INSTR_TIME_GET_MILLISEC(bufusage->blk_read_time);
counters->blk_write_time += INSTR_TIME_GET_MILLISEC(bufusage->blk_write_time);
#endif
#if PG_VERSION_NUM >= 150000
counters->temp_blk_read_time +=
INSTR_TIME_GET_MILLISEC(bufusage->temp_blk_read_time);
counters->temp_blk_write_time +=
INSTR_TIME_GET_MILLISEC(bufusage->temp_blk_write_time);
#endif
counters->usage += PGQP_USAGE_EXEC(total_time);
#if PG_VERSION_NUM >= 130000
pgqpAssert(walusage);
counters->wal_records += walusage->wal_records;
counters->wal_fpi += walusage->wal_fpi;
counters->wal_bytes += walusage->wal_bytes;
#endif
if (jitusage) {
counters->jit_functions += jitusage->created_functions;
counters->jit_generation_time +=
INSTR_TIME_GET_MILLISEC(jitusage->generation_counter);
if (INSTR_TIME_GET_MILLISEC(jitusage->inlining_counter))
counters->jit_inlining_count++;
counters->jit_inlining_time +=
INSTR_TIME_GET_MILLISEC(jitusage->inlining_counter);
if (INSTR_TIME_GET_MILLISEC(jitusage->optimization_counter))
counters->jit_optimization_count++;
counters->jit_optimization_time +=
INSTR_TIME_GET_MILLISEC(jitusage->optimization_counter);
if (INSTR_TIME_GET_MILLISEC(jitusage->emission_counter))
counters->jit_emission_count++;
counters->jit_emission_time +=
INSTR_TIME_GET_MILLISEC(jitusage->emission_counter);
}
}
#if PG_VERSION_NUM < 140000
/*
* Given an arbitrarily long query string, produce a hash for the purposes of
* identifying the query, without normalizing constants. Used when hashing
* utility statements.
*/
static uint64 pgqp_hash_string(const char *str, int len) {
return DatumGetUInt64(hash_any_extended((const unsigned char *)str, len, 0));
}
#endif
/*
* Store some statistics for a statement.
*
* If jstate is not NULL then we're trying to create an entry for which
* we have no statistics as yet; we just want to record the normalized
* query string. total_time, rows, bufusage and walusage are ignored in this
* case.
*
* If kind is PGQP_PLAN or PGQP_EXEC, its value is used as the array position
* for the arrays in the pgqpCounters field.
*/
void pgqp_store(const char *query, StringInfo execution_plan, uint64 queryId,
QueryDesc *qd, int query_location, int query_len,
pgqpStoreKind kind, double total_time, uint64 rows,
const BufferUsage *bufusage,
#if PG_VERSION_NUM >= 130000
const WalUsage *walusage,
#else
const void *walusage,
#endif
const struct JitInstrumentation *jitusage,
#if PG_VERSION_NUM >= 140000
JumbleState *jstate
#else
pgqpJumbleState *jstate
#endif
) {
pgqpQueryHashKey key;
pgqpPlanHashKey plan_key;
pgqpEntry *entry = NULL;
pgqpPlanEntry *plan_entry = NULL;
int64 generation;
pgqpAssert(query != NULL);
pgqpAssert(kind == PGQP_PLAN || kind == PGQP_EXEC || jstate != NULL);
/* Safety check... */
if (!pgqp || !pgqp_queries || !pgqp_plans || !pgqp_texts) {
return;
}
#if PG_VERSION_NUM >= 140000
/*
* Nothing to do if compute_query_id isn't enabled and no other module
* computed a query identifier.
*/
if (queryId == UINT64CONST(0)) {
return;
}
/*
* Confine our attention to the relevant part of the string, if the query
* is a portion of a multi-statement source string, and update query
* location and length if needed.
*/
query = CleanQuerytext(query, &query_location, &query_len);
#else
if (query_location >= 0) {
pgqpAssert(query_location <= strlen(query));
query += query_location;
/* Length of 0 (or -1) means "rest of string" */
if (query_len <= 0)
query_len = strlen(query);
else
pgqpAssert(query_len <= strlen(query));
} else {
/* If query location is unknown, distrust query_len as well */
query_location = 0;
query_len = strlen(query);
}
/*
* 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(query[0]))
query++, query_location++, query_len--;
while (query_len > 0 && scanner_isspace(query[query_len - 1]))
query_len--;
/*
* For utility statements, we just hash the query string to get an ID.
*/
if (queryId == UINT64CONST(0)) {
queryId = pgqp_hash_string(query, query_len);
/*
* If we are unlucky enough to get a hash of zero(invalid), use
* queryID as 2 instead, queryID 1 is already in use for normal
* statements.
*/
if (queryId == UINT64CONST(0))
queryId = UINT64CONST(2);
}
#endif
/* memset() is required when pgqpQueryHashKey is without padding only */
memset(&key, 0, sizeof(pgqpQueryHashKey));
key.userid = GetUserId();
key.dbid = MyDatabaseId;
key.queryid = queryId;
key.toplevel = (pgqp_exec_nested_level == 0);
/* Lookup the hash table entry with shared lock. */
LWLockAcquire(pgqp->lock, LW_SHARED);
entry = (pgqpEntry *)hash_search(pgqp_queries, &key, HASH_FIND, NULL);
/* Create new entry, if not present */
if (!entry) {
char *norm_query;
int need_free = 0;
/*
* Create a new, normalized query string if caller asked. We don't
* need to hold the lock while doing this work. (Note: in any case,
* it's possible that someone else creates a duplicate hashtable entry
* in the interval where we don't hold the lock below. That case is
* handled by entry_alloc.)
*/
if (jstate) {
LWLockRelease(pgqp->lock);
norm_query = pgqp_gen_normquery(jstate, query, query_location, &query_len);
need_free = 1;
LWLockAcquire(pgqp->lock, LW_SHARED);
} else {
norm_query = (char*)query;
}
/* Need exclusive lock to make a new hashtable entry - promote */
LWLockRelease(pgqp->lock);
if (lock_iteration_count == 0)
LWLockAcquire(pgqp->lock, LW_EXCLUSIVE);
else
for (int i = 0; i < lock_iteration_count; i++)
{
if (LWLockConditionalAcquire(pgqp->lock, LW_EXCLUSIVE))
break;
if (i > lock_iteration_count / 2)
pg_usleep(i * lock_backoff_timeout);
if (i == lock_iteration_count - 1)
{
elog(DEBUG1, "could not enter query information to pgqp_ya");
return;
}
}
/* OK to create a new hashtable entry */
{
volatile pgqpSharedState *s = (volatile pgqpSharedState *)pgqp;
SpinLockAcquire(&s->mutex);
generation = s->generation;
SpinLockRelease(&s->mutex);
}
entry = pgqp_query_alloc(&key, jstate != NULL, generation);
pgqpAssert(entry);
pgqp_inc_generation();
entry->query_text = pgqp_store_text(norm_query, PGQP_SQLTEXT, queryId, 0);
/* Not need exclusive lock for a while - switch to shared */
LWLockRelease(pgqp->lock);
LWLockAcquire(pgqp->lock, LW_SHARED);
/* We postpone this clean-up until we're out of the lock */
if (need_free && norm_query)
pfree(norm_query);
}
if (execution_plan) {
int64 planId;
pgqpAssert(qd);
pgqpAssert(execution_plan->data);
pgqpAssert(execution_plan->len >= 0);
planId = hash_any_extended((const unsigned char *)execution_plan->data,
execution_plan->len, PGQP_ID_SEEDVALUE);
memset(&plan_key, 0, sizeof(pgqpPlanHashKey));
plan_key.userid = GetUserId();
plan_key.dbid = MyDatabaseId;
plan_key.queryid = queryId;
plan_key.toplevel = (pgqp_exec_nested_level == 0);
plan_key.planid = planId;
plan_entry =
(pgqpPlanEntry *)hash_search(pgqp_plans, &plan_key, HASH_FIND, NULL);
/* Create new entry, if not present */
if (!plan_entry) {
ExplainState *es;
/* Need exclusive lock to make a new hashtable entry - promote */
LWLockRelease(pgqp->lock);
if (lock_iteration_count == 0)
LWLockAcquire(pgqp->lock, LW_EXCLUSIVE);
else
for (int i = 0; i < lock_iteration_count; i++)
{
if (LWLockConditionalAcquire(pgqp->lock, LW_EXCLUSIVE))
break;
if (i > lock_iteration_count / 2)
pg_usleep(i * lock_backoff_timeout);
if (i == lock_iteration_count - 1)
{
elog(DEBUG1, "could not enter query information to pgsk");
return;
}
}
/* OK to create a new hashtable entry */
{
volatile pgqpSharedState *s = (volatile pgqpSharedState *)pgqp;
SpinLockAcquire(&s->mutex);
generation = s->generation;
SpinLockRelease(&s->mutex);
}
plan_entry = pgqp_plan_alloc(&plan_key, jstate != NULL, generation);
pgqp_inc_generation();
/* Store original query text */
plan_entry->query_text =
pgqp_store_text(query, PGQP_SQLTEXT, planId, queryId);
/* Store normalized plan */
plan_entry->gen_plan = pgqp_store_text(execution_plan->data,
PGQP_GENSQLPLAN, planId, queryId);
/*
* Now make explain plan again - with user settings to show it in
* pg_stat_query_plans_plan_ya
*/
es = NewExplainState();
es->verbose = example_log_verbose;
es->format = example_plan_format;
PG_TRY();
{
ExplainBeginOutput(es);
ExplainPrintPlan(es, qd);
if (example_log_triggers)
ExplainPrintTriggers(es, qd);
ExplainEndOutput(es);
}
PG_CATCH();
{
resetStringInfo(es->str);
appendStringInfo(es->str, "Failed to generate plan info");
}
PG_END_TRY();
/* Store plan text */
plan_entry->example_plan =
pgqp_store_text(es->str->data, PGQP_SQLPLAN, planId, queryId);
/* Increase plans counter for query */
/* Query entry could be wiped out here so we should search it again */
entry = (pgqpEntry *)hash_search(pgqp_queries, &key, HASH_FIND, NULL);
if (entry) {
entry->plans_count++;
}
}
}
/* Increment the counts, except when jstate is not NULL */
if (!jstate) {
if (entry) {
/*
* Grab the spinlock while updating the counters (see comment about
* locking rules at the head of the file)
*/
volatile pgqpEntry *e = (volatile pgqpEntry *)entry;
SpinLockAcquire(&e->mutex);
pgqp_update_counters(&e->counters, kind, total_time, rows, bufusage,
walusage, jitusage);
SpinLockRelease(&e->mutex);
}
if (plan_entry) {
volatile pgqpPlanEntry *e_plan = (volatile pgqpPlanEntry *)plan_entry;
SpinLockAcquire(&e_plan->mutex);
pgqp_update_counters(&e_plan->counters, kind, total_time, rows, bufusage,
walusage, jitusage);
if (qd) {
plan_entry->plan_counters.startup_cost =
qd->plannedstmt->planTree->startup_cost;
plan_entry->plan_counters.total_cost =
qd->plannedstmt->planTree->total_cost;
plan_entry->plan_counters.plan_rows =
qd->plannedstmt->planTree->plan_rows;
plan_entry->plan_counters.plan_width =
qd->plannedstmt->planTree->plan_width;
}
SpinLockRelease(&e_plan->mutex);
}
}
LWLockRelease(pgqp->lock);
}
/*
* All methods here started with pgqp_ prefix are not thread-safe.
* Caller must hold an exclusive lock on pgqp->lock.
*/
/*
* Allocate a new hashtable entry.
*
* If "sticky" is true, make the new entry artificially sticky so that it will
* probably still be there when the query finishes execution. We do this by
* giving it a median usage value rather than the normal value. (Strictly
* speaking, query strings are normalized on a best effort basis, though it
* would be difficult to demonstrate this even under artificial conditions.)
*
* Note: despite needing exclusive lock, it's not an error for the target
* entry to already exist. This is because pgqp_store releases and
* reacquires lock after failing to find a match; so someone else could
* have made the entry while we waited to get exclusive lock.
*/
pgqpEntry *pgqp_query_alloc(pgqpQueryHashKey *key, bool sticky,
int64 generation) {
pgqpEntry *entry;
bool found;
/* Make space if needed */
pgqp_dealloc();
/* Find or create an entry with desired hash code */
entry = (pgqpEntry *)hash_search(pgqp_queries, key, HASH_ENTER, &found);
if (!found) {
/* New entry, initialize it */
/* reset the statistics */
memset(&entry->counters, 0, sizeof(pgqpCounters));
/* set the appropriate initial usage count */
entry->counters.usage = sticky ? pgqp->cur_median_usage : PGQP_USAGE_INIT;
/* re-initialize the mutex each time ... we assume no one using it */
SpinLockInit(&entry->mutex);
/* set generation */
entry->generation = generation;
/* there is no stored plans */
entry->plans_count = 0;
}
return entry;
}
/*
* Allocate a new hashtable entry. Similar to pgqp_query_alloc
*/
pgqpPlanEntry *pgqp_plan_alloc(pgqpPlanHashKey *key, bool sticky,
int64 generation) {
pgqpPlanEntry *entry;
bool found;
/* Make space if needed */
pgqp_dealloc();
/* Find or create an entry with desired hash code */
entry = (pgqpPlanEntry *)hash_search(pgqp_plans, key, HASH_ENTER, &found);
if (!found) {
/* New entry, initialize it */
/* reset the statistics */
memset(&entry->counters, 0, sizeof(pgqpCounters));
memset(&entry->plan_counters, 0, sizeof(pgqpPlanCounters));
/* set the appropriate initial usage count */
entry->counters.usage = sticky ? pgqp->cur_median_usage : PGQP_USAGE_INIT;
/* re-initialize the mutex each time ... we assume no one using it */
SpinLockInit(&entry->mutex);
/* set generation */
entry->generation = generation;
}
return entry;
}
/*
* qsort sql entry comparator for sorting into increasing usage order
*/
static int entry_dealloc_cmp(const void *lhs, const void *rhs) {
double l_usage = (*(pgqpEntry *const *)lhs)->counters.usage;
double r_usage = (*(pgqpEntry *const *)rhs)->counters.usage;
if (l_usage < r_usage)
return -1;
else if (l_usage > r_usage)
return +1;
else
return 0;
}
/*
* qsort plan entry comparator for sorting into increasing usage order
*/
static int plan_entry_dealloc_cmp(const void *lhs, const void *rhs) {
double l_usage = (*(pgqpPlanEntry *const *)lhs)->counters.usage;
double r_usage = (*(pgqpPlanEntry *const *)rhs)->counters.usage;
if (l_usage < r_usage)
return -1;
else if (l_usage > r_usage)
return +1;
else
return 0;
}
/*
* qsort comparator for sorting into increasing offset order
*/
static int entry_gc_cmp(const void *lhs, const void *rhs) {
int64 l_offset = (*(pgqpTextStorageEntry *const *)lhs)->text_offset;
int64 r_offset = (*(pgqpTextStorageEntry *const *)rhs)->text_offset;
if (l_offset < r_offset)
return -1;
else if (l_offset > r_offset)
return +1;
else
return 0;
}
/*
* Compact data in a storage and change offsets for texts
*/
void pgqp_gc_storage(void) {
HASH_SEQ_STATUS hash_seq;
pgqpTextStorageEntry **entries;
pgqpTextStorageEntry *entry;
int i;
int items_count;
int64 storage_offset;
int64 current_offset;
instr_time start;
instr_time duration;
volatile pgqpSharedState *s = (volatile pgqpSharedState *)pgqp;
pgqpAssert(s);
/* copy variables while holding lock */
SpinLockAcquire(&s->mutex);
storage_offset = s->storage_offset;
SpinLockRelease(&s->mutex);
/* check if we really need to perform gc */
if (pgqp_storage_memory - storage_offset >
pgqp_storage_memory / 100 * PGQP_FREE_PERCENT) {
return;
}
/* no-one coud change memory structures while we performing gc */
SpinLockAcquire(&s->mutex);
INSTR_TIME_SET_CURRENT(start);
entries =
palloc(hash_get_num_entries(pgqp_texts) * sizeof(pgqpTextStorageEntry *));
/*
* Sort entries by offset and deallocate not used entries.
* Copy string data in a shared memory storage while deallocating unused
* items.
*/
i = 0;
hash_seq_init(&hash_seq, pgqp_texts);
while ((entry = hash_seq_search(&hash_seq)) != NULL) {
if (entry->usage_count == 0) {
hash_search(pgqp_texts, &entry->text_key, HASH_REMOVE, NULL);
} else {
entries[i++] = entry;
}
}
items_count = i;
/* Sort into increasing order by current_offset */
qsort(entries, items_count, sizeof(pgqpTextStorageEntry *), entry_gc_cmp);
/* now shift data */
current_offset = 0;
for (i = 0; i < items_count; i++) {
pgqpAssert(entries[i]->text_offset >= current_offset);
if (entries[i]->text_offset > current_offset) {
pgqpAssert(current_offset + entries[i]->text_len < pgqp_storage_memory);
memmove(SHMEM_TEXT_PTR(current_offset),
SHMEM_TEXT_PTR(entries[i]->text_offset), entries[i]->text_len);
entries[i]->text_offset = current_offset;
}
current_offset += entries[i]->text_len;
}
pgqpAssert(current_offset <= storage_offset);
/* set storage_offset to the last position */
s->storage_offset = current_offset;
s->gc_count++;
pfree(entries);
INSTR_TIME_SET_CURRENT(duration);
INSTR_TIME_SUBTRACT(duration, start);
s->stats.gc_time_ms += INSTR_TIME_GET_MILLISEC(duration);
SpinLockRelease(&s->mutex);
};
/*
* checking if dealloc of items needed, flag already_started change boundaries
* for decision - in a case of running deallocation we should dealloc additional
* items to have reserve
*/
bool pgqp_need_gc(bool already_started, int64 queries_size, int64 plans_size) {
int64 free_entries = 1;
int64 free_entries_plan = 1;
int64 smemory = pgqp_max_query_len + 2 * pgqp_max_plan_len;
if (already_started) {
free_entries = Max(1, pgqp_max * PGQP_FREE_PERCENT / 100);
free_entries_plan = Max(1, pgqp_max_plans * PGQP_FREE_PERCENT / 100);
smemory = Max(smemory, pgqp_storage_memory / 100 * PGQP_FREE_PERCENT);
}
/* check if pgqp_queries need be cleared */
if (hash_get_num_entries(pgqp_queries) >= pgqp_max - free_entries)
return true;
/* check if plans need be cleared */
if (hash_get_num_entries(pgqp_plans) >= pgqp_max_plans - free_entries_plan)
return true;
/* check if storage need be cleared*/
if (pgqp_storage_memory <= queries_size + plans_size + smemory)
return true;
return false;
}
/*
* checking if dealloc query texts is needed, method could be called only while
* we've already started items deallocation
*/
static bool pgqp_need_gc_stat(int64 queries_size) {
int64 free_entries = Max(1, pgqp_max * PGQP_FREE_PERCENT / 100);
int64 smemory = pgqp_max_query_len + 2 * pgqp_max_plan_len;
smemory = Max(smemory, pgqp_storage_memory / 100 * PGQP_FREE_PERCENT);
if (hash_get_num_entries(pgqp_queries) >= pgqp_max - free_entries)
return true;
/* check if clearing stored query texts could help free storage memory */
if (pgqp_storage_memory <= queries_size + smemory)
return true;
return false;
}
/*
* Deallocate least-used query entries.
*/
void pgqp_dealloc(void) {
HASH_SEQ_STATUS hash_seq;
pgqpPlanEntry **entries;
pgqpPlanEntry *entry;
pgqpEntry *query_entry;
pgqpQueryHashKey key;
int item_count;
int i;
instr_time start;
instr_time duration;
volatile pgqpSharedState *s = (volatile pgqpSharedState *)pgqp;
/* Check if dealloc needed */
pgqpAssert(s);
if (!pgqp_need_gc(false, s->stats.queries_size, s->stats.plans_size))
return;
/*
* Sort entries by usage and deallocate while not satisfied pgqp_need_gc criteria.
* 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.
*/
INSTR_TIME_SET_CURRENT(start);
entries = palloc(hash_get_num_entries(pgqp_plans) * sizeof(pgqpPlanEntry *));
/* Create array for sotring and decay items */
i = 0;
hash_seq_init(&hash_seq, pgqp_plans);
while ((entry = hash_seq_search(&hash_seq)) != NULL) {
pgqpCounters *c = &entry->counters;
entries[i++] = entry;
/* "Sticky" entries get a different usage decay rate. */
if (PGQP_IS_STICKY(c))
entry->counters.usage *= PGQP_STICKY_DECREASE_FACTOR;
else
entry->counters.usage *= PGQP_USAGE_DECREASE_FACTOR;
}
/* Sort into increasing order by usage */
qsort(entries, i, sizeof(pgqpPlanEntry *), plan_entry_dealloc_cmp);
/* Record the (approximate) median usage */
if (i > 0)
pgqp->cur_median_usage = entries[i / 2]->counters.usage;
/* No-one could re-use memory while we free all structures */
{
/* remove items */
SpinLockAcquire(&s->mutex);
item_count = i;
for (i = 0; i < item_count; i++) {
/* remove entry from pgqp_plans*/
entry = hash_search(pgqp_plans, &entries[i]->key, HASH_REMOVE, NULL);
pgqpAssert(entry);
/* remove link to query text */
pgqp_remove_text(entry->query_text);
/* remove link to query plans */
pgqp_remove_text(entry->example_plan);
pgqp_remove_text(entry->gen_plan);
/* increase statistics about query remove */
s->stats.plans_wiped_out += 1;
/* remove entry from pgqp_queries */
memset(&key, 0, sizeof(pgqpQueryHashKey));
key.userid = entry->key.userid;
key.dbid = entry->key.dbid;
key.queryid = entry->key.queryid;
key.toplevel = entry->key.toplevel;
query_entry =
(pgqpEntry *)hash_search(pgqp_queries, &key, HASH_FIND, NULL);
if (query_entry) {
query_entry->plans_count--;
/* if no plans left - we could remove query_entry
* removing query could lead to store un-normalized query texts
* (normalized plan store only in post-parse steps),
* so we do not remove if really not need to.
* plans_count could be negative if query was removed during
* plan registration
*/
if (query_entry->plans_count <= 0 &&
pgqp_need_gc_stat(s->stats.queries_size)) {
query_entry = (pgqpEntry *)hash_search(
pgqp_queries, &query_entry->key, HASH_REMOVE, NULL);
pgqpAssert(query_entry);
/* remove link to query text */
pgqp_remove_text(query_entry->query_text);
/* increase statistics about query remove */
s->stats.queries_wiped_out += 1;
}
}
/* Check if we still need to delete items */
if (!pgqp_need_gc(true, s->stats.queries_size, s->stats.plans_size))
break;
}