forked from bigsql/plprofiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plprofiler.c
2086 lines (1787 loc) · 58.9 KB
/
plprofiler.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
/*-------------------------------------------------------------------------
*
* plprofiler.c
*
* Profiling plugin for PL/pgSQL instrumentation
*
* Copyright (c) 2014-2019, BigSQL
* Copyright (c) 2008-2014, PostgreSQL Global Development Group
* Copyright 2006,2007 - EnterpriseDB, Inc.
*
* Major Change History:
* 2012 - Removed from PostgreSQL plDebugger Extension
* 2015 - Resurrected as standalone plProfiler by OpenSCG
* 2016 - Rewritten as v2 to use shared hash tables, have lower overhead
* - v3 Major performance improvements, flame graph UI
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "plprofiler.h"
/**********************************************************************
* PL executor callback function prototypes
**********************************************************************/
static void profiler_func_init(PLpgSQL_execstate *estate,
PLpgSQL_function * func);
static void profiler_func_beg(PLpgSQL_execstate *estate,
PLpgSQL_function *func);
static void profiler_func_end(PLpgSQL_execstate *estate,
PLpgSQL_function *func);
static void profiler_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt);
static void profiler_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt);
/**********************************************************************
* Local function prototypes
**********************************************************************/
static Size profiler_shmem_size(void);
static void profiler_shmem_startup(void);
static void init_hash_tables(void);
static char *find_source(Oid oid, HeapTuple *tup, char **funcName);
static int count_source_lines(const char *src);
static uint32 line_hash_fn(const void *key, Size keysize);
static int line_match_fn(const void *key1, const void *key2, Size keysize);
static uint32 callgraph_hash_fn(const void *key, Size keysize);
static int callgraph_match_fn(const void *key1, const void *key2, Size keysize);
static void callgraph_push(Oid func_oid);
static void callgraph_pop_one(void);
static void callgraph_pop(Oid func_oid);
static void callgraph_check(Oid func_oid);
static void callgraph_collect(uint64 us_elapsed, uint64 us_self,
uint64 us_children);
static int32 profiler_collect_data(void);
static void profiler_xact_callback(XactEvent event, void *arg);
/**********************************************************************
* Local variables
**********************************************************************/
static MemoryContext profiler_mcxt = NULL;
static HTAB *functions_hash = NULL;
static HTAB *callgraph_hash = NULL;
static profilerSharedState *profiler_shared_state = NULL;
static HTAB *functions_shared = NULL;
static HTAB *callgraph_shared = NULL;
static bool profiler_first_call_in_xact = true;
static bool profiler_active = false;
static bool profiler_enabled_local = false;
static int profiler_max_functions = PL_MIN_FUNCTIONS;
static int profiler_max_lines = PL_MIN_LINES;
static int profiler_max_callgraph = PL_MIN_CALLGRAPH;
static callGraphKey graph_stack;
static instr_time graph_stack_entry[PL_MAX_STACK_DEPTH];
static uint64 graph_stack_child_time[PL_MAX_STACK_DEPTH];
static int graph_stack_pt = 0;
static time_t last_collect_time = 0;
static bool have_new_local_data = false;
static PLpgSQL_plugin *prev_plpgsql_plugin = NULL;
static PLpgSQL_plugin *prev_pltsql_plugin = NULL;
static shmem_startup_hook_type prev_shmem_startup_hook = NULL;
static PLpgSQL_plugin plugin_funcs = {
profiler_func_init,
profiler_func_beg,
profiler_func_end,
profiler_stmt_beg,
profiler_stmt_end,
NULL,
NULL
};
/**********************************************************************
* Extension (de)initialization functions.
**********************************************************************/
void
_PG_init(void)
{
PLpgSQL_plugin **plugin_ptr;
/* Link us into the PL/pgSQL executor. */
plugin_ptr = (PLpgSQL_plugin **)find_rendezvous_variable("PLpgSQL_plugin");
prev_plpgsql_plugin = *plugin_ptr;
*plugin_ptr = &plugin_funcs;
/* Link us into the PL/TSQL executor. */
plugin_ptr = (PLpgSQL_plugin **)find_rendezvous_variable("PLTSQL_plugin");
prev_pltsql_plugin = *plugin_ptr;
*plugin_ptr = &plugin_funcs;
/* Initialize local hash tables. */
init_hash_tables();
if (process_shared_preload_libraries_in_progress)
{
/*
* When loaded via shared_preload_libraries, we have to
* also hook into the shmem_startup call chain and register
* a callback at transaction end.
*/
prev_shmem_startup_hook = shmem_startup_hook;
shmem_startup_hook = profiler_shmem_startup;
RegisterXactCallback(profiler_xact_callback, NULL);
/*
* Additional config options only available if running via
* shared_preload_libraries. These all affect the amount of
* shared memory used by the extension, so they only make
* sense as PGC_POSTMASTER.
*/
DefineCustomIntVariable("plprofiler.max_functions",
"Maximum number of functions that can be "
"tracked in shared memory when using "
"plprofiler.collect_in_shmem",
NULL,
&profiler_max_functions,
PL_MIN_FUNCTIONS,
PL_MIN_FUNCTIONS,
INT_MAX,
PGC_POSTMASTER,
0,
NULL,
NULL,
NULL);
DefineCustomIntVariable("plprofiler.max_lines",
"Maximum number of source lines that can be "
"tracked in shared memory when using "
"plprofiler.collect_in_shmem",
NULL,
&profiler_max_lines,
PL_MIN_LINES,
PL_MIN_LINES,
INT_MAX,
PGC_POSTMASTER,
0,
NULL,
NULL,
NULL);
DefineCustomIntVariable("plprofiler.max_callgraphs",
"Maximum number of call graphs that can be "
"tracked in shared memory when using "
"plprofiler.collect_in_shmem",
NULL,
&profiler_max_callgraph,
PL_MIN_CALLGRAPH,
PL_MIN_CALLGRAPH,
INT_MAX,
PGC_POSTMASTER,
0,
NULL,
NULL,
NULL);
/* Request the additionl shared memory and LWLock needed. */
RequestAddinShmemSpace(profiler_shmem_size());
#if PG_VERSION_NUM >= 90600
RequestNamedLWLockTranche("plprofiler", 1);
#else
RequestAddinLWLocks(1);
#endif
}
}
void
_PG_fini(void)
{
PLpgSQL_plugin **plugin_ptr;
plugin_ptr = (PLpgSQL_plugin **)find_rendezvous_variable("PLpgSQL_plugin");
*plugin_ptr = prev_plpgsql_plugin;
prev_plpgsql_plugin = NULL;
plugin_ptr = (PLpgSQL_plugin **)find_rendezvous_variable("PLTSQL_plugin");
*plugin_ptr = prev_pltsql_plugin;
prev_pltsql_plugin = NULL;
MemoryContextDelete(profiler_mcxt);
profiler_mcxt = NULL;
functions_hash = NULL;
callgraph_hash = NULL;
if (prev_shmem_startup_hook != NULL)
{
shmem_startup_hook = prev_shmem_startup_hook;
prev_shmem_startup_hook = NULL;
UnregisterXactCallback(profiler_xact_callback, NULL);
}
}
/* -------------------------------------------------------------------
* profiler_shmem_size()
*
* Calculate the amount of shared memory the profiler needs to
* keep functions, callgraphs and line statistics globally.
* -------------------------------------------------------------------
*/
static Size
profiler_shmem_size(void)
{
Size num_bytes;
num_bytes = offsetof(profilerSharedState, line_info);
num_bytes = add_size(num_bytes,
sizeof(linestatsLineInfo) * profiler_max_lines);
num_bytes = add_size(num_bytes,
hash_estimate_size(profiler_max_functions,
sizeof(linestatsEntry)));
num_bytes = add_size(num_bytes,
hash_estimate_size(profiler_max_callgraph,
sizeof(callGraphEntry)));
return num_bytes;
}
/**********************************************************************
* Hook functions
**********************************************************************/
/* -------------------------------------------------------------------
* profiler_func_init()
*
* This hook function is called by the PL/pgSQL interpreter when a
* new function is about to start. Specifically, this instrumentation
* hook is called after the stack frame has been created, but before
* values are assigned to the local variables.
*
* 'estate' points to the stack frame for this function, 'func'
* points to the definition of the function
*
* We use this hook to load the source code for the function that's
* being invoked and to set up our context structures
* -------------------------------------------------------------------
*/
static void
profiler_func_init(PLpgSQL_execstate *estate, PLpgSQL_function *func )
{
profilerInfo *profiler_info;
linestatsHashKey linestats_key;
linestatsEntry *linestats_entry;
bool linestats_found;
/*
* On first call within a transaction we determine if the profiler
* is active or not. This means that starting/stopping to collect
* data will only happen on a transaction boundary.
*/
if (profiler_first_call_in_xact)
{
profiler_first_call_in_xact = false;
if (profiler_shared_state != NULL)
{
profiler_active = (
profiler_shared_state->profiler_enabled_global ||
profiler_shared_state->profiler_enabled_pid == MyProcPid ||
profiler_enabled_local);
}
else
{
profiler_active = profiler_enabled_local;
}
}
if (!profiler_active)
{
/*
* The profiler can be enabled/disabled via changing postgresql.conf
* and reload (SIGHUP). The change becomes visible in backends the
* next time, the TCOP loop is ready for a new client query. This
* allows to enable the profiler for some time, have it save the
* stats in the permanent tables, then turn it off again. At that
* moment, we want to release all profiler resources.
*/
if (functions_hash != NULL)
init_hash_tables();
return;
}
/*
* Anonymous code blocks do not have function source code
* that we can lookup in pg_proc. For now we ignore them.
*/
if (func->fn_oid == InvalidOid)
return;
/* Tell collect_data() that new information has arrived locally. */
have_new_local_data = true;
/*
* Search for this function in our line stats hash table. Create the
* entry if it does not exist yet.
*/
linestats_key.db_oid = MyDatabaseId;
linestats_key.fn_oid = func->fn_oid;
linestats_entry = (linestatsEntry *)hash_search(functions_hash,
&linestats_key,
HASH_ENTER,
&linestats_found);
if (linestats_entry == NULL)
elog(ERROR, "plprofiler out of memory");
if (!linestats_found)
{
/* New function, initialize entry. */
MemoryContext old_context;
HeapTuple proc_tuple;
char *proc_src;
char *func_name;
proc_src = find_source( func->fn_oid, &proc_tuple, &func_name );
linestats_entry->line_count = count_source_lines(proc_src) + 1;
old_context = MemoryContextSwitchTo(profiler_mcxt);
linestats_entry->line_info = palloc0(linestats_entry->line_count *
sizeof(linestatsLineInfo));
MemoryContextSwitchTo(old_context);
ReleaseSysCache(proc_tuple);
}
/*
* The PL/pgSQL interpreter provides a void pointer (in each stack frame)
* that's reserved for plugins. We allocate a profilerInfo structure and
* record it's address in that pointer so we can keep some per-invocation
* information.
*/
profiler_info = (profilerInfo *)palloc(sizeof(profilerInfo ));
profiler_info->fn_oid = func->fn_oid;
profiler_info->line_count = linestats_entry->line_count;
profiler_info->line_info = palloc0(profiler_info->line_count *
sizeof(profilerLineInfo));
estate->plugin_info = profiler_info;
}
/* -------------------------------------------------------------------
* profiler_func_beg()
*
* This hook function is called by the PL/pgSQL interpreter when a
* new function is starting. Specifically, this instrumentation
* hook is called after values have been assigned to all local
* variables (and all function parameters).
*
* 'estate' points to the stack frame for this function, 'func'
* points to the definition of the function
* -------------------------------------------------------------------
*/
static void
profiler_func_beg(PLpgSQL_execstate *estate, PLpgSQL_function *func)
{
if (!profiler_active)
return;
/* Ignore anonymous code block. */
if (estate->plugin_info == NULL)
return;
/*
* Push this function Oid onto the stack, remember the entry time and
* set the time spent in children to zero.
*/
callgraph_push(func->fn_oid);
}
/* -------------------------------------------------------------------
* profiler_func_end()
*
* This hook function is called by the PL/pgSQL interpreter when a
* function runs to completion.
* -------------------------------------------------------------------
*/
static void
profiler_func_end(PLpgSQL_execstate *estate, PLpgSQL_function *func)
{
profilerInfo *profiler_info;
linestatsHashKey key;
linestatsEntry *entry;
int i;
if (!profiler_active)
return;
/* Ignore anonymous code block. */
if (estate->plugin_info == NULL)
return;
/* Tell collect_data() that new information has arrived locally. */
have_new_local_data = true;
/* Find the linestats hash table entry for this function. */
profiler_info = (profilerInfo *) estate->plugin_info;
key.db_oid = MyDatabaseId;
key.fn_oid = func->fn_oid;
entry = (linestatsEntry *)hash_search(functions_hash, &key,
HASH_FIND, NULL);
if (!entry)
{
elog(DEBUG1, "plprofiler: local linestats entry for fn_oid %u "
"not found", func->fn_oid);
return;
}
/* Loop through each line of source code and update the stats */
for(i = 1; i < profiler_info->line_count; i++)
{
entry->line_info[i].exec_count +=
profiler_info->line_info[i].exec_count;
entry->line_info[i].us_total +=
profiler_info->line_info[i].us_total;
if (profiler_info->line_info[i].us_max > entry->line_info[i].us_max)
entry->line_info[i].us_max =
profiler_info->line_info[i].us_max;
}
/*
* Pop the call stack. This also does the time accounting
* for call graphs.
*/
callgraph_pop(func->fn_oid);
/*
* Finally if a plprofiler.collect_interval is configured, save and reset
* the stats if the interval has elapsed.
*/
if (profiler_shared_state != NULL &&
(profiler_shared_state->profiler_enabled_global ||
MyProcPid == profiler_shared_state->profiler_enabled_pid) &&
profiler_shared_state->profiler_collect_interval > 0)
{
time_t now = time(NULL);
if (now >= last_collect_time +
profiler_shared_state->profiler_collect_interval)
{
profiler_collect_data();
last_collect_time = now;
}
}
}
/* -------------------------------------------------------------------
* profiler_stmt_beg()
*
* This hook function is called by the PL/pgSQL interpreter just before
* executing a statement (stmt).
*
* Prior to executing each statement, we record the current time and
* the current values of all of the performance counters.
* -------------------------------------------------------------------
*/
static void
profiler_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
{
profilerLineInfo *line_info;
profilerInfo *profiler_info;
if (!profiler_active)
return;
/* Ignore anonymous code block. */
if (estate->plugin_info == NULL)
return;
/* Set the start time of the statement */
profiler_info = (profilerInfo *)estate->plugin_info;
if (stmt->lineno < profiler_info->line_count)
{
line_info = profiler_info->line_info + stmt->lineno;
INSTR_TIME_SET_CURRENT(line_info->start_time);
}
/* Check the call graph stack. */
callgraph_check(profiler_info->fn_oid);
}
/* -------------------------------------------------------------------
* profiler_stmt_end()
*
* This hook function is called by the PL/pgSQL interpreter just after
* it executes a statement (stmt).
*
* We use this hook to 'delta' the before and after performance counters
* and record the differences in the profilerStmtInfo structure associated
* with this statement.
* -------------------------------------------------------------------
*/
static void
profiler_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
{
profilerLineInfo *line_info;
profilerInfo *profiler_info;
instr_time end_time;
uint64 elapsed;
if (!profiler_active)
return;
/* Ignore anonymous code block. */
if (estate->plugin_info == NULL)
return;
profiler_info = (profilerInfo *)estate->plugin_info;
/*
* Ignore out of bounds line numbers. Someone is apparently
* profiling while executing DDL ... not much use in that.
*/
if (stmt->lineno >= profiler_info->line_count)
return;
/* Tell collect_data() that new information has arrived locally. */
have_new_local_data = true;
line_info = profiler_info->line_info + stmt->lineno;
INSTR_TIME_SET_CURRENT(end_time);
INSTR_TIME_SUBTRACT(end_time, line_info->start_time);
elapsed = INSTR_TIME_GET_MICROSEC(end_time);
if (elapsed > line_info->us_max)
line_info->us_max = elapsed;
line_info->us_total += elapsed;
line_info->exec_count++;
}
/**********************************************************************
* Helper functions
**********************************************************************/
/* -------------------------------------------------------------------
* init_hash_tables()
*
* Initialize hash table
* -------------------------------------------------------------------
*/
static void
init_hash_tables(void)
{
HASHCTL hash_ctl;
/* Create the memory context for our data */
if (profiler_mcxt != NULL)
{
if (profiler_mcxt->isReset)
return;
MemoryContextReset(profiler_mcxt);
}
else
{
profiler_mcxt = AllocSetContextCreate(TopMemoryContext,
"PL/pgSQL profiler",
ALLOCSET_DEFAULT_MINSIZE,
ALLOCSET_DEFAULT_INITSIZE,
ALLOCSET_DEFAULT_MAXSIZE);
}
/* Create the hash table for line stats */
MemSet(&hash_ctl, 0, sizeof(hash_ctl));
hash_ctl.keysize = sizeof(linestatsHashKey);
hash_ctl.entrysize = sizeof(linestatsEntry);
hash_ctl.hash = line_hash_fn;
hash_ctl.match = line_match_fn;
hash_ctl.hcxt = profiler_mcxt;
functions_hash = hash_create("Function Lines",
10000,
&hash_ctl,
HASH_ELEM | HASH_FUNCTION | HASH_COMPARE);
/* Create the hash table for call stats */
MemSet(&hash_ctl, 0, sizeof(hash_ctl));
hash_ctl.keysize = sizeof(callGraphKey);
hash_ctl.entrysize = sizeof(callGraphEntry);
hash_ctl.hash = callgraph_hash_fn;
hash_ctl.match = callgraph_match_fn;
hash_ctl.hcxt = profiler_mcxt;
callgraph_hash = hash_create("Function Call Graphs",
1000,
&hash_ctl,
HASH_ELEM | HASH_FUNCTION | HASH_COMPARE);
}
static void
profiler_shmem_startup(void)
{
bool found;
profilerSharedState *plpss;
Size plpss_size = 0;
HASHCTL hash_ctl;
if (prev_shmem_startup_hook)
prev_shmem_startup_hook();
/* Reset in case of restart inside of the postmaster. */
profiler_shared_state = NULL;
functions_shared = NULL;
callgraph_shared = NULL;
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
/* Create or attach to the shared state */
plpss_size = add_size(plpss_size,
offsetof(profilerSharedState, line_info));
plpss_size = add_size(plpss_size,
sizeof(linestatsLineInfo) * profiler_max_lines);
profiler_shared_state = ShmemInitStruct("plprofiler state", plpss_size,
&found);
plpss = profiler_shared_state;
if (!found)
{
memset(plpss, 0, offsetof(profilerSharedState, line_info) +
sizeof(linestatsLineInfo) * profiler_max_lines);
#if PG_VERSION_NUM >= 90600
plpss->lock = &(GetNamedLWLockTranche("plprofiler"))->lock;
#else
plpss->lock = LWLockAssign();
#endif
}
/* (Re)Initialize local hash tables. */
init_hash_tables();
/* Create or attache to the shared functions hash table */
memset(&hash_ctl, 0, sizeof(hash_ctl));
hash_ctl.keysize = sizeof(linestatsHashKey);
hash_ctl.entrysize = sizeof(linestatsEntry);
hash_ctl.hash = line_hash_fn;
hash_ctl.match = line_match_fn;
functions_shared = ShmemInitHash("plprofiler functions",
profiler_max_functions,
profiler_max_functions,
&hash_ctl,
HASH_ELEM | HASH_FUNCTION | HASH_COMPARE);
/* Create or attache to the shared callgraph hash table */
memset(&hash_ctl, 0, sizeof(hash_ctl));
hash_ctl.keysize = sizeof(callGraphKey);
hash_ctl.entrysize = sizeof(callGraphEntry);
hash_ctl.hash = callgraph_hash_fn;
hash_ctl.match = callgraph_match_fn;
callgraph_shared = ShmemInitHash("plprofiler callgraph",
profiler_max_callgraph,
profiler_max_callgraph,
&hash_ctl,
HASH_ELEM | HASH_FUNCTION | HASH_COMPARE);
LWLockRelease(AddinShmemInitLock);
}
/* -------------------------------------------------------------------
* find_source()
*
* This function locates and returns a pointer to a null-terminated string
* that contains the source code for the given function.
*
* In addition to returning a pointer to the requested source code, this
* function sets *tup to point to a HeapTuple (that you must release when
* you are finished with it) and sets *funcName to point to the name of
* the given function.
* -------------------------------------------------------------------
*/
static char *
find_source(Oid oid, HeapTuple *tup, char **funcName)
{
bool isNull;
*tup = SearchSysCache(PROCOID, ObjectIdGetDatum(oid), 0, 0, 0);
if(!HeapTupleIsValid(*tup))
elog(ERROR, "plprofiler: cache lookup for function %u failed", oid);
if (funcName != NULL)
*funcName = NameStr(((Form_pg_proc)GETSTRUCT(*tup))->proname);
return DatumGetCString(DirectFunctionCall1(textout,
SysCacheGetAttr(PROCOID,
*tup,
Anum_pg_proc_prosrc,
&isNull)));
}
/* -------------------------------------------------------------------
* count_source_lines()
*
* This function scans through the source code for a given function
* and counts the number of lines of code present in the string.
* -------------------------------------------------------------------
*/
static int
count_source_lines(const char *src)
{
int line_count = 1;
const char *cp = src;
while(cp != NULL)
{
line_count++;
cp = strchr(cp, '\n');
if (cp)
cp++;
}
return line_count;
}
static uint32
line_hash_fn(const void *key, Size keysize)
{
const linestatsHashKey *k = (const linestatsHashKey *) key;
return hash_uint32((uint32) k->fn_oid) ^
hash_uint32((uint32) k->db_oid);
}
static int
line_match_fn(const void *key1, const void *key2, Size keysize)
{
const linestatsHashKey *k1 = (const linestatsHashKey *)key1;
const linestatsHashKey *k2 = (const linestatsHashKey *)key2;
if (k1->fn_oid == k2->fn_oid &&
k1->db_oid == k2->db_oid)
return 0;
else
return 1;
}
static uint32
callgraph_hash_fn(const void *key, Size keysize)
{
return hash_any(key, keysize);
}
static int
callgraph_match_fn(const void *key1, const void *key2, Size keysize)
{
callGraphKey *stack1 = (callGraphKey *)key1;
callGraphKey *stack2 = (callGraphKey *)key2;
int i;
if (stack1->db_oid != stack2->db_oid)
return 1;
for (i = 0; i < PL_MAX_STACK_DEPTH && stack1->stack[i] != InvalidOid; i++)
if (stack1->stack[i] != stack2->stack[i])
return 1;
return 0;
}
static void
callgraph_push(Oid func_oid)
{
/*
* We only track function Oids in the call stack up to PL_MAX_STACK_DEPTH.
* Beyond that we just count the current stack depth.
*/
if (graph_stack_pt < PL_MAX_STACK_DEPTH)
{
/*
* Push this function Oid onto the stack, remember the entry time and
* set the time spent in children to zero.
*/
graph_stack.stack[graph_stack_pt] = func_oid;
INSTR_TIME_SET_CURRENT(graph_stack_entry[graph_stack_pt]);
graph_stack_child_time[graph_stack_pt] = 0;
}
graph_stack_pt++;
}
static void
callgraph_pop_one(void)
{
instr_time now;
uint64 us_elapsed;
uint64 us_self;
linestatsHashKey key;
linestatsEntry *entry;
/* Check for call stack underrun. */
if (graph_stack_pt <= 0)
{
elog(DEBUG1, "plprofiler: call graph stack underrun");
return;
}
/* Remove one level from the call stack. */
graph_stack_pt--;
/* Calculate the time spent in this function and record it. */
INSTR_TIME_SET_CURRENT(now);
INSTR_TIME_SUBTRACT(now, graph_stack_entry[graph_stack_pt]);
us_elapsed = INSTR_TIME_GET_MICROSEC(now);
us_self = us_elapsed - graph_stack_child_time[graph_stack_pt];
callgraph_collect(us_elapsed, us_self,
graph_stack_child_time[graph_stack_pt]);
/* If we have a caller, add our own time to the time of its children. */
if (graph_stack_pt > 0)
graph_stack_child_time[graph_stack_pt - 1] += us_elapsed;
/*
* We also collect per function global counts in the pseudo line number
* zero. The line stats are cumulative (for example a FOR ... LOOP
* statement has the entire execution time of all statements in its
* block), so this can't be derived from the actual per line data.
*/
key.fn_oid = graph_stack.stack[graph_stack_pt];
key.db_oid = MyDatabaseId;
entry = (linestatsEntry *)hash_search(functions_hash, &key, HASH_FIND, NULL);
if (entry)
{
entry->line_info[0].exec_count += 1;
entry->line_info[0].us_total += us_elapsed;
if (us_elapsed > entry->line_info[0].us_max)
entry->line_info[0].us_max = us_elapsed;
}
else
{
elog(DEBUG1, "plprofiler: local linestats entry for fn_oid %u "
"not found", graph_stack.stack[graph_stack_pt]);
}
/* Zap the oid from the call stack. */
graph_stack.stack[graph_stack_pt] = InvalidOid;
}
static void
callgraph_pop(Oid func_oid)
{
callgraph_check(func_oid);
callgraph_pop_one();
}
static void
callgraph_check(Oid func_oid)
{
/*
* Unwind the call stack until our own func_oid appears on the top.
*
* In case of an exception, the pl executor does not call the
* func_end callback, so we record now as the end of the function
* calls, that were left on the stack.
*/
while (graph_stack_pt > 0
&& graph_stack.stack[graph_stack_pt - 1] != func_oid)
{
elog(DEBUG1, "plprofiler: unwinding excess call graph stack entry for %u in %u",
graph_stack.stack[graph_stack_pt - 1], func_oid);
callgraph_pop_one();
}
}
static void
callgraph_collect(uint64 us_elapsed, uint64 us_self, uint64 us_children)
{
callGraphEntry *entry;
bool found;
graph_stack.db_oid = MyDatabaseId;
entry = (callGraphEntry *)hash_search(callgraph_hash, &graph_stack,
HASH_ENTER, &found);
if (!found)
{
entry->callCount = 1;
entry->totalTime = us_elapsed;
entry->childTime = us_children;
entry->selfTime = us_self;
}
else
{
entry->callCount++;
entry->totalTime = entry->totalTime + us_elapsed;
entry->childTime = entry->childTime + us_children;
entry->selfTime = entry->selfTime + us_self;
}
}
static int32
profiler_collect_data(void)
{
HASH_SEQ_STATUS hash_seq;
callGraphEntry *cge1;
callGraphEntry *cge2;
linestatsEntry *lse1;
linestatsEntry *lse2;
profilerSharedState *plpss = profiler_shared_state;
bool have_exclusive_lock = false;
bool found;
int i;
/*
* Return without doing anything if the plprofiler extension
* was not loaded via shared_preload_libraries. We don't have
* any shared memory state in that case.
*/
if (plpss == NULL)
return -1;
/*
* Don't waste any time here if there was no new data recorded
* since the last collect_data() call.
*/
if (!have_new_local_data)
return 0;
have_new_local_data = false;
/*
* Acquire a shared lock on the shared hash tables. We escalate
* to an exclusive lock later in case we need to add a new entry.
*/
LWLockAcquire(plpss->lock, LW_SHARED);
/* Collect the callgraph data into shared memory. */
hash_seq_init(&hash_seq, callgraph_hash);
while ((cge1 = hash_seq_search(&hash_seq)) != NULL)
{
cge2 = hash_search(callgraph_shared, &(cge1->key),
HASH_FIND, NULL);
if (cge2 == NULL)
{
/*
* This callgraph is not yet known in shared memory.
* Need to escalate the lock to exclusive.
*/
if (!have_exclusive_lock)
{
LWLockRelease(plpss->lock);
LWLockAcquire(plpss->lock, LW_EXCLUSIVE);
have_exclusive_lock = true;
}
cge2 = hash_search(callgraph_shared, &(cge1->key),
HASH_ENTER, &found);
if (cge2 == NULL)
{
/*
* This means that we are out of shared memory for the
* callgraph_shared hash table. Nothing we can do
* here but complain.
*/
if (!plpss->callgraph_overflow)
{
elog(LOG,
"plprofiler: entry limit reached for "
"shared memory call graph data");
plpss->callgraph_overflow = true;
}
break;
}
/*
* Since we released the lock above for lock escalation to
* exclusive, it is possible that someone else in the meantime
* created the entry for this call graph.
*/
if (!found)
{
/*
* We created a new entry for this call graph in the
* shared hash table. Initialize it.