Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * pg_ctl --- start/stops/restarts the PostgreSQL server
4 : : *
5 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
6 : : *
7 : : * src/bin/pg_ctl/pg_ctl.c
8 : : *
9 : : *-------------------------------------------------------------------------
10 : : */
11 : :
12 : : #include "postgres_fe.h"
13 : :
14 : : #include <fcntl.h>
15 : : #include <signal.h>
16 : : #include <time.h>
17 : : #include <sys/resource.h>
18 : : #include <sys/stat.h>
19 : : #include <sys/time.h>
20 : : #include <sys/wait.h>
21 : : #include <unistd.h>
22 : :
23 : :
24 : : #include "catalog/pg_control.h"
25 : : #include "common/controldata_utils.h"
26 : : #include "common/file_perm.h"
27 : : #include "common/logging.h"
28 : : #include "common/string.h"
29 : : #include "datatype/timestamp.h"
30 : : #include "getopt_long.h"
31 : : #include "utils/pidfile.h"
32 : :
33 : : #ifdef WIN32 /* on Unix, we don't need libpq */
34 : : #include "pqexpbuffer.h"
35 : : #endif
36 : :
37 : :
38 : : typedef enum
39 : : {
40 : : SMART_MODE,
41 : : FAST_MODE,
42 : : IMMEDIATE_MODE,
43 : : } ShutdownMode;
44 : :
45 : : typedef enum
46 : : {
47 : : POSTMASTER_READY,
48 : : POSTMASTER_STILL_STARTING,
49 : : POSTMASTER_SHUTDOWN_IN_RECOVERY,
50 : : POSTMASTER_FAILED,
51 : : } WaitPMResult;
52 : :
53 : : typedef enum
54 : : {
55 : : NO_COMMAND = 0,
56 : : INIT_COMMAND,
57 : : START_COMMAND,
58 : : STOP_COMMAND,
59 : : RESTART_COMMAND,
60 : : RELOAD_COMMAND,
61 : : STATUS_COMMAND,
62 : : PROMOTE_COMMAND,
63 : : LOGROTATE_COMMAND,
64 : : KILL_COMMAND,
65 : : REGISTER_COMMAND,
66 : : UNREGISTER_COMMAND,
67 : : RUN_AS_SERVICE_COMMAND,
68 : : } CtlCommand;
69 : :
70 : : #define DEFAULT_WAIT 60
71 : :
72 : : #define WAITS_PER_SEC 10
73 : : StaticAssertDecl(USECS_PER_SEC % WAITS_PER_SEC == 0,
74 : : "WAITS_PER_SEC must divide USECS_PER_SEC evenly");
75 : :
76 : : static bool do_wait = true;
77 : : static int wait_seconds = DEFAULT_WAIT;
78 : : #ifdef WIN32
79 : : static bool wait_seconds_arg = false;
80 : : #endif
81 : : static bool silent_mode = false;
82 : : static ShutdownMode shutdown_mode = FAST_MODE;
83 : : static int sig = SIGINT; /* default */
84 : : static CtlCommand ctl_command = NO_COMMAND;
85 : : static char *pg_data = NULL;
86 : : static char *pg_config = NULL;
87 : : static char *pgdata_opt = NULL;
88 : : static char *post_opts = NULL;
89 : : static const char *progname;
90 : : static char *log_file = NULL;
91 : : static char *exec_path = NULL;
92 : : #ifdef WIN32
93 : : static char *event_source = NULL;
94 : : static char *register_servicename = "PostgreSQL"; /* FIXME: + version ID? */
95 : : static char *register_username = NULL;
96 : : static char *register_password = NULL;
97 : : #endif
98 : : static char *argv0 = NULL;
99 : : static bool allow_core_files = false;
100 : : static time_t start_time;
101 : :
102 : : static char postopts_file[MAXPGPATH];
103 : : static char version_file[MAXPGPATH];
104 : : static char pid_file[MAXPGPATH];
105 : : static char promote_file[MAXPGPATH];
106 : : static char logrotate_file[MAXPGPATH];
107 : :
108 : : static volatile pid_t postmasterPID = -1;
109 : :
110 : : #ifdef WIN32
111 : : static DWORD pgctl_start_type = SERVICE_AUTO_START;
112 : : static SERVICE_STATUS status;
113 : : static SERVICE_STATUS_HANDLE hStatus = (SERVICE_STATUS_HANDLE) 0;
114 : : static HANDLE shutdownHandles[2];
115 : :
116 : : #define shutdownEvent shutdownHandles[0]
117 : : #define postmasterProcess shutdownHandles[1]
118 : : #endif
119 : :
120 : :
121 : : static void write_stderr(const char *fmt, ...) pg_attribute_printf(1, 2);
122 : : static void do_advice(void);
123 : : static void do_help(void);
124 : : static void set_mode(char *modeopt);
125 : : static void set_sig(char *signame);
126 : : static void do_init(void);
127 : : static void do_start(void);
128 : : static void do_stop(void);
129 : : static void do_restart(void);
130 : : static void do_reload(void);
131 : : static void do_status(void);
132 : : static void do_promote(void);
133 : : static void do_logrotate(void);
134 : : static void do_kill(pid_t pid);
135 : : static void print_msg(const char *msg);
136 : : static void adjust_data_dir(void);
137 : :
138 : : #ifdef WIN32
139 : : #include <versionhelpers.h>
140 : : static bool pgwin32_IsInstalled(SC_HANDLE);
141 : : static char *pgwin32_CommandLine(bool);
142 : : static void pgwin32_doRegister(void);
143 : : static void pgwin32_doUnregister(void);
144 : : static void pgwin32_SetServiceStatus(DWORD);
145 : : static void WINAPI pgwin32_ServiceHandler(DWORD);
146 : : static void WINAPI pgwin32_ServiceMain(DWORD, LPTSTR *);
147 : : static void pgwin32_doRunAsService(void);
148 : : static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, bool as_service);
149 : : static PTOKEN_PRIVILEGES GetPrivilegesToDelete(HANDLE hToken);
150 : : #endif
151 : :
152 : : static pid_t get_pgpid(bool is_status_request);
153 : : static char **readfile(const char *path, int *numlines);
154 : : static void free_readfile(char **optlines);
155 : : static pid_t start_postmaster(void);
156 : : static void read_post_opts(void);
157 : :
158 : : static WaitPMResult wait_for_postmaster_start(pid_t pm_pid, bool do_checkpoint);
159 : : static bool wait_for_postmaster_stop(void);
160 : : static bool wait_for_postmaster_promote(void);
161 : : static bool postmaster_is_alive(pid_t pid);
162 : :
163 : : #if defined(HAVE_GETRLIMIT)
164 : : static void unlimit_core_size(void);
165 : : #endif
166 : :
167 : : static DBState get_control_dbstate(void);
168 : :
169 : :
170 : : #ifdef WIN32
171 : : static void
172 : : write_eventlog(int level, const char *line)
173 : : {
174 : : static HANDLE evtHandle = INVALID_HANDLE_VALUE;
175 : :
176 : : if (silent_mode && level == EVENTLOG_INFORMATION_TYPE)
177 : : return;
178 : :
179 : : if (evtHandle == INVALID_HANDLE_VALUE)
180 : : {
181 : : evtHandle = RegisterEventSource(NULL,
182 : : event_source ? event_source : DEFAULT_EVENT_SOURCE);
183 : : if (evtHandle == NULL)
184 : : {
185 : : evtHandle = INVALID_HANDLE_VALUE;
186 : : return;
187 : : }
188 : : }
189 : :
190 : : ReportEvent(evtHandle,
191 : : level,
192 : : 0,
193 : : 0, /* All events are Id 0 */
194 : : NULL,
195 : : 1,
196 : : 0,
197 : : &line,
198 : : NULL);
199 : : }
200 : : #endif
201 : :
202 : : /*
203 : : * Write errors to stderr (or by equal means when stderr is
204 : : * not available).
205 : : */
206 : : static void
130 tgl@sss.pgh.pa.us 207 :CBC 75 : write_stderr(const char *fmt, ...)
208 : : {
209 : : va_list ap;
210 : :
8123 211 : 75 : va_start(ap, fmt);
212 : : #ifndef WIN32
213 : : /* On Unix, we just fprintf to stderr */
214 : 75 : vfprintf(stderr, fmt, ap);
215 : : #else
216 : :
217 : : /*
218 : : * On Win32, we print to stderr if running on a console, or write to
219 : : * eventlog if running as a service
220 : : */
221 : : if (pgwin32_is_service()) /* Running as a service */
222 : : {
223 : : char errbuf[2048]; /* Arbitrary size? */
224 : :
225 : : vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
226 : :
227 : : write_eventlog(EVENTLOG_ERROR_TYPE, errbuf);
228 : : }
229 : : else
230 : : /* Not running as service, write to stderr */
231 : : vfprintf(stderr, fmt, ap);
232 : : #endif
233 : 75 : va_end(ap);
234 : 75 : }
235 : :
236 : : /*
237 : : * Given an already-localized string, print it to stdout unless the
238 : : * user has specified that no messages should be printed.
239 : : */
240 : : static void
8010 neilc@samurai.com 241 : 8076 : print_msg(const char *msg)
242 : : {
243 [ + + ]: 8076 : if (!silent_mode)
244 : : {
245 : 7556 : fputs(msg, stdout);
246 : 7556 : fflush(stdout);
247 : : }
248 : 8076 : }
249 : :
250 : : static pid_t
4579 bruce@momjian.us 251 : 6581 : get_pgpid(bool is_status_request)
252 : : {
253 : : FILE *pidf;
254 : : int pid;
255 : : struct stat statbuf;
256 : :
257 [ + + ]: 6581 : if (stat(pg_data, &statbuf) != 0)
258 : : {
259 [ + - ]: 3 : if (errno == ENOENT)
4512 peter_e@gmx.net 260 : 3 : write_stderr(_("%s: directory \"%s\" does not exist\n"), progname,
261 : : pg_data);
262 : : else
922 michael@paquier.xyz 263 :UBC 0 : write_stderr(_("%s: could not access directory \"%s\": %m\n"), progname,
264 : : pg_data);
265 : :
266 : : /*
267 : : * The Linux Standard Base Core Specification 3.1 says this should
268 : : * return '4, program or service status is unknown'
269 : : * https://refspecs.linuxbase.org/LSB_3.1.0/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
270 : : */
4579 bruce@momjian.us 271 [ + + ]:CBC 3 : exit(is_status_request ? 4 : 1);
272 : : }
273 : :
274 [ - + - - ]: 6578 : if (stat(version_file, &statbuf) != 0 && errno == ENOENT)
275 : : {
4512 peter_e@gmx.net 276 :UBC 0 : write_stderr(_("%s: directory \"%s\" is not a database cluster directory\n"),
277 : : progname, pg_data);
4579 bruce@momjian.us 278 [ # # ]: 0 : exit(is_status_request ? 4 : 1);
279 : : }
280 : :
8151 bruce@momjian.us 281 :CBC 6578 : pidf = fopen(pid_file, "r");
282 [ + + ]: 6578 : if (pidf == NULL)
283 : : {
284 : : /* No pid file, not an error on startup */
285 [ + - ]: 1819 : if (errno == ENOENT)
286 : 1819 : return 0;
287 : : else
288 : : {
922 michael@paquier.xyz 289 :UBC 0 : write_stderr(_("%s: could not open PID file \"%s\": %m\n"),
290 : : progname, pid_file);
8151 bruce@momjian.us 291 : 0 : exit(1);
292 : : }
293 : : }
1429 peter@eisentraut.org 294 [ - + ]:CBC 4759 : if (fscanf(pidf, "%d", &pid) != 1)
295 : : {
296 : : /* Is the file empty? */
5135 bruce@momjian.us 297 [ # # # # ]:UBC 0 : if (ftell(pidf) == 0 && feof(pidf))
298 : 0 : write_stderr(_("%s: the PID file \"%s\" is empty\n"),
299 : : progname, pid_file);
300 : : else
301 : 0 : write_stderr(_("%s: invalid data in PID file \"%s\"\n"),
302 : : progname, pid_file);
7823 tgl@sss.pgh.pa.us 303 : 0 : exit(1);
304 : : }
8151 bruce@momjian.us 305 :CBC 4759 : fclose(pidf);
1429 peter@eisentraut.org 306 : 4759 : return (pid_t) pid;
307 : : }
308 : :
309 : :
310 : : /*
311 : : * get the lines from a text file - return NULL if file can't be opened
312 : : *
313 : : * Trailing newlines are deleted from the lines (this is a change from pre-v10)
314 : : *
315 : : * *numlines is set to the number of line pointers returned; there is
316 : : * also an additional NULL pointer after the last real line.
317 : : */
318 : : static char **
3371 tgl@sss.pgh.pa.us 319 : 3493 : readfile(const char *path, int *numlines)
320 : : {
321 : : int fd;
322 : : int nlines;
323 : : char **result;
324 : : size_t buflen;
325 : : char *buffer;
326 : : char *linebegin;
327 : : int n;
328 : : ssize_t nread;
329 : : struct stat statbuf;
330 : :
331 : 3493 : *numlines = 0; /* in case of failure or empty file */
332 : :
333 : : /*
334 : : * Slurp the file into memory.
335 : : *
336 : : * The file can change concurrently, so we read the whole file into memory
337 : : * with a single read() call. That's not guaranteed to get an atomic
338 : : * snapshot, but in practice, for a small file, it's close enough for the
339 : : * current use.
340 : : */
5090 heikki.linnakangas@i 341 : 3493 : fd = open(path, O_RDONLY | PG_BINARY, 0);
342 [ + + ]: 3493 : if (fd < 0)
343 : 965 : return NULL;
344 [ - + ]: 2528 : if (fstat(fd, &statbuf) < 0)
345 : : {
5085 heikki.linnakangas@i 346 :UBC 0 : close(fd);
8151 bruce@momjian.us 347 : 0 : return NULL;
348 : : }
5090 heikki.linnakangas@i 349 [ - + ]:CBC 2528 : if (statbuf.st_size == 0)
350 : : {
351 : : /* empty file */
5085 heikki.linnakangas@i 352 :UBC 0 : close(fd);
205 michael@paquier.xyz 353 : 0 : result = pg_malloc_object(char *);
5090 heikki.linnakangas@i 354 : 0 : *result = NULL;
355 : 0 : return result;
356 : : }
357 : :
67 peter@eisentraut.org 358 :GNC 2528 : buflen = statbuf.st_size + 1;
359 : 2528 : buffer = pg_malloc(buflen);
360 : :
361 : 2528 : nread = read(fd, buffer, buflen);
5090 heikki.linnakangas@i 362 :CBC 2528 : close(fd);
67 peter@eisentraut.org 363 [ - + ]:GNC 2528 : if (nread != buflen - 1)
364 : : {
365 : : /* oops, the file size changed between fstat and read */
81 peter@eisentraut.org 366 :UNC 0 : pg_free(buffer);
5090 heikki.linnakangas@i 367 :UBC 0 : return NULL;
368 : : }
369 : :
370 : : /*
371 : : * Count newlines. We expect there to be a newline after each full line,
372 : : * including one at the end of file. If there isn't a newline at the end,
373 : : * any characters after the last newline will be ignored.
374 : : */
5090 heikki.linnakangas@i 375 :CBC 2528 : nlines = 0;
67 peter@eisentraut.org 376 [ + + ]:GNC 513618 : for (ssize_t i = 0; i < nread; i++)
377 : : {
5090 heikki.linnakangas@i 378 [ + + ]:CBC 511090 : if (buffer[i] == '\n')
8151 bruce@momjian.us 379 : 19210 : nlines++;
380 : : }
381 : :
382 : : /* set up the result buffer */
205 michael@paquier.xyz 383 : 2528 : result = pg_malloc_array(char *, nlines + 1);
3371 tgl@sss.pgh.pa.us 384 : 2528 : *numlines = nlines;
385 : :
386 : : /* now split the buffer into lines */
5090 heikki.linnakangas@i 387 : 2528 : linebegin = buffer;
388 : 2528 : n = 0;
67 peter@eisentraut.org 389 [ + + ]:GNC 513618 : for (ssize_t i = 0; i < nread; i++)
390 : : {
5085 heikki.linnakangas@i 391 [ + + ]:CBC 511090 : if (buffer[i] == '\n')
392 : : {
3371 tgl@sss.pgh.pa.us 393 : 19210 : int slen = &buffer[i] - linebegin;
4862 bruce@momjian.us 394 : 19210 : char *linebuf = pg_malloc(slen + 1);
395 : :
5090 heikki.linnakangas@i 396 : 19210 : memcpy(linebuf, linebegin, slen);
397 : : /* we already dropped the \n, but get rid of any \r too */
3371 tgl@sss.pgh.pa.us 398 [ + + - + ]: 19210 : if (slen > 0 && linebuf[slen - 1] == '\r')
3371 tgl@sss.pgh.pa.us 399 :UBC 0 : slen--;
5090 heikki.linnakangas@i 400 :CBC 19210 : linebuf[slen] = '\0';
401 : 19210 : result[n++] = linebuf;
402 : 19210 : linebegin = &buffer[i + 1];
403 : : }
404 : : }
405 : 2528 : result[n] = NULL;
406 : :
81 peter@eisentraut.org 407 :GNC 2528 : pg_free(buffer);
408 : :
8151 bruce@momjian.us 409 :CBC 2528 : return result;
410 : : }
411 : :
412 : :
413 : : /*
414 : : * Free memory allocated for optlines through readfile()
415 : : */
416 : : static void
4586 sfrost@snowman.net 417 : 3493 : free_readfile(char **optlines)
418 : : {
4520 bruce@momjian.us 419 : 3493 : char *curr_line = NULL;
420 : 3493 : int i = 0;
421 : :
4586 sfrost@snowman.net 422 [ + + ]: 3493 : if (!optlines)
423 : 965 : return;
424 : :
4582 425 [ + + ]: 21738 : while ((curr_line = optlines[i++]))
426 : 19210 : free(curr_line);
427 : :
4586 428 : 2528 : free(optlines);
429 : : }
430 : :
431 : : /*
432 : : * start/test/stop routines
433 : : */
434 : :
435 : : /*
436 : : * Start the postmaster and return its PID.
437 : : *
438 : : * Currently, on Windows what we return is the PID of the shell process
439 : : * that launched the postmaster (and, we trust, is waiting for it to exit).
440 : : * So the PID is usable for "is the postmaster still running" checks,
441 : : * but cannot be compared directly to postmaster.pid.
442 : : *
443 : : * On Windows, we also save aside a handle to the shell process in
444 : : * "postmasterProcess", which the caller should close when done with it.
445 : : */
446 : : static pid_t
8151 bruce@momjian.us 447 : 933 : start_postmaster(void)
448 : : {
449 : : char *cmd;
450 : :
451 : : #ifndef WIN32
452 : : pid_t pm_pid;
453 : :
454 : : /* Flush stdio channels just before fork, to avoid double-output problems */
1483 tgl@sss.pgh.pa.us 455 : 933 : fflush(NULL);
456 : :
457 : : #ifdef EXEC_BACKEND
458 : : pg_disable_aslr();
459 : : #endif
460 : :
3996 461 : 933 : pm_pid = fork();
462 [ - + ]: 1866 : if (pm_pid < 0)
463 : : {
464 : : /* fork failed */
922 michael@paquier.xyz 465 :UBC 0 : write_stderr(_("%s: could not start server: %m\n"),
466 : : progname);
3996 tgl@sss.pgh.pa.us 467 : 0 : exit(1);
468 : : }
3996 tgl@sss.pgh.pa.us 469 [ + + ]:CBC 1866 : if (pm_pid > 0)
470 : : {
471 : : /* fork succeeded, in parent */
472 : 933 : return pm_pid;
473 : : }
474 : :
475 : : /* fork succeeded, in child */
476 : :
477 : : /*
478 : : * If possible, detach the postmaster process from the launching process
479 : : * group and make it a group leader, so that it doesn't get signaled along
480 : : * with the current group that launched it.
481 : : */
482 : : #ifdef HAVE_SETSID
2806 heikki.linnakangas@i 483 [ - + ]: 933 : if (setsid() < 0)
484 : : {
922 michael@paquier.xyz 485 :UBC 0 : write_stderr(_("%s: could not start server due to setsid() failure: %m\n"),
486 : : progname);
2806 heikki.linnakangas@i 487 : 0 : exit(1);
488 : : }
489 : : #endif
490 : :
491 : : /*
492 : : * Since there might be quotes to handle here, it is easier simply to pass
493 : : * everything to a shell to process them. Use exec so that the postmaster
494 : : * has the same PID as the current child process.
495 : : */
8151 bruce@momjian.us 496 [ + + ]:CBC 933 : if (log_file != NULL)
1843 tgl@sss.pgh.pa.us 497 : 921 : cmd = psprintf("exec \"%s\" %s%s < \"%s\" >> \"%s\" 2>&1",
498 : : exec_path, pgdata_opt, post_opts,
499 : : DEVNULL, log_file);
500 : : else
501 : 12 : cmd = psprintf("exec \"%s\" %s%s < \"%s\" 2>&1",
502 : : exec_path, pgdata_opt, post_opts, DEVNULL);
503 : :
3996 504 : 933 : (void) execl("/bin/sh", "/bin/sh", "-c", cmd, (char *) NULL);
505 : :
506 : : /* exec failed */
922 michael@paquier.xyz 507 : 933 : write_stderr(_("%s: could not start server: %m\n"),
508 : : progname);
3996 tgl@sss.pgh.pa.us 509 :UBC 0 : exit(1);
510 : :
511 : : return 0; /* keep dumb compilers quiet */
512 : :
513 : : #else /* WIN32 */
514 : :
515 : : /*
516 : : * As with the Unix case, it's easiest to use the shell (CMD.EXE) to
517 : : * handle redirection etc. Unfortunately CMD.EXE lacks any equivalent of
518 : : * "exec", so we don't get to find out the postmaster's PID immediately.
519 : : */
520 : : PROCESS_INFORMATION pi;
521 : : const char *comspec;
522 : :
523 : : /* Find CMD.EXE location using COMSPEC, if it's set */
524 : : comspec = getenv("COMSPEC");
525 : : if (comspec == NULL)
526 : : comspec = "CMD";
527 : :
528 : : if (log_file != NULL)
529 : : {
530 : : /*
531 : : * First, open the log file if it exists. The idea is that if the
532 : : * file is still locked by a previous postmaster run, we'll wait until
533 : : * it comes free, instead of failing with ERROR_SHARING_VIOLATION.
534 : : * (It'd be better to open the file in a sharing-friendly mode, but we
535 : : * can't use CMD.EXE to do that, so work around it. Note that the
536 : : * previous postmaster will still have the file open for a short time
537 : : * after removing postmaster.pid.)
538 : : *
539 : : * If the log file doesn't exist, we *must not* create it here. If we
540 : : * were launched with higher privileges than the restricted process
541 : : * will have, the log file might end up with permissions settings that
542 : : * prevent the postmaster from writing on it.
543 : : */
544 : : int fd = open(log_file, O_RDWR, 0);
545 : :
546 : : if (fd == -1)
547 : : {
548 : : /*
549 : : * ENOENT is expectable since we didn't use O_CREAT. Otherwise
550 : : * complain. We could just fall through and let CMD.EXE report
551 : : * the problem, but its error reporting is pretty miserable.
552 : : */
553 : : if (errno != ENOENT)
554 : : {
555 : : write_stderr(_("%s: could not open log file \"%s\": %m\n"),
556 : : progname, log_file);
557 : : exit(1);
558 : : }
559 : : }
560 : : else
561 : : close(fd);
562 : :
563 : : cmd = psprintf("\"%s\" /C \"\"%s\" %s%s < \"%s\" >> \"%s\" 2>&1\"",
564 : : comspec, exec_path, pgdata_opt, post_opts, DEVNULL, log_file);
565 : : }
566 : : else
567 : : cmd = psprintf("\"%s\" /C \"\"%s\" %s%s < \"%s\" 2>&1\"",
568 : : comspec, exec_path, pgdata_opt, post_opts, DEVNULL);
569 : :
570 : : if (!CreateRestrictedProcess(cmd, &pi, false))
571 : : {
572 : : write_stderr(_("%s: could not start server: error code %lu\n"),
573 : : progname, GetLastError());
574 : : exit(1);
575 : : }
576 : : /* Don't close command process handle here; caller must do so */
577 : : postmasterProcess = pi.hProcess;
578 : : CloseHandle(pi.hThread);
579 : : return pi.dwProcessId; /* Shell's PID, not postmaster's! */
580 : : #endif /* WIN32 */
581 : : }
582 : :
583 : :
584 : :
585 : : /*
586 : : * Wait for the postmaster to become ready.
587 : : *
588 : : * On Unix, pm_pid is the PID of the just-launched postmaster. On Windows,
589 : : * it may be the PID of an ancestor shell process, so we can't check the
590 : : * contents of postmaster.pid quite as carefully.
591 : : *
592 : : * On Windows, the static variable postmasterProcess is an implicit argument
593 : : * to this routine; it contains a handle to the postmaster process or an
594 : : * ancestor shell process thereof.
595 : : *
596 : : * Note that the checkpoint parameter enables a Windows service control
597 : : * manager checkpoint, it's got nothing to do with database checkpoints!!
598 : : */
599 : : static WaitPMResult
1429 peter@eisentraut.org 600 :CBC 933 : wait_for_postmaster_start(pid_t pm_pid, bool do_checkpoint)
601 : : {
602 : : int i;
603 : :
3373 tgl@sss.pgh.pa.us 604 [ + - ]: 3362 : for (i = 0; i < wait_seconds * WAITS_PER_SEC; i++)
605 : : {
606 : : char **optlines;
607 : : int numlines;
608 : :
609 : : /*
610 : : * Try to read the postmaster.pid file. If it's not valid, or if the
611 : : * status line isn't there yet, just keep waiting.
612 : : */
3371 613 [ + + ]: 3362 : if ((optlines = readfile(pid_file, &numlines)) != NULL &&
614 [ + + ]: 2397 : numlines >= LOCK_FILE_LINE_PM_STATUS)
615 : : {
616 : : /* File is complete enough for us, parse it */
617 : : pid_t pmpid;
618 : : time_t pmstart;
619 : :
620 : : /*
621 : : * Make sanity checks. If it's for the wrong PID, or the recorded
622 : : * start time is before pg_ctl started, then either we are looking
623 : : * at the wrong data directory, or this is a pre-existing pidfile
624 : : * that hasn't (yet?) been overwritten by our child postmaster.
625 : : * Allow 2 seconds slop for possible cross-process clock skew.
626 : : */
627 : 2302 : pmpid = atol(optlines[LOCK_FILE_LINE_PID - 1]);
713 nathan@postgresql.or 628 : 2302 : pmstart = atoll(optlines[LOCK_FILE_LINE_START_TIME - 1]);
3371 tgl@sss.pgh.pa.us 629 [ + + + + ]: 2302 : if (pmstart >= start_time - 2 &&
630 : : #ifndef WIN32
631 : : pmpid == pm_pid
632 : : #else
633 : : /* Windows can only reject standalone-backend PIDs */
634 : : pmpid > 0
635 : : #endif
636 : : )
637 : : {
638 : : /*
639 : : * OK, seems to be a valid pidfile from our child. Check the
640 : : * status line (this assumes a v10 or later server).
641 : : */
642 : 2293 : char *pmstatus = optlines[LOCK_FILE_LINE_PM_STATUS - 1];
643 : :
644 [ + + ]: 2293 : if (strcmp(pmstatus, PM_STATUS_READY) == 0 ||
645 [ + + ]: 1388 : strcmp(pmstatus, PM_STATUS_STANDBY) == 0)
646 : : {
647 : : /* postmaster is done starting up */
648 : 907 : free_readfile(optlines);
649 : 933 : return POSTMASTER_READY;
650 : : }
651 : : }
652 : : }
653 : :
654 : : /*
655 : : * Free the results of readfile.
656 : : *
657 : : * This is safe to call even if optlines is NULL.
658 : : */
659 : 2455 : free_readfile(optlines);
660 : :
661 : : /*
662 : : * Check whether the child postmaster process is still alive. This
663 : : * lets us exit early if the postmaster fails during startup.
664 : : *
665 : : * On Windows, we may be checking the postmaster's parent shell, but
666 : : * that's fine for this purpose.
667 : : */
668 : : {
669 : : bool pm_died;
670 : : #ifndef WIN32
671 : : int exitstatus;
672 : :
794 673 : 2455 : pm_died = (waitpid(pm_pid, &exitstatus, WNOHANG) == pm_pid);
674 : : #else
675 : : pm_died = (WaitForSingleObject(postmasterProcess, 0) == WAIT_OBJECT_0);
676 : : #endif
677 [ + + ]: 2455 : if (pm_died)
678 : : {
679 : : /* See if postmaster terminated intentionally */
680 [ + + ]: 26 : if (get_control_dbstate() == DB_SHUTDOWNED_IN_RECOVERY)
681 : 26 : return POSTMASTER_SHUTDOWN_IN_RECOVERY;
682 : : else
683 : 25 : return POSTMASTER_FAILED;
684 : : }
685 : : }
686 : :
687 : : /* Startup still in process; wait, printing a dot once per second */
3373 688 [ + + ]: 2429 : if (i % WAITS_PER_SEC == 0)
689 : : {
690 : : #ifdef WIN32
691 : : if (do_checkpoint)
692 : : {
693 : : /*
694 : : * Increment the wait hint by 6 secs (connection timeout +
695 : : * sleep). We must do this to indicate to the SCM that our
696 : : * startup time is changing, otherwise it'll usually send a
697 : : * stop signal after 20 seconds, despite incrementing the
698 : : * checkpoint counter.
699 : : */
700 : : status.dwWaitHint += 6000;
701 : : status.dwCheckPoint++;
702 : : SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
703 : : }
704 : : else
705 : : #endif
2093 bruce@momjian.us 706 : 956 : print_msg(".");
707 : : }
708 : :
320 alvherre@kurilemu.de 709 : 2429 : pg_usleep(USECS_PER_SEC / WAITS_PER_SEC);
710 : : }
711 : :
712 : : /* out of patience; report that postmaster is still starting up */
3371 tgl@sss.pgh.pa.us 713 :UBC 0 : return POSTMASTER_STILL_STARTING;
714 : : }
715 : :
716 : :
717 : : /*
718 : : * Wait for the postmaster to stop.
719 : : *
720 : : * Returns true if the postmaster stopped cleanly (i.e., removed its pidfile).
721 : : * Returns false if the postmaster dies uncleanly, or if we time out.
722 : : */
723 : : static bool
1683 tgl@sss.pgh.pa.us 724 :CBC 1006 : wait_for_postmaster_stop(void)
725 : : {
726 : : int cnt;
727 : :
728 [ + - ]: 4439 : for (cnt = 0; cnt < wait_seconds * WAITS_PER_SEC; cnt++)
729 : : {
730 : : pid_t pid;
731 : :
732 [ + + ]: 4439 : if ((pid = get_pgpid(false)) == 0)
733 : 1006 : return true; /* pid file is gone */
734 : :
1429 peter@eisentraut.org 735 [ - + ]: 3433 : if (kill(pid, 0) != 0)
736 : : {
737 : : /*
738 : : * Postmaster seems to have died. Check the pid file once more to
739 : : * avoid a race condition, but give up waiting.
740 : : */
1683 tgl@sss.pgh.pa.us 741 [ # # ]:UBC 0 : if (get_pgpid(false) == 0)
742 : 0 : return true; /* pid file is gone */
743 : 0 : return false; /* postmaster died untimely */
744 : : }
745 : :
1683 tgl@sss.pgh.pa.us 746 [ + + ]:CBC 3433 : if (cnt % WAITS_PER_SEC == 0)
747 : 987 : print_msg(".");
320 alvherre@kurilemu.de 748 : 3433 : pg_usleep(USECS_PER_SEC / WAITS_PER_SEC);
749 : : }
1683 tgl@sss.pgh.pa.us 750 :UBC 0 : return false; /* timeout reached */
751 : : }
752 : :
753 : :
754 : : /*
755 : : * Wait for the postmaster to promote.
756 : : *
757 : : * Returns true on success, else false.
758 : : * To avoid waiting uselessly, we check for postmaster death here too.
759 : : */
760 : : static bool
1683 tgl@sss.pgh.pa.us 761 :CBC 52 : wait_for_postmaster_promote(void)
762 : : {
763 : : int cnt;
764 : :
765 [ + - ]: 128 : for (cnt = 0; cnt < wait_seconds * WAITS_PER_SEC; cnt++)
766 : : {
767 : : pid_t pid;
768 : : DBState state;
769 : :
770 [ - + ]: 128 : if ((pid = get_pgpid(false)) == 0)
1683 tgl@sss.pgh.pa.us 771 :UBC 0 : return false; /* pid file is gone */
1429 peter@eisentraut.org 772 [ - + ]:CBC 128 : if (kill(pid, 0) != 0)
1683 tgl@sss.pgh.pa.us 773 :UBC 0 : return false; /* postmaster died */
774 : :
1683 tgl@sss.pgh.pa.us 775 :CBC 128 : state = get_control_dbstate();
776 [ + + ]: 128 : if (state == DB_IN_PRODUCTION)
777 : 52 : return true; /* successful promotion */
778 : :
779 [ + + ]: 76 : if (cnt % WAITS_PER_SEC == 0)
780 : 52 : print_msg(".");
320 alvherre@kurilemu.de 781 : 76 : pg_usleep(USECS_PER_SEC / WAITS_PER_SEC);
782 : : }
1683 tgl@sss.pgh.pa.us 783 :UBC 0 : return false; /* timeout reached */
784 : : }
785 : :
786 : :
787 : : #if defined(HAVE_GETRLIMIT)
788 : : static void
7198 andrew@dunslane.net 789 : 0 : unlimit_core_size(void)
790 : : {
791 : : struct rlimit lim;
792 : :
6884 bruce@momjian.us 793 : 0 : getrlimit(RLIMIT_CORE, &lim);
7198 andrew@dunslane.net 794 [ # # ]: 0 : if (lim.rlim_max == 0)
795 : : {
6884 bruce@momjian.us 796 : 0 : write_stderr(_("%s: cannot set core file size limit; disallowed by hard limit\n"),
797 : : progname);
798 : 0 : return;
799 : : }
7198 andrew@dunslane.net 800 [ # # # # ]: 0 : else if (lim.rlim_max == RLIM_INFINITY || lim.rlim_cur < lim.rlim_max)
801 : : {
802 : 0 : lim.rlim_cur = lim.rlim_max;
6884 bruce@momjian.us 803 : 0 : setrlimit(RLIMIT_CORE, &lim);
804 : : }
805 : : }
806 : : #endif
807 : :
808 : : static void
7020 magnus@hagander.net 809 :CBC 933 : read_post_opts(void)
810 : : {
8151 bruce@momjian.us 811 [ + + ]: 933 : if (post_opts == NULL)
812 : : {
6310 813 : 143 : post_opts = ""; /* default */
6660 814 [ + + ]: 143 : if (ctl_command == RESTART_COMMAND)
815 : : {
816 : : char **optlines;
817 : : int numlines;
818 : :
3371 tgl@sss.pgh.pa.us 819 : 130 : optlines = readfile(postopts_file, &numlines);
6660 bruce@momjian.us 820 [ - + ]: 130 : if (optlines == NULL)
821 : : {
8013 peter_e@gmx.net 822 :UBC 0 : write_stderr(_("%s: could not read file \"%s\"\n"), progname, postopts_file);
8151 bruce@momjian.us 823 : 0 : exit(1);
824 : : }
3371 tgl@sss.pgh.pa.us 825 [ - + ]:CBC 130 : else if (numlines != 1)
826 : : {
6660 bruce@momjian.us 827 :UBC 0 : write_stderr(_("%s: option file \"%s\" must have exactly one line\n"),
828 : : progname, postopts_file);
829 : 0 : exit(1);
830 : : }
831 : : else
832 : : {
833 : : char *optline;
834 : : char *arg1;
835 : :
6660 bruce@momjian.us 836 :CBC 130 : optline = optlines[0];
837 : :
838 : : /*
839 : : * Are we at the first option, as defined by space and
840 : : * double-quote?
841 : : */
842 [ + - ]: 130 : if ((arg1 = strstr(optline, " \"")) != NULL)
843 : : {
3378 tgl@sss.pgh.pa.us 844 : 130 : *arg1 = '\0'; /* terminate so we get only program name */
4520 bruce@momjian.us 845 : 130 : post_opts = pg_strdup(arg1 + 1); /* point past whitespace */
846 : : }
6128 peter_e@gmx.net 847 [ + - ]: 130 : if (exec_path == NULL)
4582 sfrost@snowman.net 848 : 130 : exec_path = pg_strdup(optline);
849 : : }
850 : :
851 : : /* Free the results of readfile. */
4586 852 : 130 : free_readfile(optlines);
853 : : }
854 : : }
7020 magnus@hagander.net 855 : 933 : }
856 : :
857 : : /*
858 : : * SIGINT signal handler used while waiting for postmaster to start up.
859 : : * Forwards the SIGINT to the postmaster process, asking it to shut down,
860 : : * before terminating pg_ctl itself. This way, if the user hits CTRL-C while
861 : : * waiting for the server to start up, the server launch is aborted.
862 : : */
863 : : static void
1467 tgl@sss.pgh.pa.us 864 :UBC 0 : trap_sigint_during_startup(SIGNAL_ARGS)
865 : : {
2806 heikki.linnakangas@i 866 [ # # ]: 0 : if (postmasterPID != -1)
867 : : {
868 [ # # ]: 0 : if (kill(postmasterPID, SIGINT) != 0)
922 michael@paquier.xyz 869 : 0 : write_stderr(_("%s: could not send stop signal (PID: %d): %m\n"),
870 : : progname, (int) postmasterPID);
871 : : }
872 : :
873 : : /*
874 : : * Clear the signal handler, and send the signal again, to terminate the
875 : : * process as normal.
876 : : */
159 andrew@dunslane.net 877 : 0 : pqsignal(postgres_signal_arg, PG_SIG_DFL);
1467 tgl@sss.pgh.pa.us 878 : 0 : raise(postgres_signal_arg);
2806 heikki.linnakangas@i 879 : 0 : }
880 : :
881 : : static char *
6128 peter_e@gmx.net 882 :CBC 804 : find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
883 : : {
884 : : int ret;
885 : : char *found_path;
886 : :
887 : 804 : found_path = pg_malloc(MAXPGPATH);
888 : :
889 [ - + ]: 804 : if ((ret = find_other_exec(argv0, target, versionstr, found_path)) < 0)
890 : : {
891 : : char full_path[MAXPGPATH];
892 : :
6128 peter_e@gmx.net 893 [ # # ]:UBC 0 : if (find_my_exec(argv0, full_path) < 0)
894 : 0 : strlcpy(full_path, progname, sizeof(full_path));
895 : :
896 [ # # ]: 0 : if (ret == -1)
1626 tgl@sss.pgh.pa.us 897 : 0 : write_stderr(_("program \"%s\" is needed by %s but was not found in the same directory as \"%s\"\n"),
898 : : target, progname, full_path);
899 : : else
900 : 0 : write_stderr(_("program \"%s\" was found by \"%s\" but was not the same version as %s\n"),
901 : : target, full_path, progname);
6128 peter_e@gmx.net 902 : 0 : exit(1);
903 : : }
904 : :
6128 peter_e@gmx.net 905 :CBC 804 : return found_path;
906 : : }
907 : :
908 : : static void
909 : 1 : do_init(void)
910 : : {
911 : : char *cmd;
912 : :
913 [ + - ]: 1 : if (exec_path == NULL)
914 : 1 : exec_path = find_other_exec_or_die(argv0, "initdb", "initdb (PostgreSQL) " PG_VERSION "\n");
915 : :
6123 itagaki.takahiro@gma 916 [ - + ]: 1 : if (pgdata_opt == NULL)
6123 itagaki.takahiro@gma 917 :UBC 0 : pgdata_opt = "";
918 : :
6128 peter_e@gmx.net 919 [ - + ]:CBC 1 : if (post_opts == NULL)
6128 peter_e@gmx.net 920 :UBC 0 : post_opts = "";
921 : :
6128 peter_e@gmx.net 922 [ + - ]:CBC 1 : if (!silent_mode)
1843 tgl@sss.pgh.pa.us 923 : 1 : cmd = psprintf("\"%s\" %s%s",
924 : : exec_path, pgdata_opt, post_opts);
925 : : else
1843 tgl@sss.pgh.pa.us 926 :UBC 0 : cmd = psprintf("\"%s\" %s%s > \"%s\"",
927 : : exec_path, pgdata_opt, post_opts, DEVNULL);
928 : :
1483 tgl@sss.pgh.pa.us 929 :CBC 1 : fflush(NULL);
6128 peter_e@gmx.net 930 [ - + ]: 1 : if (system(cmd) != 0)
931 : : {
6128 peter_e@gmx.net 932 :UBC 0 : write_stderr(_("%s: database system initialization failed\n"), progname);
933 : 0 : exit(1);
934 : : }
6128 peter_e@gmx.net 935 :CBC 1 : }
936 : :
937 : : static void
7020 magnus@hagander.net 938 : 934 : do_start(void)
939 : : {
1429 peter@eisentraut.org 940 : 934 : pid_t old_pid = 0;
941 : : pid_t pm_pid;
942 : :
7020 magnus@hagander.net 943 [ + + ]: 934 : if (ctl_command != RESTART_COMMAND)
944 : : {
2534 tgl@sss.pgh.pa.us 945 : 804 : old_pid = get_pgpid(false);
946 [ + + ]: 803 : if (old_pid != 0)
4892 peter_e@gmx.net 947 : 5 : write_stderr(_("%s: another server might be running; "
948 : : "trying to start server anyway\n"),
949 : : progname);
950 : : }
951 : :
7020 magnus@hagander.net 952 : 933 : read_post_opts();
953 : :
954 : : /* No -D or -D already added during server start */
8058 bruce@momjian.us 955 [ + + - + ]: 933 : if (ctl_command == RESTART_COMMAND || pgdata_opt == NULL)
8057 956 : 130 : pgdata_opt = "";
957 : :
6128 peter_e@gmx.net 958 [ + + ]: 933 : if (exec_path == NULL)
959 : 803 : exec_path = find_other_exec_or_die(argv0, "postgres", PG_BACKEND_VERSIONSTR);
960 : :
961 : : #if defined(HAVE_GETRLIMIT)
7198 andrew@dunslane.net 962 [ - + ]: 933 : if (allow_core_files)
7198 andrew@dunslane.net 963 :UBC 0 : unlimit_core_size();
964 : : #endif
965 : :
966 : : /*
967 : : * If possible, tell the postmaster our parent shell's PID (see the
968 : : * comments in CreateLockFile() for motivation). Windows hasn't got
969 : : * getppid() unfortunately.
970 : : */
971 : : #ifndef WIN32
972 : : {
973 : : char env_var[32];
974 : :
2090 tgl@sss.pgh.pa.us 975 :CBC 933 : snprintf(env_var, sizeof(env_var), "%d", (int) getppid());
976 : 933 : setenv("PG_GRANDPARENT_PID", env_var, 1);
977 : : }
978 : : #endif
979 : :
3996 980 : 933 : pm_pid = start_postmaster();
981 : :
8151 bruce@momjian.us 982 [ + - ]: 933 : if (do_wait)
983 : : {
984 : : /*
985 : : * If the user interrupts the startup (e.g. with CTRL-C), we'd like to
986 : : * abort the server launch. Install a signal handler that will
987 : : * forward SIGINT to the postmaster process, while we wait.
988 : : *
989 : : * (We don't bother to reset the signal handler after the launch, as
990 : : * we're about to exit, anyway.)
991 : : */
2806 heikki.linnakangas@i 992 : 933 : postmasterPID = pm_pid;
993 : 933 : pqsignal(SIGINT, trap_sigint_during_startup);
994 : :
7399 peter_e@gmx.net 995 : 933 : print_msg(_("waiting for server to start..."));
996 : :
1683 tgl@sss.pgh.pa.us 997 [ + - + + : 933 : switch (wait_for_postmaster_start(pm_pid, false))
- ]
998 : : {
3371 999 : 907 : case POSTMASTER_READY:
5776 1000 : 907 : print_msg(_(" done\n"));
1001 : 907 : print_msg(_("server started\n"));
1002 : 907 : break;
3371 tgl@sss.pgh.pa.us 1003 :UBC 0 : case POSTMASTER_STILL_STARTING:
5776 1004 : 0 : print_msg(_(" stopped waiting\n"));
3429 peter_e@gmx.net 1005 : 0 : write_stderr(_("%s: server did not start in time\n"),
1006 : : progname);
1007 : 0 : exit(1);
1008 : : break;
794 tgl@sss.pgh.pa.us 1009 :CBC 1 : case POSTMASTER_SHUTDOWN_IN_RECOVERY:
1010 : 1 : print_msg(_(" done\n"));
1011 : 1 : print_msg(_("server shut down because of recovery target settings\n"));
1012 : 1 : break;
3371 1013 : 25 : case POSTMASTER_FAILED:
5776 1014 : 25 : print_msg(_(" stopped waiting\n"));
1015 : 25 : write_stderr(_("%s: could not start server\n"
1016 : : "Examine the log output.\n"),
1017 : : progname);
1018 : 25 : exit(1);
1019 : : break;
1020 : : }
1021 : : }
1022 : : else
7399 peter_e@gmx.net 1023 :UBC 0 : print_msg(_("server starting\n"));
1024 : :
1025 : : #ifdef WIN32
1026 : : /* Now we don't need the handle to the shell process anymore */
1027 : : CloseHandle(postmasterProcess);
1028 : : postmasterProcess = INVALID_HANDLE_VALUE;
1029 : : #endif
8151 bruce@momjian.us 1030 :CBC 908 : }
1031 : :
1032 : :
1033 : : static void
1034 : 889 : do_stop(void)
1035 : : {
1036 : : pid_t pid;
1037 : :
4579 1038 : 889 : pid = get_pgpid(false);
1039 : :
8151 1040 [ + + ]: 889 : if (pid == 0) /* no pid file */
1041 : : {
8013 peter_e@gmx.net 1042 : 1 : write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
7399 1043 : 1 : write_stderr(_("Is server running?\n"));
8151 bruce@momjian.us 1044 : 1 : exit(1);
1045 : : }
1046 [ - + ]: 888 : else if (pid < 0) /* standalone backend, not postmaster */
1047 : : {
8151 bruce@momjian.us 1048 :UBC 0 : pid = -pid;
7399 peter_e@gmx.net 1049 : 0 : write_stderr(_("%s: cannot stop server; "
1050 : : "single-user server is running (PID: %d)\n"),
1051 : : progname, (int) pid);
8151 bruce@momjian.us 1052 : 0 : exit(1);
1053 : : }
1054 : :
1429 peter@eisentraut.org 1055 [ - + ]:CBC 888 : if (kill(pid, sig) != 0)
1056 : : {
922 michael@paquier.xyz 1057 :UBC 0 : write_stderr(_("%s: could not send stop signal (PID: %d): %m\n"), progname, (int) pid);
8151 bruce@momjian.us 1058 : 0 : exit(1);
1059 : : }
1060 : :
8151 bruce@momjian.us 1061 [ - + ]:CBC 888 : if (!do_wait)
1062 : : {
7399 peter_e@gmx.net 1063 :UBC 0 : print_msg(_("server shutting down\n"));
8151 bruce@momjian.us 1064 : 0 : return;
1065 : : }
1066 : : else
1067 : : {
3875 tgl@sss.pgh.pa.us 1068 :CBC 888 : print_msg(_("waiting for server to shut down..."));
1069 : :
1683 1070 [ - + ]: 888 : if (!wait_for_postmaster_stop())
1071 : : {
8010 neilc@samurai.com 1072 :UBC 0 : print_msg(_(" failed\n"));
1073 : :
3875 tgl@sss.pgh.pa.us 1074 : 0 : write_stderr(_("%s: server does not shut down\n"), progname);
5673 bruce@momjian.us 1075 [ # # ]: 0 : if (shutdown_mode == SMART_MODE)
5672 1076 : 0 : write_stderr(_("HINT: The \"-m fast\" option immediately disconnects sessions rather than\n"
1077 : : "waiting for session-initiated disconnection.\n"));
8151 1078 : 0 : exit(1);
1079 : : }
8010 neilc@samurai.com 1080 :CBC 888 : print_msg(_(" done\n"));
1081 : :
6057 peter_e@gmx.net 1082 : 888 : print_msg(_("server stopped\n"));
1083 : : }
1084 : : }
1085 : :
1086 : :
1087 : : /*
1088 : : * restart/reload routines
1089 : : */
1090 : :
1091 : : static void
8151 bruce@momjian.us 1092 : 130 : do_restart(void)
1093 : : {
1094 : : pid_t pid;
1095 : :
4579 1096 : 130 : pid = get_pgpid(false);
1097 : :
8151 1098 [ + + ]: 130 : if (pid == 0) /* no pid file */
1099 : : {
7809 tgl@sss.pgh.pa.us 1100 : 12 : write_stderr(_("%s: PID file \"%s\" does not exist\n"),
1101 : : progname, pid_file);
7399 peter_e@gmx.net 1102 : 12 : write_stderr(_("Is server running?\n"));
3244 1103 : 12 : write_stderr(_("trying to start server anyway\n"));
8151 bruce@momjian.us 1104 : 12 : do_start();
1105 : 6 : return;
1106 : : }
1107 [ - + ]: 118 : else if (pid < 0) /* standalone backend, not postmaster */
1108 : : {
8151 bruce@momjian.us 1109 :UBC 0 : pid = -pid;
1429 peter@eisentraut.org 1110 [ # # ]: 0 : if (postmaster_is_alive(pid))
1111 : : {
7399 peter_e@gmx.net 1112 : 0 : write_stderr(_("%s: cannot restart server; "
1113 : : "single-user server is running (PID: %d)\n"),
1114 : : progname, (int) pid);
1115 : 0 : write_stderr(_("Please terminate the single-user server and try again.\n"));
7809 tgl@sss.pgh.pa.us 1116 : 0 : exit(1);
1117 : : }
1118 : : }
1119 : :
1429 peter@eisentraut.org 1120 [ + - ]:CBC 118 : if (postmaster_is_alive(pid))
1121 : : {
1122 [ - + ]: 118 : if (kill(pid, sig) != 0)
1123 : : {
922 michael@paquier.xyz 1124 :UBC 0 : write_stderr(_("%s: could not send stop signal (PID: %d): %m\n"), progname, (int) pid);
7809 tgl@sss.pgh.pa.us 1125 : 0 : exit(1);
1126 : : }
1127 : :
7399 peter_e@gmx.net 1128 :CBC 118 : print_msg(_("waiting for server to shut down..."));
1129 : :
1130 : : /* always wait for restart */
1683 tgl@sss.pgh.pa.us 1131 [ - + ]: 118 : if (!wait_for_postmaster_stop())
1132 : : {
7809 tgl@sss.pgh.pa.us 1133 :UBC 0 : print_msg(_(" failed\n"));
1134 : :
7399 peter_e@gmx.net 1135 : 0 : write_stderr(_("%s: server does not shut down\n"), progname);
5673 bruce@momjian.us 1136 [ # # ]: 0 : if (shutdown_mode == SMART_MODE)
5672 1137 : 0 : write_stderr(_("HINT: The \"-m fast\" option immediately disconnects sessions rather than\n"
1138 : : "waiting for session-initiated disconnection.\n"));
7809 tgl@sss.pgh.pa.us 1139 : 0 : exit(1);
1140 : : }
1141 : :
7809 tgl@sss.pgh.pa.us 1142 :CBC 118 : print_msg(_(" done\n"));
6057 peter_e@gmx.net 1143 : 118 : print_msg(_("server stopped\n"));
1144 : : }
1145 : : else
1146 : : {
1429 peter@eisentraut.org 1147 :UBC 0 : write_stderr(_("%s: old server process (PID: %d) seems to be gone\n"),
1148 : : progname, (int) pid);
7399 peter_e@gmx.net 1149 : 0 : write_stderr(_("starting server anyway\n"));
1150 : : }
1151 : :
8151 bruce@momjian.us 1152 :CBC 118 : do_start();
1153 : : }
1154 : :
1155 : : static void
5583 peter_e@gmx.net 1156 : 131 : do_reload(void)
1157 : : {
1158 : : pid_t pid;
1159 : :
4579 bruce@momjian.us 1160 : 131 : pid = get_pgpid(false);
5583 peter_e@gmx.net 1161 [ - + ]: 131 : if (pid == 0) /* no pid file */
1162 : : {
5583 peter_e@gmx.net 1163 :UBC 0 : write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
1164 : 0 : write_stderr(_("Is server running?\n"));
1165 : 0 : exit(1);
1166 : : }
5583 peter_e@gmx.net 1167 [ - + ]:CBC 131 : else if (pid < 0) /* standalone backend, not postmaster */
1168 : : {
5583 peter_e@gmx.net 1169 :UBC 0 : pid = -pid;
1170 : 0 : write_stderr(_("%s: cannot reload server; "
1171 : : "single-user server is running (PID: %d)\n"),
1172 : : progname, (int) pid);
1173 : 0 : write_stderr(_("Please terminate the single-user server and try again.\n"));
1174 : 0 : exit(1);
1175 : : }
1176 : :
1429 peter@eisentraut.org 1177 [ - + ]:CBC 131 : if (kill(pid, sig) != 0)
1178 : : {
922 michael@paquier.xyz 1179 :UBC 0 : write_stderr(_("%s: could not send reload signal (PID: %d): %m\n"),
1180 : : progname, (int) pid);
5583 peter_e@gmx.net 1181 : 0 : exit(1);
1182 : : }
1183 : :
5583 peter_e@gmx.net 1184 :CBC 131 : print_msg(_("server signaled\n"));
1185 : 131 : }
1186 : :
1187 : :
1188 : : /*
1189 : : * promote
1190 : : */
1191 : :
1192 : : static void
5696 rhaas@postgresql.org 1193 : 56 : do_promote(void)
1194 : : {
1195 : : FILE *prmfile;
1196 : : pid_t pid;
1197 : :
4579 bruce@momjian.us 1198 : 56 : pid = get_pgpid(false);
1199 : :
5696 rhaas@postgresql.org 1200 [ + + ]: 55 : if (pid == 0) /* no pid file */
1201 : : {
1202 : 1 : write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
1203 : 1 : write_stderr(_("Is server running?\n"));
1204 : 1 : exit(1);
1205 : : }
1206 [ - + ]: 54 : else if (pid < 0) /* standalone backend, not postmaster */
1207 : : {
5696 rhaas@postgresql.org 1208 :UBC 0 : pid = -pid;
1209 : 0 : write_stderr(_("%s: cannot promote server; "
1210 : : "single-user server is running (PID: %d)\n"),
1211 : : progname, (int) pid);
1212 : 0 : exit(1);
1213 : : }
1214 : :
3708 peter_e@gmx.net 1215 [ + + ]:CBC 54 : if (get_control_dbstate() != DB_IN_ARCHIVE_RECOVERY)
1216 : : {
5696 rhaas@postgresql.org 1217 : 1 : write_stderr(_("%s: cannot promote server; "
1218 : : "server is not in standby mode\n"),
1219 : : progname);
1220 : 1 : exit(1);
1221 : : }
1222 : :
4780 heikki.linnakangas@i 1223 : 53 : snprintf(promote_file, MAXPGPATH, "%s/promote", pg_data);
1224 : :
5696 rhaas@postgresql.org 1225 [ - + ]: 53 : if ((prmfile = fopen(promote_file, "w")) == NULL)
1226 : : {
922 michael@paquier.xyz 1227 :UBC 0 : write_stderr(_("%s: could not create promote signal file \"%s\": %m\n"),
1228 : : progname, promote_file);
5696 rhaas@postgresql.org 1229 : 0 : exit(1);
1230 : : }
5696 rhaas@postgresql.org 1231 [ - + ]:CBC 53 : if (fclose(prmfile))
1232 : : {
922 michael@paquier.xyz 1233 :UBC 0 : write_stderr(_("%s: could not write promote signal file \"%s\": %m\n"),
1234 : : progname, promote_file);
5696 rhaas@postgresql.org 1235 : 0 : exit(1);
1236 : : }
1237 : :
5696 rhaas@postgresql.org 1238 :CBC 53 : sig = SIGUSR1;
1429 peter@eisentraut.org 1239 [ - + ]: 53 : if (kill(pid, sig) != 0)
1240 : : {
922 michael@paquier.xyz 1241 :UBC 0 : write_stderr(_("%s: could not send promote signal (PID: %d): %m\n"),
1242 : : progname, (int) pid);
5696 rhaas@postgresql.org 1243 [ # # ]: 0 : if (unlink(promote_file) != 0)
922 michael@paquier.xyz 1244 : 0 : write_stderr(_("%s: could not remove promote signal file \"%s\": %m\n"),
1245 : : progname, promote_file);
5696 rhaas@postgresql.org 1246 : 0 : exit(1);
1247 : : }
1248 : :
3698 peter_e@gmx.net 1249 [ + + ]:CBC 53 : if (do_wait)
1250 : : {
1251 : 52 : print_msg(_("waiting for server to promote..."));
1683 tgl@sss.pgh.pa.us 1252 [ + - ]: 52 : if (wait_for_postmaster_promote())
1253 : : {
3698 peter_e@gmx.net 1254 : 52 : print_msg(_(" done\n"));
1255 : 52 : print_msg(_("server promoted\n"));
1256 : : }
1257 : : else
1258 : : {
3698 peter_e@gmx.net 1259 :UBC 0 : print_msg(_(" stopped waiting\n"));
3429 1260 : 0 : write_stderr(_("%s: server did not promote in time\n"),
1261 : : progname);
1262 : 0 : exit(1);
1263 : : }
1264 : : }
1265 : : else
3698 peter_e@gmx.net 1266 :CBC 1 : print_msg(_("server promoting\n"));
5696 rhaas@postgresql.org 1267 : 53 : }
1268 : :
1269 : : /*
1270 : : * log rotate
1271 : : */
1272 : :
1273 : : static void
2941 akorotkov@postgresql 1274 : 1 : do_logrotate(void)
1275 : : {
1276 : : FILE *logrotatefile;
1277 : : pid_t pid;
1278 : :
1279 : 1 : pid = get_pgpid(false);
1280 : :
1281 [ - + ]: 1 : if (pid == 0) /* no pid file */
1282 : : {
2941 akorotkov@postgresql 1283 :UBC 0 : write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
1284 : 0 : write_stderr(_("Is server running?\n"));
1285 : 0 : exit(1);
1286 : : }
2941 akorotkov@postgresql 1287 [ - + ]:CBC 1 : else if (pid < 0) /* standalone backend, not postmaster */
1288 : : {
2941 akorotkov@postgresql 1289 :UBC 0 : pid = -pid;
1290 : 0 : write_stderr(_("%s: cannot rotate log file; "
1291 : : "single-user server is running (PID: %d)\n"),
1292 : : progname, (int) pid);
1293 : 0 : exit(1);
1294 : : }
1295 : :
2941 akorotkov@postgresql 1296 :CBC 1 : snprintf(logrotate_file, MAXPGPATH, "%s/logrotate", pg_data);
1297 : :
1298 [ - + ]: 1 : if ((logrotatefile = fopen(logrotate_file, "w")) == NULL)
1299 : : {
922 michael@paquier.xyz 1300 :UBC 0 : write_stderr(_("%s: could not create log rotation signal file \"%s\": %m\n"),
1301 : : progname, logrotate_file);
2941 akorotkov@postgresql 1302 : 0 : exit(1);
1303 : : }
2941 akorotkov@postgresql 1304 [ - + ]:CBC 1 : if (fclose(logrotatefile))
1305 : : {
922 michael@paquier.xyz 1306 :UBC 0 : write_stderr(_("%s: could not write log rotation signal file \"%s\": %m\n"),
1307 : : progname, logrotate_file);
2941 akorotkov@postgresql 1308 : 0 : exit(1);
1309 : : }
1310 : :
2941 akorotkov@postgresql 1311 :CBC 1 : sig = SIGUSR1;
1429 peter@eisentraut.org 1312 [ - + ]: 1 : if (kill(pid, sig) != 0)
1313 : : {
922 michael@paquier.xyz 1314 :UBC 0 : write_stderr(_("%s: could not send log rotation signal (PID: %d): %m\n"),
1315 : : progname, (int) pid);
2941 akorotkov@postgresql 1316 [ # # ]: 0 : if (unlink(logrotate_file) != 0)
922 michael@paquier.xyz 1317 : 0 : write_stderr(_("%s: could not remove log rotation signal file \"%s\": %m\n"),
1318 : : progname, logrotate_file);
2941 akorotkov@postgresql 1319 : 0 : exit(1);
1320 : : }
1321 : :
2941 akorotkov@postgresql 1322 :CBC 1 : print_msg(_("server signaled to rotate log file\n"));
1323 : 1 : }
1324 : :
1325 : :
1326 : : /*
1327 : : * utility routines
1328 : : */
1329 : :
1330 : : static bool
7823 tgl@sss.pgh.pa.us 1331 : 119 : postmaster_is_alive(pid_t pid)
1332 : : {
1333 : : /*
1334 : : * Test to see if the process is still there. Note that we do not
1335 : : * consider an EPERM failure to mean that the process is still there;
1336 : : * EPERM must mean that the given PID belongs to some other userid, and
1337 : : * considering the permissions on $PGDATA, that means it's not the
1338 : : * postmaster we are after.
1339 : : *
1340 : : * Don't believe that our own PID or parent shell's PID is the postmaster,
1341 : : * either. (Windows hasn't got getppid(), though.)
1342 : : */
1343 [ - + ]: 119 : if (pid == getpid())
7823 tgl@sss.pgh.pa.us 1344 :UBC 0 : return false;
1345 : : #ifndef WIN32
7823 tgl@sss.pgh.pa.us 1346 [ - + ]:CBC 119 : if (pid == getppid())
7823 tgl@sss.pgh.pa.us 1347 :UBC 0 : return false;
1348 : : #endif
7823 tgl@sss.pgh.pa.us 1349 [ + - ]:CBC 119 : if (kill(pid, 0) == 0)
1350 : 119 : return true;
7823 tgl@sss.pgh.pa.us 1351 :UBC 0 : return false;
1352 : : }
1353 : :
1354 : : static void
8151 bruce@momjian.us 1355 :CBC 3 : do_status(void)
1356 : : {
1357 : : pid_t pid;
1358 : :
4579 1359 : 3 : pid = get_pgpid(true);
1360 : : /* Is there a pid file? */
5456 1361 [ + + ]: 2 : if (pid != 0)
1362 : : {
1363 : : /* standalone backend? */
1364 [ - + ]: 1 : if (pid < 0)
1365 : : {
7823 tgl@sss.pgh.pa.us 1366 :UBC 0 : pid = -pid;
1429 peter@eisentraut.org 1367 [ # # ]: 0 : if (postmaster_is_alive(pid))
1368 : : {
1369 : 0 : printf(_("%s: single-user server is running (PID: %d)\n"),
1370 : : progname, (int) pid);
7823 tgl@sss.pgh.pa.us 1371 : 0 : return;
1372 : : }
1373 : : }
1374 : : else
1375 : : /* must be a postmaster */
1376 : : {
1429 peter@eisentraut.org 1377 [ + - ]:CBC 1 : if (postmaster_is_alive(pid))
1378 : : {
1379 : : char **optlines;
1380 : : char **curr_line;
1381 : : int numlines;
1382 : :
1383 : 1 : printf(_("%s: server is running (PID: %d)\n"),
1384 : : progname, (int) pid);
1385 : :
3371 tgl@sss.pgh.pa.us 1386 : 1 : optlines = readfile(postopts_file, &numlines);
7823 1387 [ + - ]: 1 : if (optlines != NULL)
1388 : : {
4582 sfrost@snowman.net 1389 [ + + ]: 2 : for (curr_line = optlines; *curr_line != NULL; curr_line++)
3371 tgl@sss.pgh.pa.us 1390 : 1 : puts(*curr_line);
1391 : :
1392 : : /* Free the results of readfile */
4586 sfrost@snowman.net 1393 : 1 : free_readfile(optlines);
1394 : : }
7823 tgl@sss.pgh.pa.us 1395 : 1 : return;
1396 : : }
1397 : : }
1398 : : }
7399 peter_e@gmx.net 1399 : 1 : printf(_("%s: no server running\n"), progname);
1400 : :
1401 : : /*
1402 : : * The Linux Standard Base Core Specification 3.1 says this should return
1403 : : * '3, program is not running'
1404 : : * https://refspecs.linuxbase.org/LSB_3.1.0/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
1405 : : */
5456 bruce@momjian.us 1406 : 1 : exit(3);
1407 : : }
1408 : :
1409 : :
1410 : :
1411 : : static void
1429 peter@eisentraut.org 1412 : 11 : do_kill(pid_t pid)
1413 : : {
1414 [ - + ]: 11 : if (kill(pid, sig) != 0)
1415 : : {
922 michael@paquier.xyz 1416 :UBC 0 : write_stderr(_("%s: could not send signal %d (PID: %d): %m\n"),
1417 : : progname, sig, (int) pid);
8151 bruce@momjian.us 1418 : 0 : exit(1);
1419 : : }
8151 bruce@momjian.us 1420 :CBC 11 : }
1421 : :
1422 : : #ifdef WIN32
1423 : :
1424 : : static bool
1425 : : pgwin32_IsInstalled(SC_HANDLE hSCM)
1426 : : {
1427 : : SC_HANDLE hService = OpenService(hSCM, register_servicename, SERVICE_QUERY_CONFIG);
1428 : : bool bResult = (hService != NULL);
1429 : :
1430 : : if (bResult)
1431 : : CloseServiceHandle(hService);
1432 : : return bResult;
1433 : : }
1434 : :
1435 : : static char *
1436 : : pgwin32_CommandLine(bool registration)
1437 : : {
1438 : : PQExpBuffer cmdLine = createPQExpBuffer();
1439 : : char cmdPath[MAXPGPATH];
1440 : : int ret;
1441 : :
1442 : : if (registration)
1443 : : {
1444 : : ret = find_my_exec(argv0, cmdPath);
1445 : : if (ret != 0)
1446 : : {
1447 : : write_stderr(_("%s: could not find own program executable\n"), progname);
1448 : : exit(1);
1449 : : }
1450 : : }
1451 : : else
1452 : : {
1453 : : ret = find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1454 : : cmdPath);
1455 : : if (ret != 0)
1456 : : {
1457 : : write_stderr(_("%s: could not find postgres program executable\n"), progname);
1458 : : exit(1);
1459 : : }
1460 : : }
1461 : :
1462 : : /* if path does not end in .exe, append it */
1463 : : if (strlen(cmdPath) < 4 ||
1464 : : pg_strcasecmp(cmdPath + strlen(cmdPath) - 4, ".exe") != 0)
1465 : : snprintf(cmdPath + strlen(cmdPath), sizeof(cmdPath) - strlen(cmdPath),
1466 : : ".exe");
1467 : :
1468 : : /* use backslashes in path to avoid problems with some third-party tools */
1469 : : make_native_path(cmdPath);
1470 : :
1471 : : /* be sure to double-quote the executable's name in the command */
1472 : : appendPQExpBuffer(cmdLine, "\"%s\"", cmdPath);
1473 : :
1474 : : /* append assorted switches to the command line, as needed */
1475 : :
1476 : : if (registration)
1477 : : appendPQExpBuffer(cmdLine, " runservice -N \"%s\"",
1478 : : register_servicename);
1479 : :
1480 : : if (pg_config)
1481 : : {
1482 : : /* We need the -D path to be absolute */
1483 : : char *dataDir;
1484 : :
1485 : : if ((dataDir = make_absolute_path(pg_config)) == NULL)
1486 : : {
1487 : : /* make_absolute_path already reported the error */
1488 : : exit(1);
1489 : : }
1490 : : make_native_path(dataDir);
1491 : : appendPQExpBuffer(cmdLine, " -D \"%s\"", dataDir);
1492 : : free(dataDir);
1493 : : }
1494 : :
1495 : : if (registration && event_source != NULL)
1496 : : appendPQExpBuffer(cmdLine, " -e \"%s\"", event_source);
1497 : :
1498 : : if (registration && do_wait)
1499 : : appendPQExpBufferStr(cmdLine, " -w");
1500 : :
1501 : : /* Don't propagate a value from an environment variable. */
1502 : : if (registration && wait_seconds_arg && wait_seconds != DEFAULT_WAIT)
1503 : : appendPQExpBuffer(cmdLine, " -t %d", wait_seconds);
1504 : :
1505 : : if (registration && silent_mode)
1506 : : appendPQExpBufferStr(cmdLine, " -s");
1507 : :
1508 : : if (post_opts)
1509 : : {
1510 : : if (registration)
1511 : : appendPQExpBuffer(cmdLine, " -o \"%s\"", post_opts);
1512 : : else
1513 : : appendPQExpBuffer(cmdLine, " %s", post_opts);
1514 : : }
1515 : :
1516 : : return cmdLine->data;
1517 : : }
1518 : :
1519 : : static void
1520 : : pgwin32_doRegister(void)
1521 : : {
1522 : : SC_HANDLE hService;
1523 : : SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
1524 : :
1525 : : if (hSCM == NULL)
1526 : : {
1527 : : write_stderr(_("%s: could not open service manager\n"), progname);
1528 : : exit(1);
1529 : : }
1530 : : if (pgwin32_IsInstalled(hSCM))
1531 : : {
1532 : : CloseServiceHandle(hSCM);
1533 : : write_stderr(_("%s: service \"%s\" already registered\n"), progname, register_servicename);
1534 : : exit(1);
1535 : : }
1536 : :
1537 : : if ((hService = CreateService(hSCM, register_servicename, register_servicename,
1538 : : SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
1539 : : pgctl_start_type, SERVICE_ERROR_NORMAL,
1540 : : pgwin32_CommandLine(true),
1541 : : NULL, NULL, "RPCSS\0", register_username, register_password)) == NULL)
1542 : : {
1543 : : CloseServiceHandle(hSCM);
1544 : : write_stderr(_("%s: could not register service \"%s\": error code %lu\n"),
1545 : : progname, register_servicename,
1546 : : GetLastError());
1547 : : exit(1);
1548 : : }
1549 : : CloseServiceHandle(hService);
1550 : : CloseServiceHandle(hSCM);
1551 : : }
1552 : :
1553 : : static void
1554 : : pgwin32_doUnregister(void)
1555 : : {
1556 : : SC_HANDLE hService;
1557 : : SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
1558 : :
1559 : : if (hSCM == NULL)
1560 : : {
1561 : : write_stderr(_("%s: could not open service manager\n"), progname);
1562 : : exit(1);
1563 : : }
1564 : : if (!pgwin32_IsInstalled(hSCM))
1565 : : {
1566 : : CloseServiceHandle(hSCM);
1567 : : write_stderr(_("%s: service \"%s\" not registered\n"), progname, register_servicename);
1568 : : exit(1);
1569 : : }
1570 : :
1571 : : if ((hService = OpenService(hSCM, register_servicename, DELETE)) == NULL)
1572 : : {
1573 : : CloseServiceHandle(hSCM);
1574 : : write_stderr(_("%s: could not open service \"%s\": error code %lu\n"),
1575 : : progname, register_servicename,
1576 : : GetLastError());
1577 : : exit(1);
1578 : : }
1579 : : if (!DeleteService(hService))
1580 : : {
1581 : : CloseServiceHandle(hService);
1582 : : CloseServiceHandle(hSCM);
1583 : : write_stderr(_("%s: could not unregister service \"%s\": error code %lu\n"),
1584 : : progname, register_servicename,
1585 : : GetLastError());
1586 : : exit(1);
1587 : : }
1588 : : CloseServiceHandle(hService);
1589 : : CloseServiceHandle(hSCM);
1590 : : }
1591 : :
1592 : : static void
1593 : : pgwin32_SetServiceStatus(DWORD currentState)
1594 : : {
1595 : : status.dwCurrentState = currentState;
1596 : : SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
1597 : : }
1598 : :
1599 : : static void WINAPI
1600 : : pgwin32_ServiceHandler(DWORD request)
1601 : : {
1602 : : switch (request)
1603 : : {
1604 : : case SERVICE_CONTROL_STOP:
1605 : : case SERVICE_CONTROL_SHUTDOWN:
1606 : :
1607 : : /*
1608 : : * We only need a short wait hint here as it just needs to wait
1609 : : * for the next checkpoint. They occur every 5 seconds during
1610 : : * shutdown
1611 : : */
1612 : : status.dwWaitHint = 10000;
1613 : : pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1614 : : SetEvent(shutdownEvent);
1615 : : return;
1616 : :
1617 : : case SERVICE_CONTROL_PAUSE:
1618 : : /* Win32 config reloading */
1619 : : status.dwWaitHint = 5000;
1620 : : kill(postmasterPID, SIGHUP);
1621 : : return;
1622 : :
1623 : : /* FIXME: These could be used to replace other signals etc */
1624 : : case SERVICE_CONTROL_CONTINUE:
1625 : : case SERVICE_CONTROL_INTERROGATE:
1626 : : default:
1627 : : break;
1628 : : }
1629 : : }
1630 : :
1631 : : static void WINAPI
1632 : : pgwin32_ServiceMain(DWORD argc, LPTSTR *argv)
1633 : : {
1634 : : PROCESS_INFORMATION pi;
1635 : : DWORD ret;
1636 : :
1637 : : /* Initialize variables */
1638 : : status.dwWin32ExitCode = S_OK;
1639 : : status.dwCheckPoint = 0;
1640 : : status.dwWaitHint = 60000;
1641 : : status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
1642 : : status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_PAUSE_CONTINUE;
1643 : : status.dwServiceSpecificExitCode = 0;
1644 : : status.dwCurrentState = SERVICE_START_PENDING;
1645 : :
1646 : : memset(&pi, 0, sizeof(pi));
1647 : :
1648 : : read_post_opts();
1649 : :
1650 : : /* Register the control request handler */
1651 : : if ((hStatus = RegisterServiceCtrlHandler(register_servicename, pgwin32_ServiceHandler)) == (SERVICE_STATUS_HANDLE) 0)
1652 : : return;
1653 : :
1654 : : if ((shutdownEvent = CreateEvent(NULL, true, false, NULL)) == NULL)
1655 : : return;
1656 : :
1657 : : /* Start the postmaster */
1658 : : pgwin32_SetServiceStatus(SERVICE_START_PENDING);
1659 : : if (!CreateRestrictedProcess(pgwin32_CommandLine(false), &pi, true))
1660 : : {
1661 : : pgwin32_SetServiceStatus(SERVICE_STOPPED);
1662 : : return;
1663 : : }
1664 : : postmasterPID = pi.dwProcessId;
1665 : : postmasterProcess = pi.hProcess;
1666 : : CloseHandle(pi.hThread);
1667 : :
1668 : : if (do_wait)
1669 : : {
1670 : : write_eventlog(EVENTLOG_INFORMATION_TYPE, _("Waiting for server startup...\n"));
1671 : : if (wait_for_postmaster_start(postmasterPID, true) != POSTMASTER_READY)
1672 : : {
1673 : : write_eventlog(EVENTLOG_ERROR_TYPE, _("Timed out waiting for server startup\n"));
1674 : : pgwin32_SetServiceStatus(SERVICE_STOPPED);
1675 : : return;
1676 : : }
1677 : : write_eventlog(EVENTLOG_INFORMATION_TYPE, _("Server started and accepting connections\n"));
1678 : : }
1679 : :
1680 : : pgwin32_SetServiceStatus(SERVICE_RUNNING);
1681 : :
1682 : : /* Wait for quit... */
1683 : : ret = WaitForMultipleObjects(2, shutdownHandles, FALSE, INFINITE);
1684 : :
1685 : : pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1686 : : switch (ret)
1687 : : {
1688 : : case WAIT_OBJECT_0: /* shutdown event */
1689 : : {
1690 : : /*
1691 : : * status.dwCheckPoint can be incremented by
1692 : : * wait_for_postmaster_start(), so it might not start from 0.
1693 : : */
1694 : : int maxShutdownCheckPoint = status.dwCheckPoint + 12;
1695 : :
1696 : : kill(postmasterPID, SIGINT);
1697 : :
1698 : : /*
1699 : : * Increment the checkpoint and try again. Abort after 12
1700 : : * checkpoints as the postmaster has probably hung.
1701 : : */
1702 : : while (WaitForSingleObject(postmasterProcess, 5000) == WAIT_TIMEOUT && status.dwCheckPoint < maxShutdownCheckPoint)
1703 : : {
1704 : : status.dwCheckPoint++;
1705 : : SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
1706 : : }
1707 : : break;
1708 : : }
1709 : :
1710 : : case (WAIT_OBJECT_0 + 1): /* postmaster went down */
1711 : : break;
1712 : :
1713 : : default:
1714 : : /* shouldn't get here? */
1715 : : break;
1716 : : }
1717 : :
1718 : : CloseHandle(shutdownEvent);
1719 : : CloseHandle(postmasterProcess);
1720 : :
1721 : : pgwin32_SetServiceStatus(SERVICE_STOPPED);
1722 : : }
1723 : :
1724 : : static void
1725 : : pgwin32_doRunAsService(void)
1726 : : {
1727 : : SERVICE_TABLE_ENTRY st[] = {{register_servicename, pgwin32_ServiceMain},
1728 : : {NULL, NULL}};
1729 : :
1730 : : if (StartServiceCtrlDispatcher(st) == 0)
1731 : : {
1732 : : write_stderr(_("%s: could not start service \"%s\": error code %lu\n"),
1733 : : progname, register_servicename,
1734 : : GetLastError());
1735 : : exit(1);
1736 : : }
1737 : : }
1738 : :
1739 : :
1740 : : /*
1741 : : * Set up STARTUPINFO for the new process to inherit this process' handles.
1742 : : *
1743 : : * Process started as services appear to have "empty" handles (GetStdHandle()
1744 : : * returns NULL) rather than invalid ones. But passing down NULL ourselves
1745 : : * doesn't work, it's interpreted as STARTUPINFO->hStd* not being set. But we
1746 : : * can pass down INVALID_HANDLE_VALUE - which makes GetStdHandle() in the new
1747 : : * process (and its child processes!) return INVALID_HANDLE_VALUE. Which
1748 : : * achieves the goal of postmaster running in a similar environment as pg_ctl.
1749 : : */
1750 : : static void
1751 : : InheritStdHandles(STARTUPINFO *si)
1752 : : {
1753 : : si->dwFlags |= STARTF_USESTDHANDLES;
1754 : : si->hStdInput = GetStdHandle(STD_INPUT_HANDLE);
1755 : : if (si->hStdInput == NULL)
1756 : : si->hStdInput = INVALID_HANDLE_VALUE;
1757 : : si->hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
1758 : : if (si->hStdOutput == NULL)
1759 : : si->hStdOutput = INVALID_HANDLE_VALUE;
1760 : : si->hStdError = GetStdHandle(STD_ERROR_HANDLE);
1761 : : if (si->hStdError == NULL)
1762 : : si->hStdError = INVALID_HANDLE_VALUE;
1763 : : }
1764 : :
1765 : : /*
1766 : : * Create a restricted token, a job object sandbox, and execute the specified
1767 : : * process with it.
1768 : : *
1769 : : * Returns 0 on success, non-zero on failure, same as CreateProcess().
1770 : : *
1771 : : * NOTE! Job object will only work when running as a service, because it's
1772 : : * automatically destroyed when pg_ctl exits.
1773 : : */
1774 : : static int
1775 : : CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, bool as_service)
1776 : : {
1777 : : int r;
1778 : : BOOL b;
1779 : : STARTUPINFO si;
1780 : : HANDLE origToken;
1781 : : HANDLE restrictedToken;
1782 : : BOOL inJob;
1783 : : SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
1784 : : SID_AND_ATTRIBUTES dropSids[2];
1785 : : PTOKEN_PRIVILEGES delPrivs;
1786 : :
1787 : : ZeroMemory(&si, sizeof(si));
1788 : : si.cb = sizeof(si);
1789 : :
1790 : : /*
1791 : : * Set stdin/stdout/stderr handles to be inherited in the child process.
1792 : : * That allows postmaster and the processes it starts to perform
1793 : : * additional checks to see if running in a service (otherwise they get
1794 : : * the default console handles - which point to "somewhere").
1795 : : */
1796 : : InheritStdHandles(&si);
1797 : :
1798 : : /* Open the current token to use as a base for the restricted one */
1799 : : if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken))
1800 : : {
1801 : : /*
1802 : : * Most Windows targets make DWORD a 32-bit unsigned long, but in case
1803 : : * it doesn't cast DWORD before printing.
1804 : : */
1805 : : write_stderr(_("%s: could not open process token: error code %lu\n"),
1806 : : progname, GetLastError());
1807 : : return 0;
1808 : : }
1809 : :
1810 : : /* Allocate list of SIDs to remove */
1811 : : ZeroMemory(&dropSids, sizeof(dropSids));
1812 : : if (!AllocateAndInitializeSid(&NtAuthority, 2,
1813 : : SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0,
1814 : : 0, &dropSids[0].Sid) ||
1815 : : !AllocateAndInitializeSid(&NtAuthority, 2,
1816 : : SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0,
1817 : : 0, &dropSids[1].Sid))
1818 : : {
1819 : : write_stderr(_("%s: could not allocate SIDs: error code %lu\n"),
1820 : : progname, GetLastError());
1821 : : return 0;
1822 : : }
1823 : :
1824 : : /* Get list of privileges to remove */
1825 : : delPrivs = GetPrivilegesToDelete(origToken);
1826 : : if (delPrivs == NULL)
1827 : : /* Error message already printed */
1828 : : return 0;
1829 : :
1830 : : b = CreateRestrictedToken(origToken,
1831 : : 0,
1832 : : sizeof(dropSids) / sizeof(dropSids[0]),
1833 : : dropSids,
1834 : : delPrivs->PrivilegeCount, delPrivs->Privileges,
1835 : : 0, NULL,
1836 : : &restrictedToken);
1837 : :
1838 : : free(delPrivs);
1839 : : FreeSid(dropSids[1].Sid);
1840 : : FreeSid(dropSids[0].Sid);
1841 : : CloseHandle(origToken);
1842 : :
1843 : : if (!b)
1844 : : {
1845 : : write_stderr(_("%s: could not create restricted token: error code %lu\n"),
1846 : : progname, GetLastError());
1847 : : return 0;
1848 : : }
1849 : :
1850 : : AddUserToTokenDacl(restrictedToken);
1851 : : r = CreateProcessAsUser(restrictedToken, NULL, cmd, NULL, NULL, TRUE, CREATE_SUSPENDED, NULL, NULL, &si, processInfo);
1852 : :
1853 : : if (IsProcessInJob(processInfo->hProcess, NULL, &inJob))
1854 : : {
1855 : : if (!inJob)
1856 : : {
1857 : : /*
1858 : : * Job objects are working, and the new process isn't in one, so
1859 : : * we can create one safely. If any problems show up when setting
1860 : : * it, we're going to ignore them.
1861 : : */
1862 : : HANDLE job;
1863 : : char jobname[128];
1864 : :
1865 : : sprintf(jobname, "PostgreSQL_%lu", processInfo->dwProcessId);
1866 : :
1867 : : job = CreateJobObject(NULL, jobname);
1868 : : if (job)
1869 : : {
1870 : : JOBOBJECT_BASIC_LIMIT_INFORMATION basicLimit;
1871 : : JOBOBJECT_BASIC_UI_RESTRICTIONS uiRestrictions;
1872 : : JOBOBJECT_SECURITY_LIMIT_INFORMATION securityLimit;
1873 : :
1874 : : ZeroMemory(&basicLimit, sizeof(basicLimit));
1875 : : ZeroMemory(&uiRestrictions, sizeof(uiRestrictions));
1876 : : ZeroMemory(&securityLimit, sizeof(securityLimit));
1877 : :
1878 : : basicLimit.LimitFlags = JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION | JOB_OBJECT_LIMIT_PRIORITY_CLASS;
1879 : : basicLimit.PriorityClass = NORMAL_PRIORITY_CLASS;
1880 : : SetInformationJobObject(job, JobObjectBasicLimitInformation, &basicLimit, sizeof(basicLimit));
1881 : :
1882 : : uiRestrictions.UIRestrictionsClass = JOB_OBJECT_UILIMIT_DESKTOP | JOB_OBJECT_UILIMIT_DISPLAYSETTINGS |
1883 : : JOB_OBJECT_UILIMIT_EXITWINDOWS | JOB_OBJECT_UILIMIT_READCLIPBOARD |
1884 : : JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS | JOB_OBJECT_UILIMIT_WRITECLIPBOARD;
1885 : :
1886 : : SetInformationJobObject(job, JobObjectBasicUIRestrictions, &uiRestrictions, sizeof(uiRestrictions));
1887 : :
1888 : : securityLimit.SecurityLimitFlags = JOB_OBJECT_SECURITY_NO_ADMIN | JOB_OBJECT_SECURITY_ONLY_TOKEN;
1889 : : securityLimit.JobToken = restrictedToken;
1890 : : SetInformationJobObject(job, JobObjectSecurityLimitInformation, &securityLimit, sizeof(securityLimit));
1891 : :
1892 : : AssignProcessToJobObject(job, processInfo->hProcess);
1893 : : }
1894 : : }
1895 : : }
1896 : :
1897 : : CloseHandle(restrictedToken);
1898 : :
1899 : : ResumeThread(processInfo->hThread);
1900 : :
1901 : : /*
1902 : : * We intentionally don't close the job object handle, because we want the
1903 : : * object to live on until pg_ctl shuts down.
1904 : : */
1905 : : return r;
1906 : : }
1907 : :
1908 : : /*
1909 : : * Get a list of privileges to delete from the access token. We delete all privileges
1910 : : * except SeLockMemoryPrivilege which is needed to use large pages, and
1911 : : * SeChangeNotifyPrivilege which is enabled by default in DISABLE_MAX_PRIVILEGE.
1912 : : */
1913 : : static PTOKEN_PRIVILEGES
1914 : : GetPrivilegesToDelete(HANDLE hToken)
1915 : : {
1916 : : DWORD length;
1917 : : PTOKEN_PRIVILEGES tokenPrivs;
1918 : : LUID luidLockPages;
1919 : : LUID luidChangeNotify;
1920 : :
1921 : : if (!LookupPrivilegeValue(NULL, SE_LOCK_MEMORY_NAME, &luidLockPages) ||
1922 : : !LookupPrivilegeValue(NULL, SE_CHANGE_NOTIFY_NAME, &luidChangeNotify))
1923 : : {
1924 : : write_stderr(_("%s: could not get LUIDs for privileges: error code %lu\n"),
1925 : : progname, GetLastError());
1926 : : return NULL;
1927 : : }
1928 : :
1929 : : if (!GetTokenInformation(hToken, TokenPrivileges, NULL, 0, &length) &&
1930 : : GetLastError() != ERROR_INSUFFICIENT_BUFFER)
1931 : : {
1932 : : write_stderr(_("%s: could not get token information: error code %lu\n"),
1933 : : progname, GetLastError());
1934 : : return NULL;
1935 : : }
1936 : :
1937 : : tokenPrivs = (PTOKEN_PRIVILEGES) pg_malloc_extended(length,
1938 : : MCXT_ALLOC_NO_OOM);
1939 : : if (tokenPrivs == NULL)
1940 : : {
1941 : : write_stderr(_("%s: out of memory\n"), progname);
1942 : : return NULL;
1943 : : }
1944 : :
1945 : : if (!GetTokenInformation(hToken, TokenPrivileges, tokenPrivs, length, &length))
1946 : : {
1947 : : write_stderr(_("%s: could not get token information: error code %lu\n"),
1948 : : progname, GetLastError());
1949 : : free(tokenPrivs);
1950 : : return NULL;
1951 : : }
1952 : :
1953 : : for (DWORD i = 0; i < tokenPrivs->PrivilegeCount; i++)
1954 : : {
1955 : : if (memcmp(&tokenPrivs->Privileges[i].Luid, &luidLockPages, sizeof(LUID)) == 0 ||
1956 : : memcmp(&tokenPrivs->Privileges[i].Luid, &luidChangeNotify, sizeof(LUID)) == 0)
1957 : : {
1958 : : for (DWORD j = i; j < tokenPrivs->PrivilegeCount - 1; j++)
1959 : : tokenPrivs->Privileges[j] = tokenPrivs->Privileges[j + 1];
1960 : : tokenPrivs->PrivilegeCount--;
1961 : : }
1962 : : }
1963 : :
1964 : : return tokenPrivs;
1965 : : }
1966 : : #endif /* WIN32 */
1967 : :
1968 : : static void
1969 : 1 : do_advice(void)
1970 : : {
8006 peter_e@gmx.net 1971 : 1 : write_stderr(_("Try \"%s --help\" for more information.\n"), progname);
8151 bruce@momjian.us 1972 : 1 : }
1973 : :
1974 : :
1975 : :
1976 : : static void
1977 : 1 : do_help(void)
1978 : : {
5583 peter_e@gmx.net 1979 : 1 : printf(_("%s is a utility to initialize, start, stop, or control a PostgreSQL server.\n\n"), progname);
8151 bruce@momjian.us 1980 : 1 : printf(_("Usage:\n"));
2941 akorotkov@postgresql 1981 : 1 : printf(_(" %s init[db] [-D DATADIR] [-s] [-o OPTIONS]\n"), progname);
1982 : 1 : printf(_(" %s start [-D DATADIR] [-l FILENAME] [-W] [-t SECS] [-s]\n"
1983 : : " [-o OPTIONS] [-p PATH] [-c]\n"), progname);
1984 : 1 : printf(_(" %s stop [-D DATADIR] [-m SHUTDOWN-MODE] [-W] [-t SECS] [-s]\n"), progname);
1985 : 1 : printf(_(" %s restart [-D DATADIR] [-m SHUTDOWN-MODE] [-W] [-t SECS] [-s]\n"
1986 : : " [-o OPTIONS] [-c]\n"), progname);
1987 : 1 : printf(_(" %s reload [-D DATADIR] [-s]\n"), progname);
1988 : 1 : printf(_(" %s status [-D DATADIR]\n"), progname);
1989 : 1 : printf(_(" %s promote [-D DATADIR] [-W] [-t SECS] [-s]\n"), progname);
1990 : 1 : printf(_(" %s logrotate [-D DATADIR] [-s]\n"), progname);
1991 : 1 : printf(_(" %s kill SIGNALNAME PID\n"), progname);
1992 : : #ifdef WIN32
1993 : : printf(_(" %s register [-D DATADIR] [-N SERVICENAME] [-U USERNAME] [-P PASSWORD]\n"
1994 : : " [-S START-TYPE] [-e SOURCE] [-W] [-t SECS] [-s] [-o OPTIONS]\n"), progname);
1995 : : printf(_(" %s unregister [-N SERVICENAME]\n"), progname);
1996 : : #endif
1997 : :
8006 peter_e@gmx.net 1998 : 1 : printf(_("\nCommon options:\n"));
5242 1999 : 1 : printf(_(" -D, --pgdata=DATADIR location of the database storage area\n"));
2000 : : #ifdef WIN32
2001 : : printf(_(" -e SOURCE event source for logging when running as a service\n"));
2002 : : #endif
4012 2003 : 1 : printf(_(" -s, --silent only print errors, no informational messages\n"));
5242 2004 : 1 : printf(_(" -t, --timeout=SECS seconds to wait when using -w option\n"));
5207 2005 : 1 : printf(_(" -V, --version output version information, then exit\n"));
3537 2006 : 1 : printf(_(" -w, --wait wait until operation completes (default)\n"));
3623 2007 : 1 : printf(_(" -W, --no-wait do not wait until operation completes\n"));
5207 2008 : 1 : printf(_(" -?, --help show this help, then exit\n"));
8006 2009 : 1 : printf(_("If the -D option is omitted, the environment variable PGDATA is used.\n"));
2010 : :
2011 : 1 : printf(_("\nOptions for start or restart:\n"));
2012 : : #if defined(HAVE_GETRLIMIT)
7198 andrew@dunslane.net 2013 : 1 : printf(_(" -c, --core-files allow postgres to produce core files\n"));
2014 : : #else
2015 : : printf(_(" -c, --core-files not applicable on this platform\n"));
2016 : : #endif
5242 peter_e@gmx.net 2017 : 1 : printf(_(" -l, --log=FILENAME write (or append) server log to FILENAME\n"));
3623 2018 : 1 : printf(_(" -o, --options=OPTIONS command line options to pass to postgres\n"
2019 : : " (PostgreSQL server executable) or initdb\n"));
6416 2020 : 1 : printf(_(" -p PATH-TO-POSTGRES normally not necessary\n"));
4420 fujii@postgresql.org 2021 : 1 : printf(_("\nOptions for stop or restart:\n"));
5242 peter_e@gmx.net 2022 : 1 : printf(_(" -m, --mode=MODE MODE can be \"smart\", \"fast\", or \"immediate\"\n"));
2023 : :
8006 2024 : 1 : printf(_("\nShutdown modes are:\n"));
8151 bruce@momjian.us 2025 : 1 : printf(_(" smart quit after all clients have disconnected\n"));
3440 tgl@sss.pgh.pa.us 2026 : 1 : printf(_(" fast quit directly, with proper shutdown (default)\n"));
8006 peter_e@gmx.net 2027 : 1 : printf(_(" immediate quit without complete shutdown; will lead to recovery on restart\n"));
2028 : :
2029 : 1 : printf(_("\nAllowed signal names for kill:\n"));
3276 andres@anarazel.de 2030 : 1 : printf(" ABRT HUP INT KILL QUIT TERM USR1 USR2\n");
2031 : :
2032 : : #ifdef WIN32
2033 : : printf(_("\nOptions for register and unregister:\n"));
2034 : : printf(_(" -N SERVICENAME service name with which to register PostgreSQL server\n"));
2035 : : printf(_(" -P PASSWORD password of account to register PostgreSQL server\n"));
2036 : : printf(_(" -U USERNAME user name of account to register PostgreSQL server\n"));
2037 : : printf(_(" -S START-TYPE service start type to register PostgreSQL server\n"));
2038 : :
2039 : : printf(_("\nStart types are:\n"));
2040 : : printf(_(" auto start service automatically during system startup (default)\n"));
2041 : : printf(_(" demand start service on demand\n"));
2042 : : #endif
2043 : :
2396 peter@eisentraut.org 2044 : 1 : printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
2045 : 1 : printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
8151 bruce@momjian.us 2046 : 1 : }
2047 : :
2048 : :
2049 : :
2050 : : static void
2051 : 766 : set_mode(char *modeopt)
2052 : : {
2053 [ + - + + ]: 766 : if (strcmp(modeopt, "s") == 0 || strcmp(modeopt, "smart") == 0)
2054 : : {
2055 : 50 : shutdown_mode = SMART_MODE;
2056 : 50 : sig = SIGTERM;
2057 : : }
2058 [ + - + + ]: 716 : else if (strcmp(modeopt, "f") == 0 || strcmp(modeopt, "fast") == 0)
2059 : : {
2060 : 353 : shutdown_mode = FAST_MODE;
2061 : 353 : sig = SIGINT;
2062 : : }
2063 [ + - + - ]: 363 : else if (strcmp(modeopt, "i") == 0 || strcmp(modeopt, "immediate") == 0)
2064 : : {
2065 : 363 : shutdown_mode = IMMEDIATE_MODE;
2066 : 363 : sig = SIGQUIT;
2067 : : }
2068 : : else
2069 : : {
8013 peter_e@gmx.net 2070 :UBC 0 : write_stderr(_("%s: unrecognized shutdown mode \"%s\"\n"), progname, modeopt);
8151 bruce@momjian.us 2071 : 0 : do_advice();
2072 : 0 : exit(1);
2073 : : }
8151 bruce@momjian.us 2074 :CBC 766 : }
2075 : :
2076 : :
2077 : :
2078 : : static void
2079 : 11 : set_sig(char *signame)
2080 : : {
5381 peter_e@gmx.net 2081 [ - + ]: 11 : if (strcmp(signame, "HUP") == 0)
8151 bruce@momjian.us 2082 :UBC 0 : sig = SIGHUP;
5381 peter_e@gmx.net 2083 [ + + ]:CBC 11 : else if (strcmp(signame, "INT") == 0)
8151 bruce@momjian.us 2084 : 5 : sig = SIGINT;
5381 peter_e@gmx.net 2085 [ + + ]: 6 : else if (strcmp(signame, "QUIT") == 0)
8151 bruce@momjian.us 2086 : 2 : sig = SIGQUIT;
5381 peter_e@gmx.net 2087 [ - + ]: 4 : else if (strcmp(signame, "ABRT") == 0)
8151 bruce@momjian.us 2088 :UBC 0 : sig = SIGABRT;
5215 bruce@momjian.us 2089 [ + - ]:CBC 4 : else if (strcmp(signame, "KILL") == 0)
5381 peter_e@gmx.net 2090 : 4 : sig = SIGKILL;
5381 peter_e@gmx.net 2091 [ # # ]:UBC 0 : else if (strcmp(signame, "TERM") == 0)
8151 bruce@momjian.us 2092 : 0 : sig = SIGTERM;
5381 peter_e@gmx.net 2093 [ # # ]: 0 : else if (strcmp(signame, "USR1") == 0)
8151 bruce@momjian.us 2094 : 0 : sig = SIGUSR1;
5381 peter_e@gmx.net 2095 [ # # ]: 0 : else if (strcmp(signame, "USR2") == 0)
8151 bruce@momjian.us 2096 : 0 : sig = SIGUSR2;
2097 : : else
2098 : : {
8013 peter_e@gmx.net 2099 : 0 : write_stderr(_("%s: unrecognized signal name \"%s\"\n"), progname, signame);
8151 bruce@momjian.us 2100 : 0 : do_advice();
2101 : 0 : exit(1);
2102 : : }
8151 bruce@momjian.us 2103 :CBC 11 : }
2104 : :
2105 : :
2106 : : #ifdef WIN32
2107 : : static void
2108 : : set_starttype(char *starttypeopt)
2109 : : {
2110 : : if (strcmp(starttypeopt, "a") == 0 || strcmp(starttypeopt, "auto") == 0)
2111 : : pgctl_start_type = SERVICE_AUTO_START;
2112 : : else if (strcmp(starttypeopt, "d") == 0 || strcmp(starttypeopt, "demand") == 0)
2113 : : pgctl_start_type = SERVICE_DEMAND_START;
2114 : : else
2115 : : {
2116 : : write_stderr(_("%s: unrecognized start type \"%s\"\n"), progname, starttypeopt);
2117 : : do_advice();
2118 : : exit(1);
2119 : : }
2120 : : }
2121 : : #endif
2122 : :
2123 : : /*
2124 : : * adjust_data_dir
2125 : : *
2126 : : * If a configuration-only directory was specified, find the real data dir.
2127 : : */
2128 : : static void
5463 2129 : 2026 : adjust_data_dir(void)
2130 : : {
2131 : : char filename[MAXPGPATH];
2132 : : char *my_exec_path,
2133 : : *cmd;
2134 : : FILE *fd;
2135 : :
2136 : : /* do nothing if we're working without knowledge of data dir */
5214 tgl@sss.pgh.pa.us 2137 [ + + ]: 2026 : if (pg_config == NULL)
2138 : 2026 : return;
2139 : :
2140 : : /* If there is no postgresql.conf, it can't be a config-only dir */
5463 bruce@momjian.us 2141 : 2015 : snprintf(filename, sizeof(filename), "%s/postgresql.conf", pg_config);
2142 [ + + ]: 2015 : if ((fd = fopen(filename, "r")) == NULL)
2143 : 4 : return;
2144 : 2011 : fclose(fd);
2145 : :
2146 : : /* If PG_VERSION exists, it can't be a config-only dir */
2147 : 2011 : snprintf(filename, sizeof(filename), "%s/PG_VERSION", pg_config);
2148 [ + - ]: 2011 : if ((fd = fopen(filename, "r")) != NULL)
2149 : : {
2150 : 2011 : fclose(fd);
2151 : 2011 : return;
2152 : : }
2153 : :
2154 : : /* Must be a configuration directory, so find the data directory */
2155 : :
2156 : : /* we use a private my_exec_path to avoid interfering with later uses */
5463 bruce@momjian.us 2157 [ # # ]:UBC 0 : if (exec_path == NULL)
2158 : 0 : my_exec_path = find_other_exec_or_die(argv0, "postgres", PG_BACKEND_VERSIONSTR);
2159 : : else
5101 tgl@sss.pgh.pa.us 2160 : 0 : my_exec_path = pg_strdup(exec_path);
2161 : :
2162 : : /* it's important for -C to be the first option, see main.c */
1843 2163 : 0 : cmd = psprintf("\"%s\" -C data_directory %s%s",
2164 : : my_exec_path,
2165 [ # # ]: 0 : pgdata_opt ? pgdata_opt : "",
2166 [ # # ]: 0 : post_opts ? post_opts : "");
1483 2167 : 0 : fflush(NULL);
2168 : :
5463 bruce@momjian.us 2169 : 0 : fd = popen(cmd, "r");
1405 peter@eisentraut.org 2170 [ # # # # : 0 : if (fd == NULL || fgets(filename, sizeof(filename), fd) == NULL || pclose(fd) != 0)
# # ]
2171 : : {
5193 peter_e@gmx.net 2172 : 0 : write_stderr(_("%s: could not determine the data directory using command \"%s\"\n"), progname, cmd);
5463 bruce@momjian.us 2173 : 0 : exit(1);
2174 : : }
81 peter@eisentraut.org 2175 :UNC 0 : pg_free(my_exec_path);
2176 : :
2177 : : /* strip trailing newline and carriage return */
2599 michael@paquier.xyz 2178 :UBC 0 : (void) pg_strip_crlf(filename);
2179 : :
81 peter@eisentraut.org 2180 :UNC 0 : pg_free(pg_data);
5101 tgl@sss.pgh.pa.us 2181 :UBC 0 : pg_data = pg_strdup(filename);
5463 bruce@momjian.us 2182 : 0 : canonicalize_path(pg_data);
2183 : : }
2184 : :
2185 : :
2186 : : static DBState
3708 peter_e@gmx.net 2187 :CBC 208 : get_control_dbstate(void)
2188 : : {
2189 : : DBState ret;
2190 : : bool crc_ok;
2729 peter@eisentraut.org 2191 : 208 : ControlFileData *control_file_data = get_controlfile(pg_data, &crc_ok);
2192 : :
3644 peter_e@gmx.net 2193 [ - + ]: 208 : if (!crc_ok)
2194 : : {
3708 peter_e@gmx.net 2195 :UBC 0 : write_stderr(_("%s: control file appears to be corrupt\n"), progname);
2196 : 0 : exit(1);
2197 : : }
2198 : :
3644 peter_e@gmx.net 2199 :CBC 208 : ret = control_file_data->state;
2200 : 208 : pfree(control_file_data);
2201 : 208 : return ret;
2202 : : }
2203 : :
2204 : :
2205 : : int
8151 bruce@momjian.us 2206 : 2127 : main(int argc, char **argv)
2207 : : {
2208 : : static struct option long_options[] = {
2209 : : {"help", no_argument, NULL, '?'},
2210 : : {"version", no_argument, NULL, 'V'},
2211 : : {"log", required_argument, NULL, 'l'},
2212 : : {"mode", required_argument, NULL, 'm'},
2213 : : {"pgdata", required_argument, NULL, 'D'},
2214 : : {"options", required_argument, NULL, 'o'},
2215 : : {"silent", no_argument, NULL, 's'},
2216 : : {"timeout", required_argument, NULL, 't'},
2217 : : {"core-files", no_argument, NULL, 'c'},
2218 : : {"wait", no_argument, NULL, 'w'},
2219 : : {"no-wait", no_argument, NULL, 'W'},
2220 : : {NULL, 0, NULL, 0}
2221 : : };
2222 : :
2223 : : char *env_wait;
2224 : : int option_index;
2225 : : int c;
1429 peter@eisentraut.org 2226 : 2127 : pid_t killproc = 0;
2227 : :
2729 2228 : 2127 : pg_logging_init(argv[0]);
8151 bruce@momjian.us 2229 : 2127 : progname = get_progname(argv[0]);
6492 peter_e@gmx.net 2230 : 2127 : set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_ctl"));
5742 bruce@momjian.us 2231 : 2127 : start_time = time(NULL);
2232 : :
2233 : : /*
2234 : : * save argv[0] so do_start() can look for the postmaster if necessary. we
2235 : : * don't look for postmaster here because in many cases we won't need it.
2236 : : */
8151 2237 : 2127 : argv0 = argv[0];
2238 : :
2239 : : /* Set restrictive mode mask until PGDATA permissions are checked */
3088 sfrost@snowman.net 2240 : 2127 : umask(PG_MODE_MASK_OWNER);
2241 : :
2242 : : /* support --help and --version even if invoked as root */
8057 bruce@momjian.us 2243 [ + - ]: 2127 : if (argc > 1)
2244 : : {
4829 2245 [ + + - + ]: 2127 : if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2246 : : {
8151 2247 : 1 : do_help();
2248 : 1 : exit(0);
2249 : : }
4829 2250 [ + + + + ]: 2126 : else if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
2251 : : {
7530 peter_e@gmx.net 2252 : 99 : puts("pg_ctl (PostgreSQL) " PG_VERSION);
8151 bruce@momjian.us 2253 : 99 : exit(0);
2254 : : }
2255 : : }
2256 : :
2257 : : /*
2258 : : * Disallow running as root, to forestall any possible security holes.
2259 : : */
2260 : : #ifndef WIN32
8003 tgl@sss.pgh.pa.us 2261 [ - + ]: 2027 : if (geteuid() == 0)
2262 : : {
8003 tgl@sss.pgh.pa.us 2263 :UBC 0 : write_stderr(_("%s: cannot be run as root\n"
2264 : : "Please log in (using, e.g., \"su\") as the "
2265 : : "(unprivileged) user that will\n"
2266 : : "own the server process.\n"),
2267 : : progname);
2268 : 0 : exit(1);
2269 : : }
2270 : : #endif
2271 : :
3875 noah@leadboat.com 2272 :CBC 2027 : env_wait = getenv("PGCTLTIMEOUT");
2273 [ - + ]: 2027 : if (env_wait != NULL)
3875 noah@leadboat.com 2274 :UBC 0 : wait_seconds = atoi(env_wait);
2275 : :
2276 : : /* process command-line options */
1164 nathan@postgresql.or 2277 :CBC 7765 : while ((c = getopt_long(argc, argv, "cD:e:l:m:N:o:p:P:sS:t:U:wW",
2278 [ + + ]: 7765 : long_options, &option_index)) != -1)
2279 : : {
2280 [ + - + + : 5739 : switch (c)
- + - - +
- + - + +
- + ]
2281 : : {
2282 : 2015 : case 'D':
2283 : : {
2284 : : char *pgdata_D;
2285 : :
2286 : 2015 : pgdata_D = pg_strdup(optarg);
2287 : 2015 : canonicalize_path(pgdata_D);
2288 : 2015 : setenv("PGDATA", pgdata_D, 1);
2289 : :
2290 : : /*
2291 : : * We could pass PGDATA just in an environment variable
2292 : : * but we do -D too for clearer postmaster 'ps' display
2293 : : */
2294 : 2015 : pgdata_opt = psprintf("-D \"%s\" ", pgdata_D);
81 peter@eisentraut.org 2295 :GNC 2015 : pg_free(pgdata_D);
8151 bruce@momjian.us 2296 :CBC 2015 : break;
2297 : : }
1164 nathan@postgresql.or 2298 :UBC 0 : case 'e':
2299 : : #ifdef WIN32
1164 nathan@postgresql.or 2300 :EUB : event_source = pg_strdup(optarg);
2301 : : #else
9 peter@eisentraut.org 2302 :UNC 0 : write_stderr(_("%s: -%c option not supported on this platform\n"),
2303 : : progname, c);
2304 : 0 : exit(1);
2305 : : #endif
1164 nathan@postgresql.or 2306 :EUB : break;
1164 nathan@postgresql.or 2307 :CBC 972 : case 'l':
2308 : 972 : log_file = pg_strdup(optarg);
2309 : 972 : break;
2310 : 766 : case 'm':
2311 : 766 : set_mode(optarg);
2312 : 766 : break;
1164 nathan@postgresql.or 2313 :UBC 0 : case 'N':
2314 : : #ifdef WIN32
1164 nathan@postgresql.or 2315 :EUB : register_servicename = pg_strdup(optarg);
2316 : : #else
9 peter@eisentraut.org 2317 :UNC 0 : write_stderr(_("%s: -%c option not supported on this platform\n"),
2318 : : progname, c);
2319 : 0 : exit(1);
2320 : : #endif
1164 nathan@postgresql.or 2321 :EUB : break;
1164 nathan@postgresql.or 2322 :CBC 889 : case 'o':
2323 : : /* append option? */
2324 [ + + ]: 889 : if (!post_opts)
2325 : 849 : post_opts = pg_strdup(optarg);
2326 : : else
2327 : : {
2328 : 40 : char *old_post_opts = post_opts;
2329 : :
2330 : 40 : post_opts = psprintf("%s %s", old_post_opts, optarg);
2331 : 40 : free(old_post_opts);
2332 : : }
2333 : 889 : break;
1164 nathan@postgresql.or 2334 :UBC 0 : case 'p':
2335 : 0 : exec_path = pg_strdup(optarg);
2336 : 0 : break;
2337 : 0 : case 'P':
2338 : : #ifdef WIN32
1164 nathan@postgresql.or 2339 :EUB : register_password = pg_strdup(optarg);
2340 : : #else
9 peter@eisentraut.org 2341 :UNC 0 : write_stderr(_("%s: -%c option not supported on this platform\n"),
2342 : : progname, c);
2343 : 0 : exit(1);
2344 : : #endif
1164 nathan@postgresql.or 2345 :EUB : break;
1164 nathan@postgresql.or 2346 :CBC 130 : case 's':
2347 : 130 : silent_mode = true;
2348 : 130 : break;
1164 nathan@postgresql.or 2349 :UBC 0 : case 'S':
2350 : : #ifdef WIN32
2351 : : set_starttype(optarg);
2352 : : #else
9 peter@eisentraut.org 2353 :UNC 0 : write_stderr(_("%s: -%c option not supported on this platform\n"),
2354 : : progname, c);
1164 nathan@postgresql.or 2355 :UBC 0 : exit(1);
2356 : : #endif
2357 : : break;
1164 nathan@postgresql.or 2358 :CBC 1 : case 't':
2359 : 1 : wait_seconds = atoi(optarg);
2360 : : #ifdef WIN32
1164 nathan@postgresql.or 2361 :ECB (1) : wait_seconds_arg = true;
2362 : : #endif
1164 nathan@postgresql.or 2363 :CBC 1 : break;
1164 nathan@postgresql.or 2364 :UBC 0 : case 'U':
2365 : : #ifdef WIN32
1164 nathan@postgresql.or 2366 [ # # ]:EUB : if (strchr(optarg, '\\'))
2367 : : register_username = pg_strdup(optarg);
2368 : : else
2369 : : /* Prepend .\ for local accounts */
2370 : : register_username = psprintf(".\\%s", optarg);
2371 : : #else
9 peter@eisentraut.org 2372 :UNC 0 : write_stderr(_("%s: -%c option not supported on this platform\n"),
2373 : : progname, c);
2374 : 0 : exit(1);
2375 : : #endif
1164 nathan@postgresql.or 2376 :EUB : break;
1164 nathan@postgresql.or 2377 :CBC 964 : case 'w':
2378 : 964 : do_wait = true;
2379 : 964 : break;
2380 : 1 : case 'W':
2381 : 1 : do_wait = false;
2382 : 1 : break;
1164 nathan@postgresql.or 2383 :UBC 0 : case 'c':
2384 : 0 : allow_core_files = true;
2385 : 0 : break;
1164 nathan@postgresql.or 2386 :CBC 1 : default:
2387 : : /* getopt_long already issued a suitable error message */
2388 : 1 : do_advice();
2389 : 1 : exit(1);
2390 : : }
2391 : : }
2392 : :
2393 : : /* Process an action */
2394 [ + - ]: 2026 : if (optind < argc)
2395 : : {
2396 [ + - ]: 2026 : if (strcmp(argv[optind], "init") == 0
2397 [ + + ]: 2026 : || strcmp(argv[optind], "initdb") == 0)
2398 : 1 : ctl_command = INIT_COMMAND;
2399 [ + + ]: 2025 : else if (strcmp(argv[optind], "start") == 0)
2400 : 804 : ctl_command = START_COMMAND;
2401 [ + + ]: 1221 : else if (strcmp(argv[optind], "stop") == 0)
2402 : 889 : ctl_command = STOP_COMMAND;
2403 [ + + ]: 332 : else if (strcmp(argv[optind], "restart") == 0)
2404 : 130 : ctl_command = RESTART_COMMAND;
2405 [ + + ]: 202 : else if (strcmp(argv[optind], "reload") == 0)
2406 : 131 : ctl_command = RELOAD_COMMAND;
2407 [ + + ]: 71 : else if (strcmp(argv[optind], "status") == 0)
2408 : 3 : ctl_command = STATUS_COMMAND;
2409 [ + + ]: 68 : else if (strcmp(argv[optind], "promote") == 0)
2410 : 56 : ctl_command = PROMOTE_COMMAND;
2411 [ + + ]: 12 : else if (strcmp(argv[optind], "logrotate") == 0)
2412 : 1 : ctl_command = LOGROTATE_COMMAND;
2413 [ + - ]: 11 : else if (strcmp(argv[optind], "kill") == 0)
2414 : : {
2415 [ - + ]: 11 : if (argc - optind < 3)
2416 : : {
1164 nathan@postgresql.or 2417 :UBC 0 : write_stderr(_("%s: missing arguments for kill mode\n"), progname);
8151 bruce@momjian.us 2418 : 0 : do_advice();
2419 : 0 : exit(1);
2420 : : }
1164 nathan@postgresql.or 2421 :CBC 11 : ctl_command = KILL_COMMAND;
2422 : 11 : set_sig(argv[++optind]);
2423 : 11 : killproc = atol(argv[++optind]);
2424 : : }
2425 : : #ifdef WIN32
2426 : : else if (strcmp(argv[optind], "register") == 0)
2427 : : ctl_command = REGISTER_COMMAND;
2428 : : else if (strcmp(argv[optind], "unregister") == 0)
2429 : : ctl_command = UNREGISTER_COMMAND;
2430 : : else if (strcmp(argv[optind], "runservice") == 0)
2431 : : ctl_command = RUN_AS_SERVICE_COMMAND;
2432 : : #endif
2433 : : else
2434 : : {
1164 nathan@postgresql.or 2435 :UBC 0 : write_stderr(_("%s: unrecognized operation mode \"%s\"\n"), progname, argv[optind]);
2436 : 0 : do_advice();
2437 : 0 : exit(1);
2438 : : }
1164 nathan@postgresql.or 2439 :CBC 2026 : optind++;
2440 : : }
2441 : :
2442 [ - + ]: 2026 : if (optind < argc)
2443 : : {
1164 nathan@postgresql.or 2444 :UBC 0 : write_stderr(_("%s: too many command-line arguments (first is \"%s\")\n"), progname, argv[optind]);
2445 : 0 : do_advice();
2446 : 0 : exit(1);
2447 : : }
2448 : :
8151 bruce@momjian.us 2449 [ - + ]:CBC 2026 : if (ctl_command == NO_COMMAND)
2450 : : {
8123 tgl@sss.pgh.pa.us 2451 :UBC 0 : write_stderr(_("%s: no operation specified\n"), progname);
8151 bruce@momjian.us 2452 : 0 : do_advice();
2453 : 0 : exit(1);
2454 : : }
2455 : :
2456 : : /* Note we put any -D switch into the env var above */
5463 bruce@momjian.us 2457 :CBC 2026 : pg_config = getenv("PGDATA");
2458 [ + + ]: 2026 : if (pg_config)
2459 : : {
5101 tgl@sss.pgh.pa.us 2460 : 2015 : pg_config = pg_strdup(pg_config);
5463 bruce@momjian.us 2461 : 2015 : canonicalize_path(pg_config);
5101 tgl@sss.pgh.pa.us 2462 : 2015 : pg_data = pg_strdup(pg_config);
2463 : : }
2464 : :
2465 : : /* -D might point at config-only directory; if so find the real PGDATA */
5463 bruce@momjian.us 2466 : 2026 : adjust_data_dir();
2467 : :
2468 : : /* Complain if -D needed and not provided */
2469 [ + + ]: 2026 : if (pg_config == NULL &&
8123 tgl@sss.pgh.pa.us 2470 [ - + - - ]: 11 : ctl_command != KILL_COMMAND && ctl_command != UNREGISTER_COMMAND)
2471 : : {
5819 alvherre@alvh.no-ip. 2472 :UBC 0 : write_stderr(_("%s: no database directory specified and environment variable PGDATA unset\n"),
2473 : : progname);
8151 bruce@momjian.us 2474 : 0 : do_advice();
2475 : 0 : exit(1);
2476 : : }
2477 : :
8151 bruce@momjian.us 2478 [ + + ]:CBC 2026 : if (ctl_command == RELOAD_COMMAND)
2479 : : {
2480 : 131 : sig = SIGHUP;
2481 : 131 : do_wait = false;
2482 : : }
2483 : :
7291 2484 [ + + ]: 2026 : if (pg_data)
2485 : : {
2486 : 2015 : snprintf(postopts_file, MAXPGPATH, "%s/postmaster.opts", pg_data);
4579 2487 : 2015 : snprintf(version_file, MAXPGPATH, "%s/PG_VERSION", pg_data);
7291 2488 : 2015 : snprintf(pid_file, MAXPGPATH, "%s/postmaster.pid", pg_data);
2489 : :
2490 : : /*
2491 : : * Set mask based on PGDATA permissions,
2492 : : *
2493 : : * Don't error here if the data directory cannot be stat'd. This is
2494 : : * handled differently based on the command and we don't want to
2495 : : * interfere with that logic.
2496 : : */
3088 sfrost@snowman.net 2497 [ + + ]: 2015 : if (GetDataDirectoryCreatePerm(pg_data))
2498 : 2011 : umask(pg_mode_mask);
2499 : : }
2500 : :
8151 bruce@momjian.us 2501 [ + + + + : 2026 : switch (ctl_command)
+ + + + +
- ]
2502 : : {
6128 peter_e@gmx.net 2503 : 1 : case INIT_COMMAND:
2504 : 1 : do_init();
2505 : 1 : break;
8151 bruce@momjian.us 2506 : 3 : case STATUS_COMMAND:
2507 : 3 : do_status();
2508 : 1 : break;
2509 : 804 : case START_COMMAND:
2510 : 804 : do_start();
2511 : 790 : break;
2512 : 889 : case STOP_COMMAND:
2513 : 889 : do_stop();
2514 : 888 : break;
2515 : 130 : case RESTART_COMMAND:
2516 : 130 : do_restart();
2517 : 118 : break;
2518 : 131 : case RELOAD_COMMAND:
2519 : 131 : do_reload();
2520 : 131 : break;
5583 peter_e@gmx.net 2521 : 56 : case PROMOTE_COMMAND:
2522 : 56 : do_promote();
2523 : 53 : break;
2941 akorotkov@postgresql 2524 : 1 : case LOGROTATE_COMMAND:
2525 : 1 : do_logrotate();
2526 : 1 : break;
8151 bruce@momjian.us 2527 : 11 : case KILL_COMMAND:
8147 2528 : 11 : do_kill(killproc);
8151 2529 : 11 : break;
2530 : : #ifdef WIN32
2531 : : case REGISTER_COMMAND:
2532 : : pgwin32_doRegister();
2533 : : break;
2534 : : case UNREGISTER_COMMAND:
2535 : : pgwin32_doUnregister();
2536 : : break;
2537 : : case RUN_AS_SERVICE_COMMAND:
2538 : : pgwin32_doRunAsService();
2539 : : break;
2540 : : #endif
8151 bruce@momjian.us 2541 :UBC 0 : default:
2542 : 0 : break;
2543 : : }
2544 : :
8151 bruce@momjian.us 2545 :CBC 1994 : exit(0);
2546 : : }
|