forked from postgres/postgres
-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathpgl_mains.c
More file actions
477 lines (393 loc) · 12.7 KB
/
pgl_mains.c
File metadata and controls
477 lines (393 loc) · 12.7 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
#include <setjmp.h>
#include <stdlib.h>
#include <string.h>
volatile int sf_connected = 0;
FILE * single_mode_feed = NULL;
volatile bool inloop = false;
volatile sigjmp_buf local_sigjmp_buf;
bool repl = false;
#define PGLITE_POSTGRES_CONFIG_ENV "PGLITE_POSTGRES_CONFIG"
static void
ApplyPostgresConfigFromEnv(void)
{
const char *raw = getenv(PGLITE_POSTGRES_CONFIG_ENV);
char *config_copy = NULL;
char *cursor = NULL;
char *entry = NULL;
if (raw == NULL || raw[0] == '\0')
return;
config_copy = strdup(raw);
if (config_copy == NULL)
return;
cursor = config_copy;
while ((entry = strsep(&cursor, ";")) != NULL)
{
char *eq = NULL;
if (entry[0] == '\0')
continue;
eq = strchr(entry, '=');
if (eq == NULL || eq == entry || eq[1] == '\0')
continue;
*eq = '\0';
SetConfigOption(entry, eq + 1, PGC_POSTMASTER, PGC_S_ARGV);
}
free(config_copy);
}
__attribute__((export_name("pgl_shutdown")))
void
pg_shutdown() {
PDEBUG("# 11:" __FILE__": pg_shutdown");
proc_exit(66);
}
__attribute__((export_name("pgl_closed")))
int
pgl_closed() {
if (sf_connected>0)
return 1;
return 0;
}
#if FIXME
extern bool startswith(const char *str, const char *prefix);
#endif
void
interactive_file() {
int firstchar = 0;
int c = 0; /* character read from getc() */
StringInfoData input_message;
StringInfoData *inBuf;
FILE *stream ;
int sql_line=1;
bool sql_skip = false;
/*
* At top of loop, reset extended-query-message flag, so that any
* errors encountered in "idle" state don't provoke skip.
*/
doing_extended_query_message = false;
/*
* Release storage left over from prior query cycle, and create a new
* query input buffer in the cleared MessageContext.
*/
MemoryContextSwitchTo(MessageContext);
MemoryContextReset(MessageContext);
initStringInfo(&input_message);
inBuf = &input_message;
DoingCommandRead = true;
stream = single_mode_feed;
while (c!=EOF) {
resetStringInfo(inBuf);
while ((c = getc(stream)) != EOF) {
if (c == '\n')
{
sql_line++;
if (UseSemiNewlineNewline)
{
/*
* In -j mode, semicolon followed by two newlines ends the
* command; otherwise treat newline as regular character.
*/
if (inBuf->len > 1 &&
inBuf->data[inBuf->len - 1] == '\n' &&
inBuf->data[inBuf->len - 2] == ';')
{
/* might as well drop the second newline */
break;
}
}
else
{
/*
* In plain mode, newline ends the command unless preceded by
* backslash.
*/
if (inBuf->len > 0 &&
inBuf->data[inBuf->len - 1] == '\\')
{
/* discard backslash from inBuf */
inBuf->data[--inBuf->len] = '\0';
/* discard newline too */
continue;
}
else
{
/* keep the newline character, but end the command */
appendStringInfoChar(inBuf, '\n');
break;
}
}
}
/* Not newline, or newline treated as regular character */
appendStringInfoChar(inBuf, (char) c);
}
if (c == EOF && inBuf->len == 0)
return;
/* Add '\0' to make it look the same as message case. */
appendStringInfoChar(inBuf, (char) '\0');
firstchar = 'Q';
#if FIXME
#warning "FIXME: REVOKE ALL ON pg_largeobject FROM PUBLIC;"
#warning "FIXME: REVOKE CREATE,TEMPORARY ON DATABASE template1 FROM public;"
sql_skip |= startswith(inBuf->data , "REVOKE ALL ON pg_largeobject FROM PUBLIC;");
sql_skip |= startswith(inBuf->data , "REVOKE CREATE,TEMPORARY ON DATABASE template1 FROM public;");
if (sql_skip) {
fprintf(stdout, "# 106: SKIPPED: %d: %s\n", sql_line, inBuf->data);
sql_skip = false;
continue;
} else {
// fprintf(stderr, "%d: %s\n", sql_line, inBuf->data);
}
#endif
// ???
if (ignore_till_sync && firstchar != EOF)
continue;
#include "pg_proto.c"
}
PDEBUG("# 115: interactive_file: end");
}
void
RePostgresSingleUserMain(int single_argc, char *single_argv[], const char *username)
{
#if PGDEBUG
printf("# 123: RePostgresSingleUserMain progname=%s for %s feed=%s\n", progname, single_argv[0], IDB_PIPE_SINGLE);
#endif
single_mode_feed = fopen(IDB_PIPE_SINGLE, "r");
// should be template1.
const char *dbname = NULL;
/* Parse command-line options. */
process_postgres_switches(single_argc, single_argv, PGC_POSTMASTER, &dbname);
ApplyPostgresConfigFromEnv();
#if PGDEBUG
printf("# 134: dbname=%s\n", dbname);
#endif
LocalProcessControlFile(false);
process_shared_preload_libraries();
// InitializeMaxBackends();
// ? IgnoreSystemIndexes = true;
IgnoreSystemIndexes = false;
process_shmem_requests();
InitializeShmemGUCs();
InitializeWalConsistencyChecking();
PgStartTime = GetCurrentTimestamp();
SetProcessingMode(InitProcessing);
PDEBUG("# 153: Re-InitPostgres");
if (am_walsender)
PDEBUG("# 155: am_walsender == true");
// BaseInit();
InitPostgres(dbname, InvalidOid, /* database to connect to */
username, InvalidOid, /* role to connect as */
(!am_walsender) ? INIT_PG_LOAD_SESSION_LIBS : 0,
NULL); /* no out_dbname */
PDEBUG("# 164:" __FILE__);
SetProcessingMode(NormalProcessing);
BeginReportingGUCOptions();
if (IsUnderPostmaster && Log_disconnections)
on_proc_exit(log_disconnections, 0);
pgstat_report_connect(MyDatabaseId);
/* Perform initialization specific to a WAL sender process. */
if (am_walsender)
InitWalSender();
#if PGDEBUG
whereToSendOutput = DestDebug;
#endif
if (whereToSendOutput == DestDebug)
printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
/*
* Create the memory context we will use in the main loop.
*
* MessageContext is reset once per iteration of the main loop, ie, upon
* completion of processing of each command message from the client.
*/
MessageContext = AllocSetContextCreate(TopMemoryContext,
"MessageContext",
ALLOCSET_DEFAULT_SIZES);
/*
* Create memory context and buffer used for RowDescription messages. As
* SendRowDescriptionMessage(), via exec_describe_statement_message(), is
* frequently executed for ever single statement, we don't want to
* allocate a separate buffer every time.
*/
row_description_context = AllocSetContextCreate(TopMemoryContext,
"RowDescriptionContext",
ALLOCSET_DEFAULT_SIZES);
MemoryContextSwitchTo(row_description_context);
initStringInfo(&row_description_buf);
MemoryContextSwitchTo(TopMemoryContext);
# define INITDB_SINGLE
# include "pgl_sjlj.c"
# undef INITDB_SINGLE
if (!ignore_till_sync)
send_ready_for_query = true; /* initially, or after error */
/*
if (!inloop) {
inloop = true;
PDEBUG("# 335: REPL(initdb-single):Begin " __FILE__ );
while (repl) { interactive_file(); }
} else {
// signal error
optind = -1;
}
*/
interactive_file();
fclose(single_mode_feed);
single_mode_feed = NULL;
/*
while (repl) { interactive_file(); }
PDEBUG("# 240: REPL:End Raising a 'RuntimeError Exception' to halt program NOW");
{
void (*npe)() = NULL;
npe();
}
// unreachable.
*/
PDEBUG("# 248: no line-repl requested, exiting and keeping runtime alive");
}
void
AsyncPostgresSingleUserMain(int argc, char *argv[], const char *username, int async_restart)
{
const char *dbname = NULL;
PDEBUG("# 254:"__FILE__);
// if (!async_restart) /* Initialize startup process environment. */
InitStandaloneProcess(argv[0]);
PDEBUG("# 254:"__FILE__);
// if (!async_restart) /* Set default values for command-line options. */
InitializeGUCOptions();
PDEBUG("# 257:"__FILE__);
// if (!async_restart) /* Parse command-line options. */
process_postgres_switches(argc, argv, PGC_POSTMASTER, &dbname);
ApplyPostgresConfigFromEnv();
PDEBUG("# 260:"__FILE__);
/* Must have gotten a database name, or have a default (the username) */
if (dbname == NULL)
{
dbname = username;
if (dbname == NULL)
ereport(FATAL,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("%s: no database nor user name specified",
progname)));
}
PDEBUG("# 291:SelectConfigFiles "__FILE__);
if (async_restart) goto async_db_change;
/* Acquire configuration parameters */
if (!SelectConfigFiles(userDoption, progname)) {
proc_exit(1);
}
PDEBUG("# 278:SelectConfigFiles "__FILE__);
checkDataDir();
ChangeToDataDir();
/*
* Create lockfile for data directory.
*/
CreateDataDirLockFile(false);
/* read control file (error checking and contains config ) */
LocalProcessControlFile(false);
/*
* process any libraries that should be preloaded at postmaster start
*/
process_shared_preload_libraries();
/* Initialize MaxBackends */
InitializeMaxBackends();
PDEBUG("# 127"); /* on_shmem_exit stubs call start here */
/*
* Give preloaded libraries a chance to request additional shared memory.
*/
process_shmem_requests();
/*
* Now that loadable modules have had their chance to request additional
* shared memory, determine the value of any runtime-computed GUCs that
* depend on the amount of shared memory required.
*/
InitializeShmemGUCs();
/*
* Now that modules have been loaded, we can process any custom resource
* managers specified in the wal_consistency_checking GUC.
*/
InitializeWalConsistencyChecking();
CreateSharedMemoryAndSemaphores();
/*
* Remember stand-alone backend startup time,roughly at the same point
* during startup that postmaster does so.
*/
PgStartTime = GetCurrentTimestamp();
/*
* Create a per-backend PGPROC struct in shared memory. We must do this
* before we can use LWLocks.
*/
InitProcess();
// main
SetProcessingMode(InitProcessing);
/* Early initialization */
BaseInit();
async_db_change:;
PDEBUG("# 167");
/*
* General initialization.
*
* NOTE: if you are tempted to add code in this vicinity, consider putting
* it inside InitPostgres() instead. In particular, anything that
* involves database access should be there, not here.
*/
InitPostgres(dbname, InvalidOid, /* database to connect to */
username, InvalidOid, /* role to connect as */
(!am_walsender) ? INIT_PG_LOAD_SESSION_LIBS : 0,
NULL); /* no out_dbname */
/*
* If the PostmasterContext is still around, recycle the space; we don't
* need it anymore after InitPostgres completes. Note this does not trash
* *MyProcPort, because ConnCreate() allocated that space with malloc()
* ... else we'd need to copy the Port data first. Also, subsidiary data
* such as the username isn't lost either; see ProcessStartupPacket().
*/
if (PostmasterContext)
{
MemoryContextDelete(PostmasterContext);
PostmasterContext = NULL;
}
SetProcessingMode(NormalProcessing);
/*
* Now all GUC states are fully set up. Report them to client if
* appropriate.
*/
BeginReportingGUCOptions();
/*
* Also set up handler to log session end; we have to wait till now to be
* sure Log_disconnections has its final value.
*/
if (IsUnderPostmaster && Log_disconnections)
on_proc_exit(log_disconnections, 0);
pgstat_report_connect(MyDatabaseId);
/* Perform initialization specific to a WAL sender process. */
if (am_walsender)
InitWalSender();
/*
* Send this backend's cancellation info to the frontend.
*/
if (whereToSendOutput == DestRemote)
{
StringInfoData buf;
pq_beginmessage(&buf, 'K');
pq_sendint32(&buf, (int32) MyProcPid);
pq_sendint32(&buf, (int32) MyCancelKey);
pq_endmessage(&buf);
/* Need not flush since ReadyForQuery will do it. */
}
/* Welcome banner for standalone case */
if (whereToSendOutput == DestDebug)
printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
/*
* Create the memory context we will use in the main loop.
*
* MessageContext is reset once per iteration of the main loop, ie, upon
* completion of processing of each command message from the client.
*/
MessageContext = AllocSetContextCreate(TopMemoryContext, "MessageContext", ALLOCSET_DEFAULT_SIZES);
/*
* Create memory context and buffer used for RowDescription messages. As
* SendRowDescriptionMessage(), via exec_describe_statement_message(), is
* frequently executed for ever single statement, we don't want to
* allocate a separate buffer every time.
*/
row_description_context = AllocSetContextCreate(TopMemoryContext, "RowDescriptionContext", ALLOCSET_DEFAULT_SIZES);
MemoryContextSwitchTo(row_description_context);
initStringInfo(&row_description_buf);
MemoryContextSwitchTo(TopMemoryContext);
} // AsyncPostgresSingleUserMain