#ifndef TRANDLOG_C
|
#define TRANDLOG_C
|
|
#include <time.h>
|
|
#include "postgres.h"
|
#include "executor/executor.h"
|
#include "executor/spi.h"
|
#include "nodes/pg_list.h"
|
#include "parser/analyze.h"
|
#include "tcop/utility.h"
|
#include "tcop/pquery.h"
|
#include "utils/memutils.h"
|
#include "commands/explain.h"
|
#include "utils/snapmgr.h"
|
|
#include <openssl/sha.h>
|
#include <libpq/libpq-be.h>
|
#include "miscadmin.h" // Для MyProcPort
|
|
#include "string_array.c"
|
#include "sql_proc.c"
|
|
#define LONG_WAY
|
|
#define MAX_SQL_MASK_LEN 10240
|
#define MAX_SQL_STR_LEN (MAX_SQL_MASK_LEN * 10)
|
|
//PG_MODULE_MAGIC;
|
#define ELOG(...) if (!no_logging) elog(__VA_ARGS__)
|
|
static bool no_conversion;
|
static bool full_conversion;
|
static bool no_logging=false;
|
static int id_len = 4;
|
static int log_format = 1;
|
|
void _TRANDLOG_init(void);
|
void _TRANDLOG_fini(void);
|
|
static ExecSimpleQuery_hook_type prev_ExecSimpleQuery = NULL;
|
static void my_ExecSimpleQuery(const char *query_string);
|
|
static int calculate_sha1(const char *str, char *sha1_hex_str);
|
static int save_string(const char *input_str);
|
static int search_mask(const char *input_request_mask, char *output_str);
|
static int save_string(const char *input_str);
|
|
#define SHA_DIGEST_LENGTH 20
|
#define HEX_STR_HASH_LEN ((SHA_DIGEST_LENGTH<<1) + 1)
|
|
#define FILE_PATH "/opt/qdb/config/trandlog.csv" // "/tmp/sha1strtab.csv"
|
#define LOG_PATH "/opt/qdb/logs/trandlog.log" // "/tmp/converter.log"
|
|
int calculate_sha1(const char *str, char *sha1_hex_str) {
|
unsigned char digest[SHA_DIGEST_LENGTH];
|
SHA1((unsigned char*)str, strlen(str), digest);
|
|
for (int i = 0; i < SHA_DIGEST_LENGTH; i++) {
|
sprintf(&sha1_hex_str[i * 2], "%02x", (unsigned int)digest[i]);
|
}
|
|
return 0;
|
}
|
|
static void write_log(char *log_str, char *start_time_str, double ms, int byte_count)
|
{
|
uint64_t truncated_connection_id;
|
char format_str[64];
|
FILE *file = fopen(LOG_PATH, "a+");
|
if (!file) {
|
ELOG(ERROR, _("(TRandLOG.function) Error while writing the log"));
|
return;
|
}
|
|
// Ограничиваем byte_count допустимыми значениями
|
if ((byte_count < 0) || (byte_count > 8)) {
|
byte_count = 4;
|
}
|
|
truncated_connection_id = MyProcPort->connection_id;
|
if (byte_count < 8) {
|
truncated_connection_id &= ((uint64_t)1 << (byte_count * 8)) - 1; // для меньших значений
|
}
|
|
// Создаем строку формата
|
|
snprintf(format_str, sizeof(format_str), "[%%.%dlX]\t%%s\t%%.3f\t%%s\n", byte_count * 2);
|
|
// Логируем данные с учетом ограничения байтов
|
fprintf(file, format_str, truncated_connection_id, start_time_str, ms, log_str);
|
|
fclose(file);
|
}
|
|
int search_mask(const char *input_request_mask, char *output_str) {
|
int result = -1;
|
const int line_size = 5 * MAX_SQL_MASK_LEN;
|
|
char *line = palloc0(line_size);
|
char input_request_mask_hash[256];
|
char *hash = palloc0(256);
|
char *in_mask = palloc0(MAX_SQL_MASK_LEN);
|
char *out_mask = palloc0(MAX_SQL_MASK_LEN);
|
char f1[256] = {0}, f2[256] = {0}, f3[256] = {0};
|
|
FILE *file = fopen(FILE_PATH, "r");
|
if (!file) {
|
pfree(line);
|
pfree(hash);
|
pfree(in_mask);
|
pfree(out_mask);
|
|
ELOG(ERROR, _("(TRandLOG.function) Error while reading"));
|
return -1;
|
}
|
|
calculate_sha1(input_request_mask, input_request_mask_hash);
|
|
while (fgets(line, line_size, file)) {
|
hash[0] = '\0';
|
in_mask[0] = '\0';
|
out_mask[0] = '\0';
|
f1[0] = '\0';
|
f2[0] = '\0';
|
f3[0] = '\0';
|
sscanf(line, "%40[^|]|%1024[^|]|%1024[^|]|%255[^|]|%255[^|]|%255[^|\n]",
|
hash, in_mask, out_mask, f1, f2, f3);
|
|
if (strcmp(hash, input_request_mask_hash) == 0) {
|
if (strlen(out_mask) > 0) {
|
strcpy(output_str, out_mask);
|
result = 1;
|
} else {
|
*output_str = '\0';
|
result = 0;
|
}
|
|
break;
|
}
|
}
|
|
fclose(file);
|
|
pfree(line);
|
pfree(hash);
|
pfree(in_mask);
|
pfree(out_mask);
|
|
return result;
|
}
|
|
int save_string(const char *input_sql_str) {
|
char input_hash_hex_str[256];
|
FILE *file = fopen(FILE_PATH, "a");
|
if (!file) {
|
ELOG(ERROR, _("(TRandLOG.function) Error while writing"));
|
return -1;
|
}
|
|
calculate_sha1(input_sql_str, input_hash_hex_str);
|
|
fprintf(file, "%s|%s|||\n", input_hash_hex_str, input_sql_str);
|
fclose(file);
|
|
return 0;
|
}
|
|
static bool trandlog_initialized = false;
|
|
void
|
_TRANDLOG_init(void)
|
{
|
if (trandlog_initialized)
|
return;
|
|
ELOG(INFO, _("(TRandLOG.function) Initialization: OK!"));
|
|
prev_ExecSimpleQuery = ExecSimpleQuery_hook;
|
ExecSimpleQuery_hook = my_ExecSimpleQuery;
|
|
DefineCustomBoolVariable(
|
"trandlog.no_conversion",
|
"Disable conversion feature in converter extension",
|
NULL, &no_conversion,
|
true, PGC_USERSET, GUC_DISALLOW_IN_FILE,
|
NULL, NULL, NULL
|
);
|
DefineCustomBoolVariable(
|
"trandlog.full_conversion",
|
"Setup Full conversion feature in converter extension",
|
NULL, &full_conversion,
|
true, PGC_USERSET, GUC_DISALLOW_IN_FILE,
|
NULL, NULL, NULL
|
);
|
DefineCustomBoolVariable(
|
"trandlog.no_logging",
|
"Disable logging feature in converter extension",
|
NULL, &no_logging,
|
true, PGC_USERSET, GUC_DISALLOW_IN_FILE,
|
NULL, NULL, NULL
|
);
|
DefineCustomIntVariable(
|
"trandlog.id_len",
|
"Set bytes length for connection id in logging",
|
NULL, &id_len,
|
4, 0, 8, /* Значение: default, min, max */
|
PGC_USERSET, GUC_DISALLOW_IN_FILE,
|
NULL, NULL, NULL
|
);
|
DefineCustomIntVariable(
|
"trandlog.log_format",
|
"Set log format for input and output strings",
|
NULL, &log_format,
|
1, 1, 7, /* Значение: default, min, max */
|
PGC_USERSET, GUC_DISALLOW_IN_FILE,
|
NULL, NULL, NULL
|
);
|
trandlog_initialized = true;
|
}
|
|
|
void
|
_TRANDLOG_fini(void)
|
{
|
ExecSimpleQuery_hook = prev_ExecSimpleQuery;
|
}
|
|
|
static void
|
my_ExecSimpleQuery(const char *query_string)
|
{
|
char* output_sql_str = NULL;
|
char* input_mask = NULL;
|
struct timespec start, end;
|
struct timeval tv;
|
char log_str[1024] = {0};
|
struct tm* local_time = {0};
|
char start_time_str[150] = {0}, final_time_str[64] = {0};
|
output_sql_str = pstrdup(query_string);
|
ELOG(INFO, "ORIG QUERY is '%s', CONVERSION IS [%s](%s)", query_string, (no_conversion)?("OFF"):("ON"), (full_conversion)?("FULL"):("SHORT"));
|
|
#ifdef LONG_WAY
|
if (!no_conversion)
|
{
|
char hash_hex_str[HEX_STR_HASH_LEN] = {0};
|
StringArray* param_strings;
|
const char *original_query = query_string;
|
|
/* Begin Example Write in to the table. */
|
param_strings = initializeStringArray();
|
input_mask = sql_str_process(original_query, param_strings);
|
|
if (full_conversion){
|
int hash_found=0;
|
char *output_mask_str = palloc0(MAX_SQL_STR_LEN);
|
calculate_sha1((const char *) input_mask, hash_hex_str);
|
//ELOG(INFO, " *** *** INPUT MASK IS [%s], SHA1:%s", input_mask, hash_hex_str);
|
|
hash_found = search_mask(input_mask, output_mask_str);
|
|
//ELOG(INFO, " *** *** HASH FOUND: %s, OUTPUT MASK is [%s]", (hash_found>=0)?("YES"):("NO"), output_mask_str);
|
|
if (hash_found==-1)
|
{
|
//ELOG(INFO, " *** *** SAVE MASK [%s]", input_mask);
|
save_string(input_mask);
|
}
|
else
|
{
|
if (hash_found==1)
|
{
|
//ELOG(INFO, " *** *** HASH & MASK FOUND, OUTPUT MASK is [%s]", output_mask_str);
|
pfree(output_sql_str);
|
output_sql_str = generateOutputString(output_mask_str, param_strings);
|
}
|
else
|
{} //ELOG(INFO, " *** *** HASH & MASK NOT FOUND ********* ");
|
}
|
|
pfree(output_mask_str);
|
} //full_conversion
|
freeStringArray(param_strings);
|
/* End */
|
}
|
#else
|
/* Begin Example Write in to the table. */
|
StringArray* param_strings;
|
param_strings = initializeStringArray();
|
input_mask = sql_str_process(query_string, param_strings);
|
freeStringArray(param_strings);
|
#endif
|
|
// Начало измерения времени
|
|
if (!no_logging)
|
{
|
clock_gettime(CLOCK_MONOTONIC, &start);
|
|
// Получаем текущее время
|
gettimeofday(&tv, NULL);
|
|
// Разделяем на секунды и миллисекунды
|
local_time = localtime(&tv.tv_sec);
|
}
|
|
if (prev_ExecSimpleQuery)
|
prev_ExecSimpleQuery(output_sql_str);
|
else
|
standard_ExecSimpleQuery(output_sql_str);
|
|
if (!no_logging)
|
{
|
long seconds, nanoseconds;
|
double microseconds;
|
// Форматируем начальное время до секунды
|
strftime(start_time_str, sizeof(start_time_str), "%H:%M:%S", local_time);
|
// Добавляем миллисекунды
|
snprintf(final_time_str, sizeof(final_time_str), "%s.%06ld", start_time_str, tv.tv_usec);
|
|
// Конец измерения времени
|
clock_gettime(CLOCK_MONOTONIC, &end);
|
seconds = end.tv_sec - start.tv_sec;
|
nanoseconds = end.tv_nsec - start.tv_nsec;
|
microseconds = seconds * 1000000L + nanoseconds / 1.0e3;
|
|
//snprintf(log_str, sizeof(log_str), "%s <- %s", input_mask, output_sql_str);
|
/* Формирование строки лога в зависимости от log_format */
|
if (log_format & 0x04) {
|
if ((log_format & 0x03) == 0x03) {
|
snprintf(log_str, sizeof(log_str), "%s -> %s", output_sql_str, input_mask);
|
} else if (log_format & 0x02) {
|
snprintf(log_str, sizeof(log_str), "%s", output_sql_str);
|
} else if (log_format & 0x01) {
|
snprintf(log_str, sizeof(log_str), "%s", input_mask);
|
}
|
} else {
|
if ((log_format & 0x03) == 0x03) {
|
snprintf(log_str, sizeof(log_str), "%s <- %s", input_mask, output_sql_str);
|
} else if (log_format & 0x01) {
|
snprintf(log_str, sizeof(log_str), "%s", input_mask);
|
} else if (log_format & 0x02) {
|
snprintf(log_str, sizeof(log_str), "%s", output_sql_str);
|
}
|
}
|
|
write_log(log_str, final_time_str, microseconds, id_len);
|
}
|
pfree(output_sql_str);
|
|
}
|
|
#endif // TRANDLOG_C
|