-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpg_dbms_errlog.c
More file actions
1318 lines (1156 loc) · 33 KB
/
pg_dbms_errlog.c
File metadata and controls
1318 lines (1156 loc) · 33 KB
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_dbms_errlog.c:
* pg_dbms_errlog is a PostgreSQL extension that logs each failing DML
* query. It emulates the DBMS_ERRLOG Oracle module.
*
* This program is open source, licensed under the PostgreSQL license.
* For license terms, see the LICENSE file.
*
* Copyright (C) 2021-2023: MigOps Inc
* Copyright (c) 2023-2025: HexaCluster Corp.
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/genam.h"
#include "access/heapam.h"
#if PG_VERSION_NUM >= 130000
#include "access/table.h"
#else
/* for imported functions */
#include "mb/pg_wchar.h"
#endif
#include "access/xact.h"
#include "catalog/dependency.h"
#include "catalog/namespace.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_namespace.h"
#include "executor/executor.h"
#include "executor/spi.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "parser/analyze.h"
#include "parser/parser.h"
#include "postmaster/bgworker.h"
#include "storage/ipc.h"
#include "storage/proc.h"
#include "tcop/tcopprot.h"
#include "tcop/utility.h"
#include "utils/builtins.h"
#include "utils/elog.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#if PG_VERSION_NUM < 110000
#include "utils/memutils.h"
#endif
#include "utils/rel.h"
#include "utils/syscache.h"
#include "utils/varlena.h"
#if PG_VERSION_NUM >= 140000
#include "utils/wait_event.h"
#else
#include "pgstat.h"
#endif
#include "include/pg_dbms_errlog.h"
#include "include/pel_errqueue.h"
#if PG_VERSION_NUM < 100000
#error Minimum version of PostgreSQL required is 10
#endif
/* Define ProcessUtility hook proto/parameters following the PostgreSQL version */
#if PG_VERSION_NUM >= 140000
#define PEL_PROCESSUTILITY_PROTO PlannedStmt *pstmt, const char *queryString, \
bool readOnlyTree, \
ProcessUtilityContext context, ParamListInfo params, \
QueryEnvironment *queryEnv, DestReceiver *dest, \
QueryCompletion *qc
#define PEL_PROCESSUTILITY_ARGS pstmt, queryString, readOnlyTree, context, params, queryEnv, dest, qc
#elif PG_VERSION_NUM >= 130000
#define PEL_PROCESSUTILITY_PROTO PlannedStmt *pstmt, const char *queryString, \
ProcessUtilityContext context, ParamListInfo params, \
QueryEnvironment *queryEnv, DestReceiver *dest, \
QueryCompletion *qc
#define PEL_PROCESSUTILITY_ARGS pstmt, queryString, context, params, queryEnv, dest, qc
#else
#define PEL_PROCESSUTILITY_PROTO PlannedStmt *pstmt, const char *queryString, \
ProcessUtilityContext context, ParamListInfo params, \
QueryEnvironment *queryEnv, DestReceiver *dest, \
char *completionTag
#define PEL_PROCESSUTILITY_ARGS pstmt, queryString, context, params, queryEnv, dest, completionTag
#endif
#define PEL_REGISTRATION_TABLE "register_errlog_tables"
#define Anum_pel_relid 1
#define Anum_pel_errlogid 2
#define MAX_PREPARED_STMT_SIZE 1048576
PG_MODULE_MAGIC;
#define PEL_TRANCHE_NAME "pg_dbms_errlog"
/* Saved hook values in case of unload */
#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 ProcessUtility_hook_type prev_ProcessUtility = 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 emit_log_hook_type prev_emit_log_hook = NULL;
static post_parse_analyze_hook_type prev_post_parse_analyze_hook = NULL;
/* Links to shared memory state */
pelSharedState *pel = NULL;
dsa_area *pel_area = NULL;
/* GUC variables */
typedef enum
{
PEL_SYNC_OFF, /* never wait for queued errors processing */
PEL_SYNC_QUERY, /* wait for every error */
PEL_SYNC_XACT /* wait at the end of the xact (implicit or not) */
} pelSyncLevel;
static const struct config_enum_entry pel_sync_options[] =
{
{"off", PEL_SYNC_OFF, false},
{"query", PEL_SYNC_QUERY, false},
{"transaction", PEL_SYNC_XACT, false},
{NULL, 0, false}
};
#define PEL_SYNC_ON_QUERY() (pel_synchronous == PEL_SYNC_QUERY || \
(pel_synchronous == PEL_SYNC_XACT && !IsTransactionBlock()))
/*
* We also have to wait for completion if level is PEL_SYNC_QUERY and we're in
* a transaction block, as it could have be raised from PEL_SYNC_OFF just
* before a COMMIT, which should force a sync
*/
#define PEL_SYNC_ON_XACT() (pel_synchronous == PEL_SYNC_XACT || \
(pel_synchronous == PEL_SYNC_QUERY && IsTransactionBlock()))
bool pel_debug = false;
bool pel_done = false;
bool pel_enabled = false;
int pel_frequency = 60;
int pel_max_workers = 1;
int pel_reject_limit = -1;
char *query_tag = NULL;
int pel_synchronous = PEL_SYNC_XACT;
bool pel_no_client_error = true;
/* global variable used to store DML table name */
char *current_dml_table = NULL;
char current_dml_kind = '\0';
char *current_bind_parameters = NULL;
/* Current nesting depth of ExecutorRun calls */
static int exec_nested_level = 0;
/* cache to store query of prepared stamement */
struct HTAB *PreparedCache = NULL;
/* Functions declaration */
void _PG_init(void);
extern PGDLLEXPORT Datum pg_dbms_errlog_publish_queue(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(pg_dbms_errlog_publish_queue);
extern PGDLLEXPORT Datum pg_dbms_errlog_queue_size(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(pg_dbms_errlog_queue_size);
#if PG_VERSION_NUM >= 150000
static void pel_shmem_request(void);
#endif
static void pel_shmem_startup(void);
static void pel_ProcessUtility(PEL_PROCESSUTILITY_PROTO);
static void pel_ExecutorStart(QueryDesc *queryDesc, int eflags);
static void pel_ExecutorRun(QueryDesc *queryDesc,
ScanDirection direction,
uint64 count
#if PG_VERSION_NUM < 180000
, bool execute_once
#endif
);
static void pel_ExecutorFinish(QueryDesc *queryDesc);
static void pel_ExecutorEnd(QueryDesc *queryDesc);
static void pel_log_error(ErrorData *edata);
static Size pel_memsize(void);
char *lookupCachedPrepared(const char *preparedName);
void removeCachedPrepared(const char *localPreparedName);
static void pel_setupCachedPreparedHash(void);
void putCachedPrepared(const char *preparedName, const char *preparedStmt);
char *get_relation_name(Oid relid);
void generate_error_message (ErrorData *edata, StringInfoData *buf);
void append_with_tabs(StringInfo buf, const char *str);
#if PG_VERSION_NUM < 130000
/* Copied from src/backend/nodes/params.c for older versions */
char *BuildParamLogString(ParamListInfo params, char **knownTextValues, int maxlen);
/* Copied from src/backend/utils/mb/stringinfo_mb.c */
void appendStringInfoStringQuoted(StringInfo str, const char *s, int maxlen);
/* Copied from src/backend/access/transam/xact.c */
/* Adapted from src/backend/nodes/list.c */
static List *list_copy_deep(const List *oldlist);
#endif
#if PG_VERSION_NUM < 110000
static void appendBinaryStringInfoNT(StringInfo str, const char *data, int datalen);
#endif
typedef struct PreparedCacheKey
{
char preparedName[NAMEDATALEN];
} PreparedCacheKey;
typedef struct PreparedCacheEntry
{
PreparedCacheKey key;
char preparedStmt[MAX_PREPARED_STMT_SIZE];
} PreparedCacheEntry;
static void
pel_setupCachedPreparedHash(void)
{
/* Initialize cache */
if (PreparedCache == NULL)
{
HASHCTL ctl;
MemSet(&ctl, 0, sizeof(ctl));
ctl.keysize = sizeof(PreparedCacheKey);
ctl.entrysize = sizeof(PreparedCacheEntry);
/* allocate PrepareHash in the cache context */
ctl.hcxt = CacheMemoryContext;
PreparedCache = hash_create("pg_dbms_errlog_prepares", 8, &ctl,
HASH_ELEM | HASH_CONTEXT | HASH_BLOBS);
}
}
void
putCachedPrepared(const char *preparedName, const char *preparedStmt)
{
PreparedCacheKey key = { { 0 } };
PreparedCacheEntry *entry;
bool found;
pel_setupCachedPreparedHash();
strncpy(key.preparedName, preparedName, sizeof(PreparedCacheKey));
entry = hash_search(PreparedCache, &key, HASH_ENTER, &found);
if (found)
{
elog(ERROR, "PREPAREDCACHE: Prepared statement '%s' already exist in cache with query: %s",
preparedName, entry->preparedStmt);
}
else
{
elog(DEBUG1, "PREPAREDCACHE: Add prepared statement '%s' with query '%s'",
preparedName, preparedStmt);
strncpy(entry->preparedStmt, preparedStmt, sizeof(entry->preparedStmt));
}
}
void
removeCachedPrepared(const char *preparedName)
{
PreparedCacheKey key = { { 0 } }; // zero out the key, no trailing garbage
PreparedCacheEntry *entry;
bool found;
pel_setupCachedPreparedHash();
strncpy(key.preparedName, preparedName, sizeof(PreparedCacheKey));
entry = hash_search(PreparedCache, &key, HASH_REMOVE, &found);
if (found)
elog(DEBUG1, "PREPAREDCACHE: Prepared statement '%s' exist in cache with query '%s'",
preparedName, entry->preparedStmt);
else
elog(DEBUG1, "PREPAREDCACHE: Prepared statement '%s' to remove not in cache",
preparedName);
}
char *
lookupCachedPrepared(const char *preparedName)
{
PreparedCacheKey key = { { 0 } };
PreparedCacheEntry *entry;
bool found;
pel_setupCachedPreparedHash();
strncpy(key.preparedName, preparedName, sizeof(PreparedCacheKey));
entry = hash_search(PreparedCache, &key, HASH_FIND, &found);
if (!found)
elog(ERROR, "Prepared statement '%s' is not found in cache", preparedName);
elog(DEBUG1, "PREPAREDCACHE: prepared statement '%s' found in cache with query: %s",
key.preparedName, entry->preparedStmt);
return entry->preparedStmt;
}
/*
* Module load callback
*/
void
_PG_init(void)
{
BackgroundWorker worker;
if (!process_shared_preload_libraries_in_progress)
{
elog(ERROR, "This module can only be loaded via shared_preload_libraries");
return;
}
/* Define custom GUC variables */
DefineCustomBoolVariable( "pg_dbms_errlog.debug",
"Enable/disable debug traces.",
NULL,
&pel_debug,
false,
PGC_USERSET, /* Any user can set it */
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable( "pg_dbms_errlog.enabled",
"Enable/disable log of failing queries.",
NULL,
&pel_enabled,
false,
PGC_USERSET, /* Any user can set it */
0,
NULL,
NULL,
NULL);
DefineCustomIntVariable("pg_dbms_errlog.frequency",
"Defines the frequency for checking for data to process",
NULL,
&pel_frequency,
60,
10,
3600,
PGC_SUSET,
GUC_UNIT_S,
NULL,
NULL,
NULL);
DefineCustomIntVariable("pg_dbms_errlog.max_workers",
"Defines the maximum number of bgworker to launch to process data",
NULL,
&pel_max_workers,
1,
1,
max_worker_processes,
PGC_POSTMASTER,
0,
NULL,
NULL,
NULL);
DefineCustomIntVariable("pg_dbms_errlog.reject_limit",
"Maximum number of errors that can be encountered before the DML"
" statement terminates and rolls back. A value of -1 mean unlimited,"
" this is the default. When reject limit is zero no error is logged"
" and the statement rolls back.",
NULL,
&pel_reject_limit,
-1,
-1,
INT_MAX,
PGC_USERSET, /* Any user can set it */
0,
NULL,
NULL,
NULL);
DefineCustomStringVariable( "pg_dbms_errlog.query_tag",
"Tag (a numeric or string literal in parentheses) that gets added"
" to the error log to help identify the statement that caused the"
" errors. If the tag is omitted, a NULL value is used.",
NULL,
&query_tag,
NULL,
PGC_USERSET, /* Any user can set it */
0,
NULL,
NULL,
NULL );
DefineCustomEnumVariable("pg_dbms_errlog.synchronous",
"Wait for error queue completion when an error happens",
NULL,
&pel_synchronous,
PEL_SYNC_XACT,
pel_sync_options,
PGC_USERSET,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("pg_dbms_errlog.no_client_error",
"Enable/disable client error logging",
NULL,
&pel_no_client_error,
true,
PGC_USERSET,
0,
NULL,
NULL,
NULL);
EmitWarningsOnPlaceholders("pg_dbms_errlog");
#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 pel_shmem_startup().
*
* If you change code here, don't forget to also report the modifications
* in pel_shmem_request() for pg15 and later.
*/
RequestAddinShmemSpace(pel_memsize());
RequestNamedLWLockTranche(PEL_TRANCHE_NAME, 1);
#endif
/* Install hooks */
#if PG_VERSION_NUM >= 150000
prev_shmem_request_hook = shmem_request_hook;
shmem_request_hook = pel_shmem_request;
#endif
prev_shmem_startup_hook = shmem_startup_hook;
shmem_startup_hook = pel_shmem_startup;
prev_ProcessUtility = ProcessUtility_hook;
ProcessUtility_hook = pel_ProcessUtility;
prev_ExecutorStart = ExecutorStart_hook;
ExecutorStart_hook = pel_ExecutorStart;
prev_ExecutorRun = ExecutorRun_hook;
ExecutorRun_hook = pel_ExecutorRun;
prev_ExecutorFinish = ExecutorFinish_hook;
ExecutorFinish_hook = pel_ExecutorFinish;
prev_ExecutorEnd = ExecutorEnd_hook;
ExecutorEnd_hook = pel_ExecutorEnd;
prev_emit_log_hook = emit_log_hook;
emit_log_hook = pel_log_error;
prev_post_parse_analyze_hook = post_parse_analyze_hook;
memset(&worker, 0, sizeof(BackgroundWorker));
worker.bgw_flags = BGWORKER_SHMEM_ACCESS;
worker.bgw_start_time = BgWorkerStart_RecoveryFinished;
snprintf(worker.bgw_library_name, BGW_MAXLEN, "pg_dbms_errlog");
snprintf(worker.bgw_function_name, BGW_MAXLEN, "pel_worker_main");
snprintf(worker.bgw_name, BGW_MAXLEN, "pg_dbms_errlog main worker");
worker.bgw_restart_time = 0;
worker.bgw_main_arg = (Datum) 0;
worker.bgw_notify_pid = 0;
RegisterBackgroundWorker(&worker);
}
PGDLLEXPORT Datum
pg_dbms_errlog_publish_queue(PG_FUNCTION_ARGS)
{
bool sync;
int pos;
if (PG_ARGISNULL(0))
sync = false;
else
sync = PG_GETARG_BOOL(0);
pos = pel_publish_queue(sync);
PG_RETURN_BOOL(pos != PEL_PUBLISH_ERROR);
}
PGDLLEXPORT Datum
pg_dbms_errlog_queue_size(PG_FUNCTION_ARGS)
{
int num = pel_queue_size();
if (num == -1)
PG_RETURN_NULL();
else
PG_RETURN_INT32(num);
}
#if PG_VERSION_NUM >= 150000
static void
pel_shmem_request(void)
{
if (prev_shmem_request_hook)
prev_shmem_request_hook();
/*
* If you change code here, don't forget to also report the modifications in
* _PG_init() for pg14 and below.
*/
RequestAddinShmemSpace(pel_memsize());
RequestNamedLWLockTranche(PEL_TRANCHE_NAME, 1);
}
#endif
static void
pel_shmem_startup(void)
{
bool found;
if (prev_shmem_startup_hook)
prev_shmem_startup_hook();
/* reset in case this is a restart within the postmaster */
pel = NULL;
/* Create or attach to the shared memory state */
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
pel = ShmemInitStruct("pg_dbms_errlog",
pel_memsize(),
&found);
if (!found)
{
int trancheid;
/* First time through ... */
pel->bgw_saved_cur = 0;
#if PG_VERSION_NUM < 170000
pg_atomic_init_u32(&pel->bgw_procno, INVALID_PGPROCNO);
StaticAssertStmt(sizeof(INVALID_PGPROCNO <= sizeof(pel->bgw_procno)),
"INVALID_PGPROCNO is bigger for uint32");
#else
pg_atomic_init_u32(&pel->bgw_procno, INVALID_PROC_NUMBER);
StaticAssertStmt(sizeof(INVALID_PROC_NUMBER <= sizeof(pel->bgw_procno)),
"INVALID_PROC_NUMBER is bigger for uint32");
#endif
pel->lock = &(GetNamedLWLockTranche(PEL_TRANCHE_NAME))->lock;
pel->pel_dsa_handle = DSM_HANDLE_INVALID;
pel->pqueue = InvalidDsaPointer;
pel->max_errs = 0;
pel->cur_err = 0;
pel->bgw_err = 0;
/* try to guess our trancheid */
for (trancheid = LWTRANCHE_FIRST_USER_DEFINED; ; trancheid++)
{
if (strcmp(GetLWLockIdentifier(PG_WAIT_LWLOCK, trancheid),
PEL_TRANCHE_NAME) == 0)
{
/* Found it! */
break;
}
if ((trancheid - LWTRANCHE_FIRST_USER_DEFINED) > 50)
{
/* No point trying so hard, just give up. */
trancheid = LWTRANCHE_FIRST_USER_DEFINED;
break;
}
}
Assert(trancheid >= LWTRANCHE_FIRST_USER_DEFINED);
pel->LWTRANCHE_PEL = trancheid;
}
LWLockRelease(AddinShmemInitLock);
}
static void
pel_ProcessUtility(PEL_PROCESSUTILITY_PROTO)
{
Node *parsetree = pstmt->utilityStmt;
pel_done = false;
if (IsA(parsetree, PrepareStmt))
{
PrepareStmt *stmt = (PrepareStmt *) parsetree;
putCachedPrepared(stmt->name, debug_query_string);
}
else if (IsA(parsetree, DeallocateStmt))
{
DeallocateStmt *stmt = (DeallocateStmt *) parsetree;
removeCachedPrepared(stmt->name);
}
/* Excecute the utility command, we are not concerned */
if (prev_ProcessUtility)
prev_ProcessUtility(PEL_PROCESSUTILITY_ARGS);
else
standard_ProcessUtility(PEL_PROCESSUTILITY_ARGS);
/* Publish or discard queue on COMMIT/ROLLBACK */
if (IsA(parsetree, TransactionStmt))
{
TransactionStmt *stmt = (TransactionStmt *) parsetree;
/* Check if the commit really performed a commit */
if (stmt->kind == TRANS_STMT_COMMIT)
{
bool is_commit = false;
#if PG_VERSION_NUM >= 130000
if (!qc)
{
/* no way to tell, assume commit did happen */
is_commit = true;
}
else if (qc->commandTag != CMDTAG_ROLLBACK)
is_commit = true;
#else
if (strcmp(completionTag, "ROLLBACK") != 0)
is_commit = true;
#endif
if (is_commit)
{
if (pel_publish_queue(PEL_SYNC_ON_XACT()) == PEL_PUBLISH_ERROR)
elog(WARNING, "could not publish the queue");
}
else
pel_discard_queue();
}
else if (stmt->kind == TRANS_STMT_ROLLBACK)
pel_discard_queue();
}
}
static void
pel_ExecutorStart(QueryDesc *queryDesc, int eflags)
{
if (pel_enabled)
{
if (queryDesc->dest->mydest != DestSPI)
{
if (queryDesc->operation == CMD_INSERT)
current_dml_kind = 'I';
else if (queryDesc->operation == CMD_UPDATE)
current_dml_kind = 'U';
else if (queryDesc->operation == CMD_DELETE)
current_dml_kind = 'D';
else
current_dml_kind = '?';
}
if (exec_nested_level == 0)
{
pel_done = false;
if (current_bind_parameters != NULL)
{
pfree(current_bind_parameters);
current_bind_parameters = NULL;
}
}
if (!pel_done)
{
if (queryDesc->params && queryDesc->params->numParams > 0)
current_bind_parameters = BuildParamLogString(queryDesc->params, NULL, -1);
else
current_bind_parameters = NULL;
}
}
if (prev_ExecutorStart)
prev_ExecutorStart(queryDesc, eflags);
else
standard_ExecutorStart(queryDesc, eflags);
}
/*
* ExecutorRun hook: all we need do is track nesting depth
*/
static void
pel_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count
#if PG_VERSION_NUM < 180000
,bool execute_once
#endif
)
{
exec_nested_level++;
PG_TRY();
{
if (prev_ExecutorRun)
prev_ExecutorRun(queryDesc, direction, count
#if PG_VERSION_NUM < 180000
, execute_once
#endif
);
else
standard_ExecutorRun(queryDesc, direction, count
#if PG_VERSION_NUM < 180000
, execute_once
#endif
);
exec_nested_level--;
}
PG_CATCH();
{
exec_nested_level--;
PG_RE_THROW();
}
PG_END_TRY();
}
/*
* ExecutorFinish hook: all we need do is track nesting depth
*/
static void
pel_ExecutorFinish(QueryDesc *queryDesc)
{
exec_nested_level++;
PG_TRY();
{
if (prev_ExecutorFinish)
prev_ExecutorFinish(queryDesc);
else
standard_ExecutorFinish(queryDesc);
exec_nested_level--;
}
PG_CATCH();
{
exec_nested_level--;
PG_RE_THROW();
}
PG_END_TRY();
}
/*
* ExecutorEnd hook: done required cleanup
*/
static void
pel_ExecutorEnd(QueryDesc *queryDesc)
{
if (pel_enabled && exec_nested_level == 0)
{
if (current_bind_parameters != NULL)
{
pfree(current_bind_parameters);
current_bind_parameters = NULL;
}
}
if (prev_ExecutorEnd)
prev_ExecutorEnd(queryDesc);
else
standard_ExecutorEnd(queryDesc);
}
/*
* Log statement according to the user that launched the statement.
*/
static void
pel_log_error(ErrorData *edata)
{
if (!pel_enabled
|| !edata || edata->elevel != ERROR /* Only process errors */
|| !debug_query_string /* Ignore errors raised from non-backend processes */
|| edata->sqlerrcode == ERRCODE_SUCCESSFUL_COMPLETION
)
{
goto prev_hook;
}
if (!pel_done)
{
MemoryContext pelcontext, oldcontext;
List *stmts;
RawStmt *raw;
Node *stmt;
const char *sql = debug_query_string;
CmdType cmdType = CMD_UNKNOWN;
char *operation = NULL;
RangeVar *rv = NULL;
Oid relid;
pel_done = true; /* prevent recursive call */
pelcontext = AllocSetContextCreate(CurTransactionContext,
"PEL temporary context",
ALLOCSET_DEFAULT_SIZES);
oldcontext = MemoryContextSwitchTo(pelcontext);
#if PG_VERSION_NUM >= 140000
stmts = raw_parser(sql, RAW_PARSE_DEFAULT);
#else
stmts = raw_parser(sql);
#endif
MemoryContextSwitchTo(oldcontext);
stmts = list_copy_deep(stmts);
MemoryContextDelete(pelcontext);
if (list_length(stmts) != 1)
{
elog(WARNING, "pel_log_error(): not supported");
goto prev_hook;
}
raw = (RawStmt *) linitial(stmts);
stmt = raw->stmt;
if (IsA(stmt, ExecuteStmt))
{
ExecuteStmt *s = (ExecuteStmt *) stmt;
sql = lookupCachedPrepared(s->name);
#if PG_VERSION_NUM >= 140000
stmts = raw_parser(sql, RAW_PARSE_DEFAULT);
#else
stmts = raw_parser(sql);
#endif
if (list_length(stmts) != 1)
{
elog(WARNING, "not supported");
goto prev_hook;
}
raw = (RawStmt *) linitial(stmts);
Assert(IsA(raw->stmt, PrepareStmt));
stmt = ((PrepareStmt *) raw->stmt)->query;
}
if(IsA(stmt, InsertStmt))
{
rv = ((InsertStmt *) stmt)->relation;
cmdType = CMD_INSERT;
operation = "INSERT";
current_dml_kind = 'I';
}
else if (IsA(stmt, UpdateStmt))
{
rv = ((UpdateStmt *) stmt)->relation;
cmdType = CMD_UPDATE;
operation = "UPDATE";
current_dml_kind = 'U';
}
else if (IsA(stmt, DeleteStmt))
{
rv = ((DeleteStmt *) stmt)->relation;
cmdType = CMD_DELETE;
operation = "DELETE";
current_dml_kind = 'D';
}
if (cmdType == CMD_UNKNOWN)
{
/* Unhandled DML, bail out */
goto prev_hook;
}
else
{
Assert(rv != NULL);
Assert(operation != NULL);
}
relid = RangeVarGetRelid(rv, AccessShareLock, true);
if (!OidIsValid(relid))
{
if (rv->schemaname)
elog(WARNING, "could not find an oid for relation \"%s\".\"%s\"",
rv->schemaname, rv->relname);
else
elog(WARNING, "could not find an oid for relation \"%s\"",
rv->relname);
goto prev_hook;
}
elog(DEBUG1, "pel_log_error(): OPERATION: %s, KIND: %c, RELID: %u", operation, current_dml_kind, relid);
/* Get the associated error logging table if any */
if (OidIsValid(relid))
{
StringInfoData relstmt;
StringInfoData msg;
int rc = 0;
Oid logtable;
bool isnull, ok;
bool need_priv_escalation = !superuser(); /* we might be a SU */
Oid save_userid;
int save_sec_context;
Relation rel;
AclResult aclresult;
initStringInfo(&relstmt);
/* Inserting error to log table must be created as SU */
if (need_priv_escalation)
{
/* Get current user's Oid and security context */
GetUserIdAndSecContext(&save_userid, &save_sec_context);
/* Become superuser */
SetUserIdAndSecContext(BOOTSTRAP_SUPERUSERID, save_sec_context
| SECURITY_LOCAL_USERID_CHANGE
| SECURITY_RESTRICTED_OPERATION);
}
rc = SPI_connect();
if (rc != SPI_OK_CONNECT)
{
elog(WARNING, "Can not connect to SPI manager to retrieve"
" error log table for \"%s\", rc=%d. ",
rv->relname, rc);
goto prev_hook;
}
appendStringInfo(&relstmt, "SELECT e.relerrlog"
" FROM %s.%s e"
" WHERE e.reldml = %u",
quote_identifier(PEL_NAMESPACE_NAME),
quote_identifier(PEL_REGISTRATION_TABLE),
relid);
rc = SPI_exec(relstmt.data, 0);
if (rc != SPI_OK_SELECT || SPI_processed != 1)
{
elog(WARNING, "SPI execution failure (rc=%d) on query: %s",
rc, relstmt.data);
goto prev_hook;
}
logtable = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0],
SPI_tuptable->tupdesc,
1,
&isnull));
if (isnull)
{
elog(WARNING, "can not get error logging table for table %s",
relstmt.data);
goto prev_hook;
}
rc = SPI_finish();
if (rc != SPI_OK_FINISH)
{
elog(WARNING, "could not disconnect from SPI manager");
goto prev_hook;
}
/* Restore user's privileges */
if (need_priv_escalation)
SetUserIdAndSecContext(save_userid, save_sec_context);
/*
* Try to open the error log relation to catch priviledge issues
* as the bg_worker will have the full priviledge on the table.
*/
rel = table_open(logtable, AccessShareLock);
aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
ACL_INSERT);
if (aclresult != ACLCHECK_OK)
aclcheck_error(aclresult, get_relkind_objtype(rel->rd_rel->relkind),
RelationGetRelationName(rel));
table_close(rel, AccessShareLock);
/* generate the full error message to log */
initStringInfo(&msg);
generate_error_message(edata, &msg);
if (current_bind_parameters && current_bind_parameters[0] != '\0')
{
appendStringInfo(&msg, "PARAMETERS: %s",
current_bind_parameters);
}
/* Queue the error information. */
ok = pel_queue_error(logtable,
edata->sqlerrcode,
edata->message,
current_dml_kind,
query_tag,
sql,
msg.data,
PEL_SYNC_ON_QUERY());
if (!ok)
goto prev_hook;
elog(DEBUG1, "pel_log_error(): ERRCODE: %s;KIND: %c,TAG: %s;MESSAGE: %s;QUERY: %s;TABLE: %s; INFO: %s",
unpack_sql_state(edata->sqlerrcode),
current_dml_kind,
(query_tag) ? query_tag : "null",
(edata->message) ? edata->message : "null",
quote_literal_cstr(sql),
rv->relname,
msg.data
);
}
if (pel_no_client_error)
edata->output_to_client = false;
}
pel_done = false;
prev_hook:
if (current_bind_parameters != NULL)
{
pfree(current_bind_parameters);
current_bind_parameters = NULL;