Repository navigation
Expand file tree
/
Copy pathvpg.c
More file actions
780 lines (672 loc) · 16.8 KB
/
Copy pathvpg.c
File metadata and controls
780 lines (672 loc) · 16.8 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
#define _GNU_SOURCE
#include <pthread.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
#include "postgres.h"
#include "access/xlog.h"
#include "access/xact.h"
#include "commands/vacuum.h"
#include "executor/spi.h"
#include "libpq/pqsignal.h"
#include "miscadmin.h"
#include "postmaster/bgwriter.h"
#include "postmaster/postmaster.h"
#include "storage/bufmgr.h"
#include "storage/ipc.h"
#include "storage/proc.h"
#include "tcop/tcopprot.h"
#include "utils/builtins.h"
#include "utils/elog.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "utils/snapmgr.h"
#include "utils/timeout.h"
#include "utils/timestamp.h"
static bool vpg_initialized = false;
static bool vpg_runtime_ready = false;
static char *vpg_last_error = NULL;
static char *vpg_python_last_error = NULL;
static char *vpg_exec_path = NULL;
static pthread_mutex_t vpg_mutex = PTHREAD_MUTEX_INITIALIZER;
static int vpg_connection_count = 0;
static char *vpg_active_data_dir = NULL;
const char *progname = "vpg";
typedef struct VPGConnection
{
bool open;
char *data_dir;
char *username;
char *dbname;
} VPGConnection;
DispatchOption
parse_dispatch_option(const char *name)
{
if (strcmp(name, "check") == 0)
return DISPATCH_CHECK;
if (strcmp(name, "boot") == 0)
return DISPATCH_BOOT;
if (strcmp(name, "forkchild") == 0)
return DISPATCH_FORKCHILD;
if (strcmp(name, "describe-config") == 0)
return DISPATCH_DESCRIBE_CONFIG;
if (strcmp(name, "single") == 0)
return DISPATCH_SINGLE;
return DISPATCH_POSTMASTER;
}
static void
vpg_replace_owned_string(char **slot, const char *value)
{
if (*slot != NULL)
free(*slot);
*slot = value != NULL ? strdup(value) : NULL;
}
static void
vpg_capture_current_error(void)
{
ErrorData *edata;
char *message;
edata = CopyErrorData();
message = edata->message ? edata->message : "unknown PostgreSQL error";
vpg_replace_owned_string(&vpg_last_error, message);
FlushErrorState();
FreeErrorData(edata);
}
static char *
vpg_strdup_result(const char *value)
{
return strdup(value != NULL ? value : "");
}
static bool
vpg_valid_connection(VPGConnection *conn)
{
return conn != NULL && conn->open;
}
const char *
vpg_get_exec_path(void)
{
if (vpg_exec_path != NULL)
return vpg_exec_path;
#ifdef __APPLE__
uint32_t size = 0;
_NSGetExecutablePath(NULL, &size);
vpg_exec_path = malloc(size);
if (vpg_exec_path == NULL)
return "vpg";
if (_NSGetExecutablePath(vpg_exec_path, &size) != 0)
{
free(vpg_exec_path);
vpg_exec_path = NULL;
return "vpg";
}
return vpg_exec_path;
#else
{
char path[1024];
ssize_t len;
len = readlink("/proc/self/exe", path, sizeof(path) - 1);
if (len < 0)
return "vpg";
path[len] = '\0';
vpg_exec_path = strdup(path);
if (vpg_exec_path == NULL)
return "vpg";
return vpg_exec_path;
}
#endif
}
void
vpg_set_exec_path(const char *path)
{
if (path == NULL || path[0] == '\0')
return;
vpg_replace_owned_string(&vpg_exec_path, path);
}
static void
vpg_runtime_init(void)
{
if (vpg_runtime_ready)
return;
MyProcPid = getpid();
MemoryContextInit();
(void) set_stack_base();
set_pglocale_pgservice(vpg_get_exec_path(), PG_TEXTDOMAIN("postgres"));
vpg_runtime_ready = true;
}
void
vpg_free(void *ptr)
{
free(ptr);
}
static void
vpg_backend_start_options_unlocked(const char *data_dir,
const char *username,
const char *dbname,
const char *shared_preload_libraries);
static const char *vpg_exec_unlocked(const char *query);
static int vpg_run_vacuum_unlocked(bits32 options);
static void vpg_finish_unlocked(void);
const char *
vpg_last_error_message(void)
{
return vpg_last_error;
}
void
vpg_set_python_error(const char *message)
{
vpg_replace_owned_string(&vpg_python_last_error,
message != NULL ? message : "unknown vpg python error");
}
const char *
vpg_python_error(void)
{
if (vpg_python_last_error != NULL)
return vpg_python_last_error;
return vpg_last_error;
}
extern int vpg_initdb_run(int argc, char *argv[]); /* from vpg_initdb.c */
void
vpg_initdb_options(const char *data_dir,
const char *username,
const char *auth,
const char *encoding,
const char *locale,
bool no_instructions)
{
char *av[16];
char auth_arg[128];
char encoding_arg[128];
char locale_arg[128];
int ac = 0;
vpg_replace_owned_string(&vpg_last_error, NULL);
vpg_runtime_init(); /* ensure MemoryContextInit before any palloc */
pqsignal(SIGUSR1, SIG_IGN);
snprintf(auth_arg, sizeof(auth_arg), "--auth=%s",
auth != NULL && auth[0] != '\0' ? auth : "trust");
snprintf(encoding_arg, sizeof(encoding_arg), "--encoding=%s",
encoding != NULL && encoding[0] != '\0' ? encoding : "UTF8");
snprintf(locale_arg, sizeof(locale_arg), "--locale=%s",
locale != NULL && locale[0] != '\0' ? locale : "C");
av[ac++] = (char *) vpg_get_exec_path();
av[ac++] = "-D";
av[ac++] = (char *) data_dir;
av[ac++] = "-U";
av[ac++] = (char *) username;
av[ac++] = auth_arg;
av[ac++] = encoding_arg;
av[ac++] = locale_arg;
if (no_instructions)
av[ac++] = "--no-instructions";
av[ac] = NULL;
int rc = vpg_initdb_run(ac, av);
if (rc != 0)
vpg_replace_owned_string(&vpg_last_error, "vpg_initdb failed");
else
{
pqsignal(SIGUSR1, procsignal_sigusr1_handler);
vpg_replace_owned_string(&vpg_active_data_dir, data_dir);
vpg_initialized = true;
}
}
void
vpg_backend_start_options(const char *data_dir,
const char *username,
const char *dbname,
const char *shared_preload_libraries)
{
pthread_mutex_lock(&vpg_mutex);
vpg_backend_start_options_unlocked(data_dir, username, dbname, shared_preload_libraries);
pthread_mutex_unlock(&vpg_mutex);
}
static void
vpg_backend_start_options_unlocked(const char *data_dir,
const char *username,
const char *dbname,
const char *shared_preload_libraries)
{
if (vpg_initialized)
return;
vpg_replace_owned_string(&vpg_last_error, NULL);
vpg_runtime_init();
PG_TRY();
{
Assert(!IsUnderPostmaster);
progname = vpg_get_exec_path();
InitStandaloneProcess(progname);
InitializeGUCOptions();
SetConfigOption("data_directory", data_dir, PGC_POSTMASTER, PGC_S_ARGV);
SetConfigOption("shared_preload_libraries",
shared_preload_libraries != NULL ? shared_preload_libraries : "",
PGC_POSTMASTER, PGC_S_ARGV);
if (dbname == NULL || dbname[0] == '\0')
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("no database name provided")));
if (!SelectConfigFiles(data_dir, progname))
proc_exit(1);
checkDataDir();
ChangeToDataDir();
CreateDataDirLockFile(false);
LocalProcessControlFile(false);
process_shared_preload_libraries();
InitializeMaxBackends();
InitPostmasterChildSlots();
InitializeFastPathLocks();
process_shmem_requests();
InitializeShmemGUCs();
InitializeWalConsistencyChecking();
CreateSharedMemoryAndSemaphores();
set_max_safe_fds();
PgStartTime = GetCurrentTimestamp();
InitProcess();
pqsignal(SIGHUP, SIG_IGN);
pqsignal(SIGINT, StatementCancelHandler);
pqsignal(SIGTERM, die);
pqsignal(SIGQUIT, die);
pqsignal(SIGPIPE, SIG_IGN);
pqsignal(SIGUSR1, procsignal_sigusr1_handler);
pqsignal(SIGUSR2, SIG_IGN);
pqsignal(SIGFPE, FloatExceptionHandler);
pqsignal(SIGCHLD, SIG_DFL);
InitializeTimeouts();
whereToSendOutput = DestNone;
BaseInit();
sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
InitPostgres(dbname, InvalidOid, username, InvalidOid, 0, NULL);
SetProcessingMode(NormalProcessing);
vpg_replace_owned_string(&vpg_active_data_dir, data_dir);
vpg_initialized = true;
}
PG_CATCH();
{
vpg_capture_current_error();
vpg_initialized = false;
}
PG_END_TRY();
}
const char *
vpg_exec(const char *query)
{
const char *result;
pthread_mutex_lock(&vpg_mutex);
result = vpg_exec_unlocked(query);
pthread_mutex_unlock(&vpg_mutex);
return result;
}
static const char *
vpg_exec_unlocked(const char *query)
{
StringInfoData buf;
char *result;
if (!vpg_initialized)
{
vpg_replace_owned_string(&vpg_last_error, "backend not initialized");
return NULL;
}
vpg_replace_owned_string(&vpg_last_error, NULL);
initStringInfo(&buf);
result = NULL;
PG_TRY();
{
int spi_rc;
int exec_rc;
StartTransactionCommand();
PushActiveSnapshot(GetTransactionSnapshot());
spi_rc = SPI_connect();
if (spi_rc != SPI_OK_CONNECT)
elog(ERROR, "SPI_connect failed: %s", SPI_result_code_string(spi_rc));
exec_rc = SPI_exec(query, 0);
if (exec_rc < 0)
elog(ERROR, "SPI_exec failed: %s", SPI_result_code_string(exec_rc));
if (SPI_tuptable != NULL)
{
TupleDesc tupdesc = SPI_tuptable->tupdesc;
uint64 row;
for (int col = 0; col < tupdesc->natts; col++)
{
appendStringInfoString(&buf, NameStr(TupleDescAttr(tupdesc, col)->attname));
if (col + 1 < tupdesc->natts)
appendStringInfoChar(&buf, ',');
}
appendStringInfoChar(&buf, '\n');
for (row = 0; row < SPI_processed; row++)
{
HeapTuple tuple = SPI_tuptable->vals[row];
for (int col = 0; col < tupdesc->natts; col++)
{
char *value = SPI_getvalue(tuple, tupdesc, col + 1);
if (value != NULL)
appendStringInfoString(&buf, value);
else
appendStringInfoString(&buf, "null");
if (col + 1 < tupdesc->natts)
appendStringInfoChar(&buf, ',');
}
appendStringInfoChar(&buf, '\n');
}
}
else
{
appendStringInfo(&buf, "OK %llu\n", (unsigned long long) SPI_processed);
}
if (SPI_finish() != SPI_OK_FINISH)
elog(ERROR, "SPI_finish failed");
PopActiveSnapshot();
CommitTransactionCommand();
result = vpg_strdup_result(buf.data);
}
PG_CATCH();
{
vpg_capture_current_error();
HOLD_INTERRUPTS();
if (ActiveSnapshotSet())
PopActiveSnapshot();
AbortCurrentTransaction();
RESUME_INTERRUPTS();
result = NULL;
}
PG_END_TRY();
pfree(buf.data);
return result;
}
static int
vpg_run_vacuum(bits32 options)
{
int rc;
pthread_mutex_lock(&vpg_mutex);
rc = vpg_run_vacuum_unlocked(options);
pthread_mutex_unlock(&vpg_mutex);
return rc;
}
static int
vpg_run_vacuum_unlocked(bits32 options)
{
int rc = 0;
if (!vpg_initialized)
{
vpg_replace_owned_string(&vpg_last_error, "backend not initialized");
return -1;
}
vpg_replace_owned_string(&vpg_last_error, NULL);
PG_TRY();
{
VacuumParams params;
BufferAccessStrategy bstrategy = NULL;
MemoryContext vac_context;
MemoryContext old_context;
memset(¶ms, 0, sizeof(params));
params.options = options;
params.freeze_min_age = -1;
params.freeze_table_age = -1;
params.multixact_freeze_min_age = -1;
params.multixact_freeze_table_age = -1;
params.log_min_duration = -1;
params.index_cleanup = VACOPTVALUE_UNSPECIFIED;
params.truncate = VACOPTVALUE_UNSPECIFIED;
params.toast_parent = InvalidOid;
params.max_eager_freeze_failure_rate = vacuum_max_eager_freeze_failure_rate;
params.nworkers = 0;
StartTransactionCommand();
vac_context = AllocSetContextCreate(PortalContext,
"vpg vacuum",
ALLOCSET_DEFAULT_SIZES);
old_context = MemoryContextSwitchTo(vac_context);
bstrategy = GetAccessStrategyWithSize(BAS_VACUUM, VacuumBufferUsageLimit);
MemoryContextSwitchTo(old_context);
vacuum(NIL, ¶ms, bstrategy, vac_context, true);
MemoryContextDelete(vac_context);
CommitTransactionCommand();
}
PG_CATCH();
{
vpg_capture_current_error();
HOLD_INTERRUPTS();
AbortCurrentTransaction();
RESUME_INTERRUPTS();
rc = -1;
}
PG_END_TRY();
return rc;
}
int
vpg_vacuum(void)
{
return vpg_run_vacuum(VACOPT_VACUUM |
VACOPT_PROCESS_MAIN |
VACOPT_PROCESS_TOAST);
}
int
vpg_analyze(void)
{
return vpg_run_vacuum(VACOPT_ANALYZE |
VACOPT_PROCESS_MAIN |
VACOPT_PROCESS_TOAST);
}
int
vpg_maintain(void)
{
int rc = 0;
pthread_mutex_lock(&vpg_mutex);
if (vpg_run_vacuum_unlocked(VACOPT_VACUUM |
VACOPT_ANALYZE |
VACOPT_PROCESS_MAIN |
VACOPT_PROCESS_TOAST) != 0)
{
pthread_mutex_unlock(&vpg_mutex);
return -1;
}
PG_TRY();
{
StartTransactionCommand();
/* Force dirty buffers and WAL state to disk before returning. */
RequestCheckpoint(CHECKPOINT_IMMEDIATE |
CHECKPOINT_FORCE |
CHECKPOINT_WAIT);
CommitTransactionCommand();
}
PG_CATCH();
{
vpg_capture_current_error();
AbortCurrentTransaction();
rc = -1;
}
PG_END_TRY();
pthread_mutex_unlock(&vpg_mutex);
return rc;
}
void *
vpg_connect_options(const char *data_dir,
const char *username,
const char *dbname,
const char *shared_preload_libraries)
{
VPGConnection *conn;
pthread_mutex_lock(&vpg_mutex);
vpg_replace_owned_string(&vpg_last_error, NULL);
if (data_dir == NULL || data_dir[0] == '\0')
{
vpg_replace_owned_string(&vpg_last_error, "data directory is required");
pthread_mutex_unlock(&vpg_mutex);
return NULL;
}
if (vpg_initialized &&
vpg_active_data_dir != NULL &&
strcmp(vpg_active_data_dir, data_dir) != 0)
{
vpg_replace_owned_string(&vpg_last_error,
"only one embedded data directory can be open in a process");
pthread_mutex_unlock(&vpg_mutex);
return NULL;
}
vpg_backend_start_options_unlocked(data_dir, username, dbname, shared_preload_libraries);
if (vpg_last_error != NULL)
{
pthread_mutex_unlock(&vpg_mutex);
return NULL;
}
conn = calloc(1, sizeof(VPGConnection));
if (conn == NULL)
{
vpg_replace_owned_string(&vpg_last_error, "out of memory allocating connection");
pthread_mutex_unlock(&vpg_mutex);
return NULL;
}
conn->open = true;
conn->data_dir = strdup(data_dir);
conn->username = strdup(username != NULL && username[0] != '\0' ? username : "postgres");
conn->dbname = strdup(dbname != NULL && dbname[0] != '\0' ? dbname : conn->username);
if (conn->data_dir == NULL || conn->username == NULL || conn->dbname == NULL)
{
free(conn->data_dir);
free(conn->username);
free(conn->dbname);
free(conn);
vpg_replace_owned_string(&vpg_last_error, "out of memory allocating connection");
pthread_mutex_unlock(&vpg_mutex);
return NULL;
}
vpg_connection_count++;
pthread_mutex_unlock(&vpg_mutex);
return conn;
}
const char *
vpg_conn_exec(void *handle, const char *query)
{
const char *result;
VPGConnection *conn = (VPGConnection *) handle;
pthread_mutex_lock(&vpg_mutex);
if (!vpg_valid_connection(conn))
{
vpg_replace_owned_string(&vpg_last_error, "connection is closed");
pthread_mutex_unlock(&vpg_mutex);
return NULL;
}
result = vpg_exec_unlocked(query);
pthread_mutex_unlock(&vpg_mutex);
return result;
}
int
vpg_conn_vacuum(void *handle)
{
int rc;
VPGConnection *conn = (VPGConnection *) handle;
pthread_mutex_lock(&vpg_mutex);
if (!vpg_valid_connection(conn))
{
vpg_replace_owned_string(&vpg_last_error, "connection is closed");
pthread_mutex_unlock(&vpg_mutex);
return -1;
}
rc = vpg_run_vacuum_unlocked(VACOPT_VACUUM |
VACOPT_PROCESS_MAIN |
VACOPT_PROCESS_TOAST);
pthread_mutex_unlock(&vpg_mutex);
return rc;
}
int
vpg_conn_analyze(void *handle)
{
int rc;
VPGConnection *conn = (VPGConnection *) handle;
pthread_mutex_lock(&vpg_mutex);
if (!vpg_valid_connection(conn))
{
vpg_replace_owned_string(&vpg_last_error, "connection is closed");
pthread_mutex_unlock(&vpg_mutex);
return -1;
}
rc = vpg_run_vacuum_unlocked(VACOPT_ANALYZE |
VACOPT_PROCESS_MAIN |
VACOPT_PROCESS_TOAST);
pthread_mutex_unlock(&vpg_mutex);
return rc;
}
int
vpg_conn_maintain(void *handle)
{
int rc = 0;
VPGConnection *conn = (VPGConnection *) handle;
pthread_mutex_lock(&vpg_mutex);
if (!vpg_valid_connection(conn))
{
vpg_replace_owned_string(&vpg_last_error, "connection is closed");
pthread_mutex_unlock(&vpg_mutex);
return -1;
}
if (vpg_run_vacuum_unlocked(VACOPT_VACUUM |
VACOPT_ANALYZE |
VACOPT_PROCESS_MAIN |
VACOPT_PROCESS_TOAST) != 0)
{
pthread_mutex_unlock(&vpg_mutex);
return -1;
}
PG_TRY();
{
StartTransactionCommand();
RequestCheckpoint(CHECKPOINT_IMMEDIATE |
CHECKPOINT_FORCE |
CHECKPOINT_WAIT);
CommitTransactionCommand();
}
PG_CATCH();
{
vpg_capture_current_error();
AbortCurrentTransaction();
rc = -1;
}
PG_END_TRY();
pthread_mutex_unlock(&vpg_mutex);
return rc;
}
void
vpg_conn_close(void *handle)
{
VPGConnection *conn = (VPGConnection *) handle;
if (conn == NULL)
return;
pthread_mutex_lock(&vpg_mutex);
if (conn->open)
{
conn->open = false;
if (vpg_connection_count > 0)
vpg_connection_count--;
if (vpg_connection_count == 0)
vpg_finish_unlocked();
}
pthread_mutex_unlock(&vpg_mutex);
free(conn->data_dir);
free(conn->username);
free(conn->dbname);
free(conn);
}
void
vpg_finish(void)
{
pthread_mutex_lock(&vpg_mutex);
vpg_finish_unlocked();
pthread_mutex_unlock(&vpg_mutex);
}
static void
vpg_finish_unlocked(void)
{
if (!vpg_initialized)
return;
PG_TRY();
{
AbortOutOfAnyTransaction();
shmem_exit(0);
}
PG_CATCH();
{
vpg_capture_current_error();
FlushErrorState();
}
PG_END_TRY();
vpg_initialized = false;
vpg_replace_owned_string(&vpg_active_data_dir, NULL);
}