Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
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
#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